web_stack_test.py 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558
  1. #!/usr/bin/env python3
  2. """Self-contained web-stack feature tests: app + fake saddle daemon.
  3. Unlike integration_test.py (which needs a real saddle daemon and a mock
  4. LLM), this suite spawns everything it needs:
  5. - the clanker-saddle app binary (path from argv[1], or builddir default)
  6. in a scratch directory with its own web-config.json (statum keys copied
  7. from the repo, plus `saddle_callback_base_url`) and SQLite database
  8. - an in-process fake saddle daemon speaking the wire contract: POST
  9. /start (captures the payload), GET /status (scripted state machine),
  10. GET /output (empty), GET /log?since= (raw PTY chunks, one new chunk
  11. per request so since-paging is exercised)
  12. It then drives the app the way statum.js does (entrypoint loads + action
  13. POSTs) and asserts the Workstream B features against the wire contract:
  14. 3. plan-review blocks hide their duplicate body preview
  15. 5. rules CRUD/attach + the effective `rules` array in /start
  16. 6. project notes, POST /api/saddle/note, `project_notes` + `callback`
  17. in /start
  18. plus the raw-log side: session_raw_log polling + terminal raw view
  19. Prints PASS/FAIL lines Statum-style; exits non-zero on any failure.
  20. """
  21. import json
  22. import os
  23. import shutil
  24. import socket
  25. import sqlite3
  26. import subprocess
  27. import sys
  28. import threading
  29. import time
  30. import urllib.error
  31. import urllib.parse
  32. import urllib.request
  33. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  34. REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  35. APP = os.path.abspath(sys.argv[1]) if len(sys.argv) > 1 else os.path.join(REPO, "builddir", "clanker-saddle")
  36. WORK = os.environ.get("WEBSTACK_WORK", "/tmp/kilo/webstack-e2e")
  37. DB_PATH = os.path.join(WORK, "web.sqlite")
  38. passes = 0
  39. failures = 0
  40. def check(condition, label):
  41. global passes, failures
  42. if condition:
  43. passes += 1
  44. print("PASS %s" % label)
  45. else:
  46. failures += 1
  47. print("FAIL %s" % label)
  48. def free_port():
  49. with socket.socket() as sock:
  50. sock.bind(("127.0.0.1", 0))
  51. return sock.getsockname()[1]
  52. APP_PORT = free_port()
  53. DAEMON_PORT = free_port()
  54. WEB = "http://127.0.0.1:%d" % APP_PORT
  55. def http(method, url, data=None, headers=None, timeout=30):
  56. body = None
  57. if data is not None:
  58. pairs = []
  59. for k, v in data.items():
  60. for item in (v if isinstance(v, (list, tuple)) else [v]):
  61. pairs.append((k, item))
  62. body = "&".join("%s=%s" % (k, urllib.parse.quote(str(item))) for k, item in pairs).encode()
  63. request = urllib.request.Request(WEB + url if url.startswith("/") else url,
  64. data=body, method=method)
  65. if data is not None:
  66. request.add_header("Content-Type", "application/x-www-form-urlencoded")
  67. for key, value in (headers or {}).items():
  68. request.add_header(key, value)
  69. # Retry dropped/refused connections: the freshly started app can
  70. # close a very early keep-alive connection once while warming up,
  71. # and its first seconds can wobble under load.
  72. for attempt in range(3):
  73. try:
  74. with urllib.request.urlopen(request, timeout=timeout) as response:
  75. return response.status, response.read().decode()
  76. except urllib.error.HTTPError as error:
  77. return error.code, error.read().decode()
  78. except (urllib.error.URLError, OSError):
  79. if attempt >= 2:
  80. raise
  81. time.sleep(0.75)
  82. def directives(uri, auth=None):
  83. headers = {}
  84. if auth:
  85. headers["X-Statum-Slot"] = "key=%s; as_at=%s" % (auth["key"], auth["as_at"])
  86. status, body = http("GET", "/_statum/entrypoint?uri=" + urllib.parse.quote(uri.split("?")[0]),
  87. headers=headers)
  88. if status != 200:
  89. raise SystemExit("entrypoint %s -> HTTP %d: %s" % (uri, status, body[:300]))
  90. return json.loads(body)
  91. def slot_public(auth, uri, type_name):
  92. for directive in directives(uri, auth):
  93. if directive["type"] == "set":
  94. content = json.loads(directive["snapshot_frame"]["content"])
  95. if content["slot"]["type"] == type_name:
  96. return content["public"]
  97. raise SystemExit("no %s slot in entrypoint state for %s" % (type_name, uri))
  98. def act(auth, action, fields):
  99. headers = {"X-Statum-Slot": "key=%s; as_at=%s" % (auth["key"], auth["as_at"])}
  100. if action.get("private"):
  101. headers["X-Statum-Private"] = action["private"]
  102. status, body = http(action.get("method", "POST"), action["uri"], fields, headers)
  103. if status != 200:
  104. raise SystemExit("action %s -> HTTP %d: %s" % (action["uri"], status, body[:300]))
  105. return json.loads(body)
  106. def login(username, password):
  107. frames = directives("/login")
  108. content = json.loads(frames[0]["snapshot_frame"]["content"])
  109. action = content["public"]["login"]
  110. status, body = http(action.get("method", "POST"), action["uri"],
  111. {"username": username, "password": password})
  112. if status != 200:
  113. raise SystemExit("login -> HTTP %d: %s" % (status, body[:300]))
  114. for directive in json.loads(body):
  115. if directive["type"] == "set":
  116. frame = json.loads(directive["snapshot_frame"]["content"])
  117. if frame["slot"]["type"] == "auth":
  118. return {"key": frame["slot"]["key"], "as_at": frame["as_at"]}
  119. raise SystemExit("login response carried no auth slot: " + body[:300])
  120. def wait_for(predicate, timeout=60, what="condition", interval=0.5):
  121. deadline = time.monotonic() + timeout
  122. last = None
  123. while time.monotonic() < deadline:
  124. last = predicate()
  125. if last is not False and last is not None:
  126. return last
  127. time.sleep(interval)
  128. print(" (timeout waiting for %s; last: %s)" % (what, last))
  129. return None
  130. def task_state(auth, task_id):
  131. return slot_public(auth, "/tasks/%d" % task_id, "task")
  132. def wait_task_done(auth, task_id, timeout=90):
  133. return wait_for(lambda: task_state(auth, task_id).get("status") == "done" or False,
  134. timeout=timeout, what="task %d -> done" % task_id)
  135. def task_id_of(title):
  136. conn = db()
  137. try:
  138. return conn.execute("select id from tasks where title = ?", (title,)).fetchone()[0]
  139. finally:
  140. conn.close()
  141. def saddle_api(method, path, token, payload=None):
  142. """Raw call against the saddle ingest API; returns (status, json)."""
  143. request = urllib.request.Request(WEB + path,
  144. data=json.dumps(payload or {}).encode(), method=method)
  145. request.add_header("Content-Type", "application/json")
  146. if token is not None:
  147. request.add_header("Authorization", "Bearer " + token)
  148. try:
  149. with urllib.request.urlopen(request, timeout=15) as response:
  150. return response.status, json.loads(response.read().decode() or "{}")
  151. except urllib.error.HTTPError as error:
  152. body = error.read().decode()
  153. try:
  154. return error.code, json.loads(body)
  155. except ValueError:
  156. return error.code, {"raw": body}
  157. def db():
  158. return sqlite3.connect(DB_PATH)
  159. class FakeSaddle:
  160. """In-process saddle daemon implementing the wire contract."""
  161. PROMPT = "bbarrow@fedora:/workspace/task-1$ "
  162. def __init__(self):
  163. self.lock = threading.Lock()
  164. self.start_payloads = [] # captured POST /start bodies
  165. self.chunks = [] # [{seq, text}] — the raw log ring
  166. self.next_seq = 1
  167. self.state = "idle"
  168. self.summary = ""
  169. self.state_entered = time.monotonic()
  170. self.fail_next = False # next /start drives the task to failed
  171. self.start_counts = {} # task id -> /start count
  172. self.resumed_pending = False # crash-resume flag on the next /status
  173. self.suspend_after_start = False # next task parks as suspended
  174. self.pending_output = [] # entries drained by the next /output poll
  175. self.output_seq = 100
  176. self.last_activity_epoch = int(time.time())
  177. self.subtask_status_events = [] # recorded POST /subtask-status payloads
  178. self.fail_subtask_status = False # exercise the web's retry path
  179. self.hang_next = {} # path suffix -> hang count (never responds)
  180. self.fail_log_count = 0 # /log requests failing (500) while > 0
  181. self.scripted_log = None # fixed chunk set served by /log
  182. self.scripted_next = 0 # the daemon-style next for it
  183. self.scripted_corpus = None # chunks "produced" when a task starts
  184. self.race_texts = None # chunks appended DURING /log response
  185. # construction (the daemon-side bug)
  186. self.answer_bodies = [] # recorded POST /answer payloads
  187. self.abort_failures = 0 # /abort requests failing (500) while > 0
  188. self.abort_log = [] # task ids aborted via POST /abort
  189. self.running_task = 0 # task id the daemon believes it runs
  190. self.zombie_409 = 0 # /start 409s once per unit (then decrements)
  191. self.conflict_running = 0 # while > 0, /start persistently 409s with this id
  192. self.hold_state = False # freeze /status lifecycle transitions
  193. self.ssh_public_key = "" # reported on /status (plan-9 contract)
  194. self.started_mono = time.monotonic()
  195. self.freeze_activity = False # hold last_activity_epoch still
  196. def set_state(self, state, summary=None):
  197. """Advances the scripted lifecycle.
  198. Time-based on purpose: the web app may probe /status more than
  199. once per tick (status polls, stale-busy healing, manual
  200. refreshes), and a poll-counted machine would conflate them and
  201. race dependent sections.
  202. """
  203. self.state = state
  204. if summary is not None:
  205. self.summary = summary
  206. self.state_entered = time.monotonic()
  207. def queue_output(self, entry_type, command, output):
  208. """Queues a typed entry for the dispatcher's next /output poll."""
  209. with self.lock:
  210. self.pending_output.append({
  211. "id": self.output_seq,
  212. "command": command,
  213. "output": output,
  214. "exit_code": 1,
  215. "type": entry_type,
  216. "timestamp": "2026-09-06T00:00:00Z",
  217. })
  218. self.output_seq += 1
  219. def touch_activity(self):
  220. if not self.freeze_activity:
  221. self.last_activity_epoch = int(time.time())
  222. def append_chunk(self, text):
  223. with self.lock:
  224. self.chunks.append({"seq": self.next_seq, "text": text})
  225. self.next_seq += 1
  226. def log_since(self, since):
  227. with self.lock:
  228. if self.scripted_log is not None:
  229. chunks = [c for c in self.scripted_log if c["seq"] >= since]
  230. return chunks, self.scripted_next
  231. # `since` is the inclusive resume point (wire contract: a
  232. # response ending at seq 12 carries next=13, and polling
  233. # with since=13 must still deliver the chunk numbered 13).
  234. chunks = [c for c in self.chunks if c["seq"] >= since]
  235. return chunks, self.next_seq
  236. class Handler(BaseHTTPRequestHandler):
  237. daemon = None # set on the class before serving
  238. protocol_version = "HTTP/1.1"
  239. def log_message(self, fmt, *args):
  240. pass
  241. def maybe_hang(self, path):
  242. """True when this request should hang forever (never respond),
  243. consuming one unit of the path's hang budget."""
  244. for suffix, count in list(self.daemon.hang_next.items()):
  245. if count > 0 and path.startswith(suffix):
  246. self.daemon.hang_next[suffix] = count - 1
  247. return True
  248. return False
  249. def _send(self, status, obj):
  250. body = json.dumps(obj).encode()
  251. self.send_response(status)
  252. self.send_header("Content-Type", "application/json")
  253. self.send_header("Content-Length", str(len(body)))
  254. self.end_headers()
  255. self.wfile.write(body)
  256. def do_POST(self):
  257. self.daemon.touch_activity()
  258. length = int(self.headers.get("Content-Length") or 0)
  259. raw = self.rfile.read(length).decode() if length else "{}"
  260. if self.path == "/start":
  261. if self.daemon.conflict_running > 0 or self.daemon.zombie_409 > 0:
  262. # Wire contract: a machine-readable conflict.
  263. running = self.daemon.conflict_running
  264. if running == 0:
  265. running = self.daemon.running_task
  266. self.daemon.zombie_409 -= 1
  267. body = json.dumps({"ok": False, "error": "busy",
  268. "state": "working",
  269. "running_task_id": running}).encode()
  270. self.send_response(409)
  271. self.send_header("Content-Type", "application/json")
  272. self.send_header("Content-Length", str(len(body)))
  273. self.end_headers()
  274. self.wfile.write(body)
  275. return
  276. try:
  277. payload = json.loads(raw)
  278. except ValueError:
  279. payload = {"raw": raw}
  280. self.daemon.start_payloads.append(payload)
  281. task_id = (payload.get("task") or {}).get("id")
  282. self.daemon.running_task = int(task_id or 0)
  283. count = self.daemon.start_counts.get(task_id, 0) + 1
  284. self.daemon.start_counts[task_id] = count
  285. if count > 1:
  286. # Crash-resume contract: re-pushing a task whose
  287. # workspace still exists restores it; the first
  288. # /status after the restore reports "resumed": true.
  289. self.daemon.resumed_pending = True
  290. self.daemon.append_chunk(self.daemon.PROMPT)
  291. self.daemon.append_chunk("echo hello\r\n")
  292. self.daemon.append_chunk("hello\r\n")
  293. self.daemon.set_state("failing" if self.daemon.fail_next else "working")
  294. self.daemon.fail_next = False
  295. if self.daemon.scripted_corpus is not None:
  296. with self.daemon.lock:
  297. for chunk in self.daemon.scripted_corpus:
  298. self.daemon.scripted_log.append(dict(chunk))
  299. self.daemon.scripted_next = self.daemon.scripted_corpus[-1]["seq"] + 1
  300. self._send(200, {})
  301. elif self.path == "/answer":
  302. try:
  303. self.daemon.answer_bodies.append(json.loads(raw))
  304. except ValueError:
  305. pass
  306. self._send(200, {})
  307. elif self.path == "/abort":
  308. if self.daemon.abort_failures > 0:
  309. self.daemon.abort_failures -= 1
  310. self._send(500, {"error": "abort failed (simulated)"})
  311. return
  312. aborted = self.daemon.running_task
  313. self.daemon.set_state("idle")
  314. self.daemon.summary = ""
  315. self.daemon.running_task = 0
  316. self.daemon.abort_log.append(aborted)
  317. self._send(200, {"ok": True, "aborted_task_id": aborted})
  318. elif self.path == "/subtask-status":
  319. try:
  320. payload = json.loads(raw)
  321. except ValueError:
  322. self._send(400, {"error": "bad json"})
  323. return
  324. if self.daemon.fail_subtask_status:
  325. self._send(500, {"error": "simulated failure"})
  326. return
  327. self.daemon.subtask_status_events.append(payload)
  328. self._send(200, {"ok": True})
  329. else:
  330. self._send(404, {"error": "no such route"})
  331. def do_GET(self):
  332. if self.maybe_hang(self.path):
  333. time.sleep(600)
  334. return
  335. if self.path != "/status":
  336. # /status itself is not daemon activity: the wedge signal
  337. # must reflect loop rounds / command completions.
  338. self.daemon.touch_activity()
  339. if self.path == "/status":
  340. response = {"state": self.daemon.state, "summary": self.daemon.summary,
  341. "uptime_seconds": int(time.monotonic() - self.daemon.started_mono),
  342. "last_activity_epoch": self.daemon.last_activity_epoch,
  343. "ssh_public_key": self.daemon.ssh_public_key}
  344. if self.daemon.resumed_pending:
  345. response["resumed"] = True
  346. self.daemon.resumed_pending = False
  347. if self.daemon.hold_state:
  348. self._send(200, response)
  349. return
  350. if self.daemon.state == "failing":
  351. # Fails fast (a rejected /start script).
  352. if time.monotonic() - self.daemon.state_entered >= 1:
  353. self.daemon.set_state("failed",
  354. "bash -n rejected the script (simulated)")
  355. elif self.daemon.state == "working":
  356. # Time-based, not poll-based: whoever probes /status
  357. # (dispatcher polls, stale-busy healing, refreshes)
  358. # must not advance the lifecycle.
  359. if time.monotonic() - self.daemon.state_entered >= 8:
  360. if self.daemon.suspend_after_start:
  361. # `saddle suspend`: park until a fresh /start
  362. # resumes the workspace (one-shot flag).
  363. self.daemon.set_state("suspended")
  364. self.daemon.suspend_after_start = False
  365. else:
  366. self.daemon.set_state("done", "fake daemon finished")
  367. self._send(200, response)
  368. elif self.path.startswith("/output"):
  369. with self.daemon.lock:
  370. entries = self.daemon.pending_output
  371. self.daemon.pending_output = []
  372. self._send(200, entries)
  373. elif self.path.startswith("/log"):
  374. if self.daemon.fail_log_count > 0:
  375. self.daemon.fail_log_count -= 1
  376. self._send(500, {"error": "log unavailable (simulated)"})
  377. return
  378. query = urllib.parse.urlparse(self.path).query
  379. since = int(urllib.parse.parse_qs(query).get("since", ["0"])[0])
  380. # The daemon-side snapshot race: the served array is
  381. # snapshotted, chunks are appended, and `next` is computed
  382. # AFTER the appends — the response's next skips chunks the
  383. # array never carried (the live run's 33 lost chunks).
  384. raced = False
  385. if since > 0 and self.daemon.race_texts:
  386. raced = True
  387. with self.daemon.lock:
  388. next_seq = self.daemon.scripted_next
  389. for text in self.daemon.race_texts:
  390. self.daemon.scripted_log.append(
  391. {"seq": next_seq, "text": text})
  392. next_seq += 1
  393. self.daemon.scripted_next = next_seq
  394. self.daemon.race_texts = None
  395. # Simulate the live PTY: each poll produces one more chunk
  396. # (before slicing, so the poller actually sees it).
  397. self.daemon.append_chunk("stream-line-%d\r\n" % self.daemon.next_seq)
  398. chunks, nxt = self.daemon.log_since(since)
  399. if raced:
  400. nxt = self.daemon.scripted_next
  401. self._send(200, {"chunks": chunks, "next": nxt})
  402. else:
  403. self._send(404, {"error": "no such route"})
  404. self.close_connection = True
  405. def serve(self):
  406. handler = type("BoundHandler", (FakeSaddle.Handler,), {"daemon": self})
  407. self.server = ThreadingHTTPServer(("127.0.0.1", DAEMON_PORT), handler)
  408. threading.Thread(target=self.server.serve_forever, daemon=True).start()
  409. return self.server
  410. def kill(self):
  411. """Stops listening: subsequent connections are refused — a daemon
  412. that died mid-task."""
  413. if getattr(self, "server", None) is not None:
  414. self.server.shutdown()
  415. self.server.server_close()
  416. self.server = None
  417. def start_app():
  418. config = json.load(open(os.path.join(REPO, "web-config.json")))
  419. config["saddle_callback_base_url"] = WEB
  420. with open(os.path.join(WORK, "web-config.json"), "w") as handle:
  421. json.dump(config, handle)
  422. env = dict(os.environ)
  423. env.update({
  424. "SPRY_DB_PATH": DB_PATH,
  425. "SPRY_SEED_ADMIN_USERNAME": "admin",
  426. "SPRY_SEED_ADMIN_PASSWORD": "adminpass123",
  427. "SADDLE_LLM_BASE_URL": "http://127.0.0.1:%d" % DAEMON_PORT,
  428. "SADDLE_PROJECTS_ROOT": os.path.join(WORK, "workspace"),
  429. "SADDLE_HTTP_TIMEOUT_S": "5",
  430. "SADDLE_RAW_PROBE_INTERVAL_S": "5",
  431. "SADDLE_STRAND_GRACE_S": "10",
  432. "SADDLE_WEDGE_THRESHOLD_S": "8",
  433. # Never inherit a caller-poisoned LD_LIBRARY_PATH (e.g. one that
  434. # resolves the ancient /lib64 copies): empty makes the loader use
  435. # the binary's RUNPATH, which is the dev stack it was built
  436. # against.
  437. "LD_LIBRARY_PATH": "",
  438. })
  439. log = open(os.path.join(WORK, "app.log"), "w")
  440. command = [APP, str(APP_PORT)]
  441. if os.environ.get("WEBSTACK_GDB"):
  442. # Debugging aid: run the app under gdb; a crash backtrace lands in
  443. # app.log. WEBSTACK_GDB=1 meson test ... to enable.
  444. command = ["gdb", "-batch", "-quiet",
  445. "-ex", "handle SIGPIPE nostop noprint pass",
  446. "-ex", "run", "-ex", "bt", "--args", APP, str(APP_PORT)]
  447. process = subprocess.Popen(command, cwd=WORK, env=env,
  448. stdout=log, stderr=subprocess.STDOUT)
  449. outcome = wait_for(lambda: (app_ready() and "ready")
  450. or (process.poll() is not None and "app-exited-%d" % process.poll())
  451. or False, timeout=30, what="app ready")
  452. if outcome is None:
  453. raise SystemExit("app did not come up; see %s/app.log" % WORK)
  454. if str(outcome).startswith("app-exited-"):
  455. raise SystemExit("app exited during startup (%s); see %s/app.log"
  456. % outcome, WORK)
  457. return process
  458. def app_ready():
  459. try:
  460. status, _ = http("GET", "/login", timeout=3)
  461. return status == 200
  462. except (urllib.error.URLError, OSError):
  463. return False
  464. def dump_app_stacks(pid):
  465. """Best-effort thread backtrace of the (possibly wedged) app."""
  466. try:
  467. fds = os.listdir("/proc/%d/fd" % pid)
  468. print("(app open fds at dump: %d)" % len(fds))
  469. kinds = {}
  470. for fd in fds[:1200]:
  471. try:
  472. target = os.readlink("/proc/%d/fd/%s" % (pid, fd))
  473. except OSError:
  474. continue
  475. key = target.split(":", 1)[0] if ":" in target else target
  476. kinds[key] = kinds.get(key, 0) + 1
  477. print("(fd kinds: %s)" % sorted(kinds.items(), key=lambda kv: -kv[1])[:6])
  478. except OSError:
  479. pass
  480. for command in (["eu-stack", "-p", str(pid)],
  481. ["gdb", "-batch", "-quiet", "-p", str(pid),
  482. "-ex", "thread apply all bt"]):
  483. try:
  484. out = subprocess.run(command, capture_output=True, timeout=60)
  485. text = out.stdout.decode(errors="replace") + out.stderr.decode(errors="replace")
  486. if text.strip():
  487. print("(app stacks via %s)\n%s" % (command[0], text[:12000]))
  488. return
  489. except (OSError, subprocess.SubprocessError):
  490. continue
  491. def main():
  492. if not os.path.exists(APP):
  493. raise SystemExit("app binary not found at %s (build first)" % APP)
  494. fake = FakeSaddle()
  495. fake.serve()
  496. # A rare framework-level crash (stack corruption in Statum slot
  497. # signing during the FIRST login — shared-library codegen bug, moved
  498. # twice already) kills the app before any test runs; a clean restart
  499. # sidesteps it. Only tolerated while nothing has been checked yet.
  500. auth = None
  501. app = None
  502. for attempt in range(3):
  503. if os.path.exists(WORK):
  504. shutil.rmtree(WORK)
  505. os.makedirs(os.path.join(WORK, "workspace"))
  506. try:
  507. app = start_app()
  508. auth = login("admin", "adminpass123")
  509. break
  510. except (SystemExit, OSError, urllib.error.URLError):
  511. if passes > 0:
  512. raise
  513. if app is not None and app.poll() is None:
  514. app.terminate()
  515. try:
  516. app.wait(timeout=5)
  517. except subprocess.TimeoutExpired:
  518. app.kill()
  519. app = None
  520. print("(app died before login; restarting cleanly, attempt %d)" % (attempt + 1))
  521. if app is None or auth is None:
  522. raise SystemExit("app never came up; see %s/app.log" % WORK)
  523. try:
  524. check(True, "login yields an auth slot")
  525. print("== feature 3: plan review hides duplicate body ==")
  526. state = slot_public(auth, "/projects", "projects")
  527. act(auth, state["create"], {
  528. "name": "demo",
  529. "git_url": "https://example.com/demo.git",
  530. "default_branch": "main",
  531. })
  532. conn = db()
  533. conn.execute("insert into tasks (project_id, title, status, priority,"
  534. " is_design_task, plan, created_at)"
  535. " values (1, 'Plan review task', 'working', 5, 1, '# The plan\n\n1. Do it',"
  536. " strftime('%s','now'))")
  537. conn.commit()
  538. plan_task = conn.execute("select max(id) from tasks").fetchone()[0]
  539. saddles_state = slot_public(auth, "/saddles", "saddles")
  540. act(auth, saddles_state["register"], {"name": "fake-saddle",
  541. "host": "127.0.0.1:%d" % DAEMON_PORT})
  542. registered = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  543. if s["name"] == "fake-saddle"]
  544. check(len(registered) == 1 and registered[0]["token"].startswith("saddle-"),
  545. "fake saddle registered with an API token")
  546. fake_id = int(registered[0]["id"])
  547. fake_token = registered[0]["token"]
  548. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  549. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  550. (plan_task, fake_id))
  551. conn.commit()
  552. session_id = conn.execute("select max(id) from sessions").fetchone()[0]
  553. conn.close()
  554. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  555. {"type": "block", "session_id": session_id, "data": {
  556. "question": "Plan submitted for review",
  557. "type": "rfc",
  558. "body": "# The plan\n\n1. Do it"}})
  559. check(status == 200 and body.get("block_id"), "plan-review block raised")
  560. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  561. {"type": "block", "session_id": session_id, "data": {
  562. "question": "Which database?",
  563. "type": "question",
  564. "options": ["SQLite", "Postgres"],
  565. "body": "# Storage choice"}})
  566. check(status == 200, "question block raised")
  567. detail = task_state(auth, plan_task)
  568. blocks = {b["block_type"]: b for b in detail["blocks"]}
  569. check(blocks["rfc"].get("is_plan_review") is True,
  570. "rfc block flagged as the plan review")
  571. check(blocks["rfc"].get("show_body") is False,
  572. "pending plan review hides the duplicate body preview")
  573. check(blocks["question"].get("show_body") is True,
  574. "question block keeps its body preview")
  575. act(auth, blocks["rfc"]["answer_action"], {"answer": "Plan approved. Proceed."})
  576. detail = task_state(auth, plan_task)
  577. rfc = [b for b in detail["blocks"] if b["block_type"] == "rfc"][0]
  578. check(rfc.get("show_body") is True,
  579. "answered plan review shows the body again (review section gone)")
  580. print("== B1: highlight-to-comment quote dialog ==")
  581. status, page = http("GET", "/tasks/%d" % plan_task, timeout=15)
  582. check(status == 200 and "quote-comment-dialog" in page and "quote-text" in page,
  583. "task page carries the quote-comment dialog the popover opens")
  584. check('name="quote"' in page and 'name="return_to"' in page,
  585. "quote dialog posts the quote and return-to fields")
  586. status, page = http("GET", "/tasks/%d/terminal" % plan_task, timeout=15)
  587. check(status == 200 and "quote-comment-dialog" in page,
  588. "terminal page keeps its quote dialog")
  589. print("== B3: review section hides the duplicate body ==")
  590. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  591. {"type": "block", "session_id": session_id, "data": {
  592. "question": "Review the diff",
  593. "type": "review",
  594. "body": "# The change\n\nReworks the flange module."}})
  595. check(status == 200 and body.get("block_id"), "review block raised")
  596. detail = task_state(auth, plan_task)
  597. review_block = [b for b in detail["blocks"] if b["block_type"] == "review"][0]
  598. check(detail.get("review_pending") is True,
  599. "review section shows while the review is unanswered")
  600. check(review_block.get("show_body") is False,
  601. "pending review block hides its duplicate body preview")
  602. check(review_block.get("body", "").startswith("# The change"),
  603. "review body itself still arrives in state (B2 counterpart)")
  604. act(auth, review_block["answer_action"], {"answer": "Human approved the review"})
  605. detail = task_state(auth, plan_task)
  606. review_block = [b for b in detail["blocks"] if b["block_type"] == "review"][0]
  607. check(review_block.get("show_body") is True,
  608. "answered review shows the body again (banner gone)")
  609. print("== B2: question block body above options ==")
  610. # Contract side (A2 will restore bodies end-to-end): a question
  611. # block raised with a heredoc body carries it; the body preview
  612. # rides above the options (template order) and survives answering
  613. # alongside the selected answer.
  614. detail = task_state(auth, plan_task)
  615. question = [b for b in detail["blocks"] if b["block_type"] == "question"][0]
  616. check(question.get("body") == "# Storage choice"
  617. and question.get("show_body") is True,
  618. "question block keeps its body markdown with the preview on")
  619. act(auth, question["answer_action"], {"option": "SQLite"})
  620. detail = task_state(auth, plan_task)
  621. question = [b for b in detail["blocks"] if b["block_type"] == "question"][0]
  622. check(question.get("answered") is True and question.get("answer") == "SQLite"
  623. and question.get("body") == "# Storage choice"
  624. and question.get("show_body") is True,
  625. "answered question shows body + selected answer")
  626. print("== B5: compare-changes SSH -> HTTPS ==")
  627. def diff_url_for_project(git_url, suffix):
  628. state = slot_public(auth, "/projects", "projects")
  629. act(auth, state["create"], {"name": "diff-%s" % suffix, "git_url": git_url})
  630. project_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  631. if p["name"] == "diff-%s" % suffix][0])
  632. conn = db()
  633. conn.execute("insert into tasks (project_id, title, status, task_branch,"
  634. " branch_from, created_at) values (?, ?, 'working', 'feature/x',"
  635. " 'main', strftime('%s','now'))", (project_id, "Diff %s" % suffix))
  636. conn.commit()
  637. task_id = conn.execute("select max(id) from tasks").fetchone()[0]
  638. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at,"
  639. " outcome) values (?, ?, strftime('%s','now'), strftime('%s','now'),"
  640. " 'done')", (task_id, fake_id))
  641. conn.commit()
  642. session = conn.execute("select max(id) from sessions").fetchone()[0]
  643. conn.close()
  644. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  645. {"type": "block", "session_id": session, "data": {
  646. "question": "Review the diff", "type": "review"}})
  647. return task_state(auth, task_id).get("review_diff_url") or ""
  648. check(diff_url_for_project("ssh://fabrica.unitatem.net:222/clanker/clanker-saddle.git",
  649. "fabrica")
  650. == "https://fabrica.unitatem.net/clanker/clanker-saddle/compare/main...feature/x",
  651. "ssh://git@host:port/owner/repo.git translates (port dropped)")
  652. check(diff_url_for_project("git@github.com:acme/widgets.git", "scp")
  653. == "https://github.com/acme/widgets/compare/main...feature/x",
  654. "git@host:owner/repo.git translates to the browse host")
  655. check(diff_url_for_project("https://example.com/plain/repo", "plain")
  656. == "https://example.com/plain/repo/compare/main...feature/x",
  657. "HTTPS URLs pass through unchanged")
  658. print("== feature 5: rules ==")
  659. rules_state = slot_public(auth, "/rules", "rules")
  660. for name, body in [
  661. ("Use Invercargill", "Never use libgee; use Invercargill enumerables."),
  662. ("Write Vala docs", "Every public class carries a doc comment."),
  663. ("Prefer meson", "Builds go through meson; no makefiles."),
  664. ("Co-dev rule", "Keep the wire contract exactly."),
  665. ("Reference rule", "Must never ride along."),
  666. ]:
  667. act(auth, rules_state["create"], {"name": name, "body": body})
  668. listed = {r["name"]: r for r in slot_public(auth, "/rules", "rules")["rules"]}
  669. check(len(listed) == 5, "five rules created and listed on /rules")
  670. def rule_id(name):
  671. rows = [r for r in slot_public(auth, "/rules", "rules")["rules"] if r["name"] == name]
  672. return int(rows[0]["id"])
  673. state = slot_public(auth, "/projects", "projects")
  674. act(auth, state["create"], {"name": "co", "git_url": "https://example.com/co.git"})
  675. act(auth, state["create"], {"name": "ref", "git_url": "https://example.com/ref.git"})
  676. co_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  677. if p["name"] == "co"][0])
  678. ref_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  679. if p["name"] == "ref"][0])
  680. project = slot_public(auth, "/projects/1", "project")
  681. act(auth, project["add_link"], {"linked_project_id": str(co_id),
  682. "relationship": "co-developed"})
  683. act(auth, project["add_link"], {"linked_project_id": str(ref_id),
  684. "relationship": "reference"})
  685. act(auth, project["attach_rule"], {"rule_id": str(rule_id("Use Invercargill"))})
  686. act(auth, project["attach_rule"], {"rule_id": str(rule_id("Prefer meson"))})
  687. project = slot_public(auth, "/projects/1", "project")
  688. check(sorted(r["name"] for r in project["rules"]) == ["Prefer meson", "Use Invercargill"],
  689. "project page lists its attached rules")
  690. co_project = slot_public(auth, "/projects/%d" % co_id, "project")
  691. act(auth, co_project["attach_rule"], {"rule_id": str(rule_id("Co-dev rule"))})
  692. ref_project = slot_public(auth, "/projects/%d" % ref_id, "project")
  693. act(auth, ref_project["attach_rule"], {"rule_id": str(rule_id("Reference rule"))})
  694. tasks_state = slot_public(auth, "/tasks", "tasks")
  695. act(auth, tasks_state["create"], {
  696. "project_id": "1",
  697. "title": "Rules dispatch",
  698. "description": "Effective rule set rides the /start payload.",
  699. "priority": "2",
  700. })
  701. rule_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  702. if t["title"] == "Rules dispatch"][0])
  703. detail = task_state(auth, rule_task)
  704. act(auth, detail["attach_rule"], {"rule_id": str(rule_id("Write Vala docs"))})
  705. act(auth, detail["attach_rule"], {"rule_id": str(rule_id("Use Invercargill"))})
  706. detail = task_state(auth, rule_task)
  707. check(sorted(r["name"] for r in detail["rules"]) == ["Use Invercargill", "Write Vala docs"],
  708. "task page lists its attached rules")
  709. check(wait_for(lambda: len(fake.start_payloads) > 0 or False,
  710. timeout=30, what="/start push") is not None,
  711. "dispatcher pushes the task to the fake saddle")
  712. payload = fake.start_payloads[-1]
  713. rule_names = [r["name"] for r in payload.get("rules", [])]
  714. check(rule_names == ["Write Vala docs", "Use Invercargill", "Prefer meson", "Co-dev rule"],
  715. "effective rules in /start: task, primary, co-developed order (%s)" % rule_names)
  716. check(all(r.get("body") for r in payload.get("rules", [])),
  717. "rules carry their bodies")
  718. check("Reference rule" not in rule_names,
  719. "reference project rules excluded")
  720. detail = task_state(auth, rule_task)
  721. act(auth, detail["rules"][0]["detach"], {})
  722. check([r["name"] for r in task_state(auth, rule_task)["rules"]] == ["Use Invercargill"],
  723. "detached task rule disappears")
  724. rules_rows = slot_public(auth, "/rules", "rules")["rules"]
  725. docs_row = [r for r in rules_rows if r["name"] == "Write Vala docs"][0]
  726. act(auth, docs_row["update"], {"name": "Write Vala docs", "body": "Doc comments or bust."})
  727. check(any(r["body"] == "Doc comments or bust."
  728. for r in slot_public(auth, "/rules", "rules")["rules"]),
  729. "rule edit saves the body")
  730. check(wait_task_done(auth, rule_task, timeout=60) is not None,
  731. "dispatched task completes against the fake daemon")
  732. print("== feature 6: project notes + callback ==")
  733. conn = db()
  734. callback_rows = conn.execute(
  735. "select token from api_tokens where saddle_id = 0").fetchall()
  736. conn.close()
  737. check(len(callback_rows) == 1 and callback_rows[0][0].startswith("saddle-callback-"),
  738. "dedicated saddle-callback token minted at startup")
  739. callback_token = callback_rows[0][0]
  740. status, _ = saddle_api("POST", "/api/saddle/note", None,
  741. {"project": "demo", "body": "x"})
  742. check(status == 401, "note endpoint rejects a missing token")
  743. status, _ = saddle_api("POST", "/api/saddle/note", "saddle-callback-not-real",
  744. {"project": "demo", "body": "x"})
  745. check(status == 401, "note endpoint rejects a wrong token")
  746. status, body = saddle_api("POST", "/api/saddle/note", callback_token,
  747. {"task_id": rule_task, "project": "demo",
  748. "body": "style.css tokens live in :root"})
  749. check(status == 200 and body.get("ok") is True, "note accepted with the callback token")
  750. status, _ = saddle_api("POST", "/api/saddle/note", callback_token,
  751. {"project": "no-such-project", "body": "x"})
  752. check(status == 400, "unknown project rejected")
  753. status, _ = saddle_api("POST", "/api/saddle/note", callback_token,
  754. {"project": "demo", "body": " "})
  755. check(status == 400, "empty note body rejected")
  756. project = slot_public(auth, "/projects/1", "project")
  757. check(any("style.css tokens" in n["body"] and int(n["source_task_id"]) == rule_task
  758. for n in project["notes"]),
  759. "project page lists the note with its source task")
  760. act(auth, [n for n in project["notes"] if "style.css tokens" in n["body"]][0]["delete"], {})
  761. check(all("style.css tokens" not in n["body"]
  762. for n in slot_public(auth, "/projects/1", "project")["notes"]),
  763. "note deleted from the project page")
  764. # /start payload: notes of primary + co-developed (not reference),
  765. # oldest first; callback carries the configured base URL + token.
  766. saddle_api("POST", "/api/saddle/note", callback_token,
  767. {"project": "demo", "body": "note-one"})
  768. saddle_api("POST", "/api/saddle/note", callback_token,
  769. {"project": "demo", "body": "note-two"})
  770. saddle_api("POST", "/api/saddle/note", callback_token,
  771. {"project": "co", "body": "co-note"})
  772. conn = db()
  773. conn.execute("insert into project_notes (project_id, body, created_at)"
  774. " values (?, 'ref-note-must-not-ship', strftime('%s','now'))", (ref_id,))
  775. conn.commit()
  776. conn.close()
  777. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  778. "project_id": "1",
  779. "title": "Notes dispatch",
  780. "description": "Project notes ride the /start payload.",
  781. "priority": "2",
  782. })
  783. check(wait_for(lambda: len(fake.start_payloads) >= 2 or False,
  784. timeout=30, what="second /start push") is not None,
  785. "dispatcher pushes the notes task")
  786. payload = fake.start_payloads[-1]
  787. notes = payload.get("project_notes", [])
  788. check([n["body"] for n in notes] == ["note-one", "note-two", "co-note"],
  789. "project_notes: primary + co-developed, oldest first (%s)" % [n["body"] for n in notes])
  790. check(all(n.get("project") for n in notes)
  791. and notes[2]["project"] == "co",
  792. "project_notes carry the project name")
  793. check("ref-note-must-not-ship" not in [n["body"] for n in notes],
  794. "reference project notes excluded")
  795. callback = payload.get("callback", {})
  796. check(callback.get("base_url") == WEB and callback.get("token") == callback_token,
  797. "callback carries the configured base URL and the minted token")
  798. # entry cap: 30 of 33 candidates
  799. conn = db()
  800. for i in range(33):
  801. conn.execute("insert into project_notes (project_id, body, created_at)"
  802. " values (?, ?, strftime('%s','now'))", (1, "bulk-%02d" % i))
  803. conn.commit()
  804. conn.close()
  805. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  806. "project_id": "1",
  807. "title": "Entry cap dispatch",
  808. "priority": "2",
  809. })
  810. check(wait_for(lambda: len(fake.start_payloads) >= 3 or False,
  811. timeout=30, what="third /start push") is not None,
  812. "dispatcher pushes the entry-cap task")
  813. notes = fake.start_payloads[-1].get("project_notes", [])
  814. check(len(notes) == 30 and notes[0]["body"] == "note-one" and notes[1]["body"] == "note-two",
  815. "project_notes capped at 30 entries, oldest kept (%d)" % len(notes))
  816. # char cap: the giant note is truncated so the total stays <= 20000
  817. conn = db()
  818. conn.execute("delete from project_notes where body like 'bulk-%' or body = 'co-note'")
  819. conn.execute("insert into project_notes (project_id, body, created_at)"
  820. " values (?, ?, strftime('%s','now'))", (1, "giant!" + "x" * 25000,))
  821. conn.commit()
  822. conn.close()
  823. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  824. "project_id": "1",
  825. "title": "Char cap dispatch",
  826. "priority": "2",
  827. })
  828. check(wait_for(lambda: len(fake.start_payloads) >= 4 or False,
  829. timeout=30, what="fourth /start push") is not None,
  830. "dispatcher pushes the char-cap task")
  831. notes = fake.start_payloads[-1].get("project_notes", [])
  832. total = sum(len(n["body"]) for n in notes)
  833. check(len(notes) == 3 and total == 20000 and notes[2]["body"].startswith("giant!"),
  834. "project_notes char cap: head kept, giant truncated (entries=%d, chars=%d)"
  835. % (len(notes), total))
  836. print("== raw log polling + terminal raw view ==")
  837. # Wait for the last dispatch to finish so its final polls ran.
  838. check(wait_task_done(auth, task_id_of("Char cap dispatch"), timeout=60) is not None,
  839. "char-cap task completes")
  840. conn = db()
  841. raw_session = conn.execute(
  842. "select s.id from sessions s join tasks t on t.id = s.task_id"
  843. " where t.title = 'Char cap dispatch' order by s.id desc limit 1").fetchone()[0]
  844. rows = conn.execute("select seq, chunk from session_raw_log where session_id = ?"
  845. " order by seq", (raw_session,)).fetchall()
  846. conn.close()
  847. check(len(rows) >= 3, "session_raw_log captured the daemon's chunks (%d)" % len(rows))
  848. seqs = [r[0] for r in rows]
  849. check(seqs == sorted(seqs) and len(set(seqs)) == len(seqs),
  850. "raw chunks stored once, seq strictly increasing")
  851. text = "".join(r[1] for r in rows)
  852. check(fake.PROMPT in text and "echo hello" in text and "hello" in text,
  853. "raw log keeps the prompt and echoed output byte-exact")
  854. check("stream-line-" in text, "incremental /log polls append later chunks")
  855. terminal = slot_public(auth, "/tasks/%d/terminal" % task_id_of("Char cap dispatch"),
  856. "terminal")
  857. check(terminal.get("has_raw_log") is True and int(terminal["session_id"]) == raw_session,
  858. "terminal view selects raw rendering for the raw session")
  859. # Old sessions (typed entries, no raw rows) keep the fallback view.
  860. conn = db()
  861. conn.execute("insert into session_commands (session_id, command_text, output_text,"
  862. " type, started_at) values (?, 'ls', 'old-output', 'command',"
  863. " strftime('%s','now'))", (session_id,))
  864. conn.commit()
  865. conn.close()
  866. legacy = slot_public(auth, "/tasks/%d/terminal" % plan_task, "terminal")
  867. check(legacy.get("has_raw_log") is False,
  868. "legacy session falls back to the entry-type terminal view")
  869. request = urllib.request.Request(WEB + "/terminal-stream/%d" % raw_session)
  870. with urllib.request.urlopen(request, timeout=15) as stream:
  871. raw_events = []
  872. deadline = time.monotonic() + 8
  873. while time.monotonic() < deadline and len(raw_events) < 3:
  874. line = stream.readline().decode().strip()
  875. if not line.startswith("data: ") or line == "data: ping":
  876. continue
  877. event = json.loads(line[6:])
  878. if event.get("type") == "raw":
  879. raw_events.append(event)
  880. check(len(raw_events) >= 3 and raw_events[0]["text"] == fake.PROMPT
  881. and raw_events[0]["seq"] < raw_events[1]["seq"],
  882. "terminal stream serves raw chunks in seq order (prompt first)")
  883. print("== capabilities: tag-based routing ==")
  884. saddles_state = slot_public(auth, "/saddles", "saddles")
  885. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  886. act(auth, saddles_state["create_capability"], {"name": "bigmem"})
  887. saddles_state = slot_public(auth, "/saddles", "saddles")
  888. caps = {c["name"]: c for c in saddles_state["capabilities"]}
  889. check(len(caps) == 2 and all(int(c["saddle_count"]) == 0 and int(c["task_count"]) == 0
  890. for c in caps.values()),
  891. "capabilities created and listed with zero usage")
  892. def saddle_card(name):
  893. rows = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  894. if s["name"] == name]
  895. return rows[0]
  896. fake_card = saddle_card("fake-saddle")
  897. check(fake_card["capabilities"] == [],
  898. "saddle card starts with no capability chips")
  899. # A task requiring 'gpu' waits while the only idle saddle lacks it;
  900. # a later task without requirements still dispatches (skip-and-continue).
  901. tasks_state = slot_public(auth, "/tasks", "tasks")
  902. act(auth, tasks_state["create"], {
  903. "project_id": "1",
  904. "title": "GPU task",
  905. "priority": "2",
  906. })
  907. gpu_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  908. if t["title"] == "GPU task"][0])
  909. detail = task_state(auth, gpu_task)
  910. act(auth, detail["attach_capability"], {"capability_id": str(int(caps["gpu"]["id"]))})
  911. detail = task_state(auth, gpu_task)
  912. check([c["name"] for c in detail["capabilities"]] == ["gpu"],
  913. "task page lists the required capability")
  914. # The only idle saddle lacks the tag, so the queue flags the wait
  915. # (read before any other task claims the idle saddle).
  916. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  917. if int(t["id"]) == gpu_task][0]
  918. check(queue["status"] == "queued" and queue["capabilities"] == ["gpu"]
  919. and queue.get("waiting_for_saddle") is True,
  920. "queue row shows the waiting task with its tag and wait flag")
  921. act(auth, tasks_state["create"], {
  922. "project_id": "1",
  923. "title": "Any-saddle task",
  924. "priority": "3",
  925. })
  926. any_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  927. if t["title"] == "Any-saddle task"][0])
  928. check(wait_for(lambda: task_state(auth, any_task).get("status") != "queued" or False,
  929. timeout=30, what="uncapable task dispatches") is not None,
  930. "task without requirements dispatches past the waiting task")
  931. with open(os.path.join(WORK, "app.log")) as handle:
  932. app_log = handle.read()
  933. check("waits for a capable saddle" in app_log and "requires: gpu" in app_log,
  934. "dispatcher logs the capability wait")
  935. # Attaching the tag to the saddle releases the task.
  936. fake_card = saddle_card("fake-saddle")
  937. act(auth, fake_card["attach_capability"], {"capability_id": str(int(caps["gpu"]["id"]))})
  938. fake_card = saddle_card("fake-saddle")
  939. check([c["name"] for c in fake_card["capabilities"]] == ["gpu"],
  940. "saddle card shows the attached chip")
  941. check(wait_task_done(auth, gpu_task, timeout=60) is not None,
  942. "task dispatches once the saddle carries the required tag")
  943. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  944. if int(t["id"]) == gpu_task][0]
  945. check(queue.get("waiting_for_saddle") is not True,
  946. "wait flag clears once dispatched")
  947. # Multi-tag: gpu + bigmem required, only gpu carried → waits; adding
  948. # bigmem completes the superset.
  949. act(auth, tasks_state["create"], {
  950. "project_id": "1",
  951. "title": "Big task",
  952. "priority": "2",
  953. })
  954. big_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  955. if t["title"] == "Big task"][0])
  956. detail = task_state(auth, big_task)
  957. act(auth, detail["attach_capability"], {"capability_id": str(int(caps["gpu"]["id"]))})
  958. act(auth, detail["attach_capability"], {"capability_id": str(int(caps["bigmem"]["id"]))})
  959. check(wait_for(lambda: ([t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  960. if int(t["id"]) == big_task][0].get("waiting_for_saddle")
  961. is True) or False, timeout=30, what="big task waits") is not None,
  962. "task waits when the saddle's tags are not a superset")
  963. fake_card = saddle_card("fake-saddle")
  964. act(auth, fake_card["attach_capability"], {"capability_id": str(int(caps["bigmem"]["id"]))})
  965. check(wait_task_done(auth, big_task, timeout=60) is not None,
  966. "task dispatches once the superset is complete")
  967. # Detach a requirement; delete a capability everywhere.
  968. detail = task_state(auth, big_task)
  969. act(auth, [c for c in detail["capabilities"] if c["name"] == "bigmem"][0]["detach"], {})
  970. check([c["name"] for c in task_state(auth, big_task)["capabilities"]] == ["gpu"],
  971. "detached requirement disappears from the task")
  972. bigmem_row = [c for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  973. if c["name"] == "bigmem"][0]
  974. act(auth, bigmem_row["delete"], {})
  975. saddles_state = slot_public(auth, "/saddles", "saddles")
  976. check(all(c["name"] != "bigmem" for c in saddles_state["capabilities"]),
  977. "deleted capability gone from the catalogue")
  978. check([c["name"] for c in task_state(auth, big_task)["capabilities"]] == ["gpu"],
  979. "deleting a capability drops its task requirements")
  980. check(all(c["name"] != "bigmem"
  981. for c in saddle_card("fake-saddle")["capabilities"]),
  982. "deleting a capability drops it from saddles")
  983. print("== B4: required capabilities on the create form ==")
  984. tasks_state = slot_public(auth, "/tasks", "tasks")
  985. gpu_option = [o for o in tasks_state.get("capability_options", [])
  986. if o["name"] == "gpu"][0]
  987. check(len(tasks_state.get("capability_options", [])) >= 1,
  988. "queue page offers capability options in the create form")
  989. conn = db()
  990. before = conn.execute("select count(*) from tasks").fetchone()[0]
  991. conn.close()
  992. act(auth, tasks_state["create"], {
  993. "project_id": "1",
  994. "title": "Bad cap task",
  995. "capability_id": [gpu_option["id"], "999"],
  996. })
  997. conn = db()
  998. after = conn.execute("select count(*) from tasks").fetchone()[0]
  999. conn.close()
  1000. check(after == before, "unknown capability id rejects the create")
  1001. act(auth, tasks_state["create"], {
  1002. "project_id": "1",
  1003. "title": "Cap-on-create task",
  1004. "capability_id": [gpu_option["id"]],
  1005. })
  1006. cap_create = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1007. if t["title"] == "Cap-on-create task"][0])
  1008. detail = task_state(auth, cap_create)
  1009. check([c["name"] for c in detail["capabilities"]] == ["gpu"],
  1010. "capabilities from the create form land on the task")
  1011. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1012. if int(t["id"]) == cap_create][0]
  1013. check(queue["capabilities"] == ["gpu"],
  1014. "queue row shows the created task's requirements")
  1015. # The waiting flag must hold it back until the capable saddle frees
  1016. # up (the fake saddle still carries gpu from the routing checks).
  1017. check(queue.get("waiting_for_saddle") is not True,
  1018. "capable saddle available: no wait flag on the new task")
  1019. print("== B6: computed display state ==")
  1020. conn = db()
  1021. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  1022. " values (1, 'Parent', 'done', 5, strftime('%s','now'))")
  1023. parent6 = conn.execute("select max(id) from tasks").fetchone()[0]
  1024. # The post-mortem case: stored done WITH an unanswered review block.
  1025. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  1026. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  1027. (parent6, fake_id))
  1028. session6 = conn.execute("select max(id) from sessions").fetchone()[0]
  1029. conn.commit()
  1030. conn.close()
  1031. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1032. {"type": "block", "session_id": session6, "data": {
  1033. "question": "Review the final diff", "type": "review"}})
  1034. detail = task_state(auth, parent6)
  1035. check(detail.get("display") == "review requested" and detail.get("terminal") is True,
  1036. "unanswered review overrides the stored done status (terminal flag keeps stored truth)")
  1037. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1038. if int(t["id"]) == parent6][0]
  1039. check(queue["display"] == "review requested",
  1040. "queue row shows the computed review-requested display")
  1041. # Delegation: with the review answered, open subtasks delegate.
  1042. conn = db()
  1043. conn.execute("update task_blocks set answered_at = strftime('%s','now'),"
  1044. " answer = 'Human approved the review' where task_id = ?", (parent6,))
  1045. conn.execute("insert into tasks (project_id, title, status, priority, parent_task_id,"
  1046. " created_at) values (1, 'Sub A', 'working', 5, ?, strftime('%s','now'))",
  1047. (parent6,))
  1048. conn.execute("insert into tasks (project_id, title, status, priority, parent_task_id,"
  1049. " created_at) values (1, 'Sub B', 'done', 5, ?, strftime('%s','now'))",
  1050. (parent6,))
  1051. conn.commit()
  1052. conn.close()
  1053. detail = task_state(auth, parent6)
  1054. check(detail.get("display") == "delegating 1/2" and detail.get("subtask_open") == 1,
  1055. "open subtasks show the delegating breakdown (%s)" % detail.get("display"))
  1056. # Flags track the stored status once the display falls through
  1057. # (subtasks terminal first — delegating leads while any are open).
  1058. conn = db()
  1059. conn.execute("update tasks set status = 'failed', completed_at = strftime('%s','now')"
  1060. " where id = ?", (parent6,))
  1061. conn.execute("update tasks set status = 'failed', completed_at = strftime('%s','now')"
  1062. " where title = 'Sub A'")
  1063. conn.commit()
  1064. conn.close()
  1065. detail = task_state(auth, parent6)
  1066. check(detail.get("display") == "failed" and detail.get("failed") is True
  1067. and detail.get("terminal") is True,
  1068. "failed task with answered review and terminal subtasks shows failed + terminal flags")
  1069. print("== retry + resume ==")
  1070. # A daemon-side failure fails the task with its explanation.
  1071. fake.fail_next = True
  1072. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1073. "project_id": "1",
  1074. "title": "Flaky task",
  1075. "priority": "2",
  1076. })
  1077. flaky = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1078. if t["title"] == "Flaky task"][0])
  1079. check(wait_for(lambda: task_state(auth, flaky).get("status") == "failed" or False,
  1080. timeout=60, what="flaky task fails") is not None,
  1081. "daemon failure fails the task")
  1082. detail = task_state(auth, flaky)
  1083. check("bash -n rejected" in (detail.get("summary") or ""),
  1084. "failure summary shows the daemon's explanation")
  1085. # Retry: summary moves into a comment and clears, task requeues,
  1086. # history stays, and the re-dispatch restores the workspace.
  1087. comments_before = len(detail.get("comments", []))
  1088. progress_before = len(detail.get("progress", []))
  1089. act(auth, detail["retry"], {})
  1090. detail = task_state(auth, flaky)
  1091. check(detail["status"] == "queued" and (detail.get("summary") or "") == "",
  1092. "retry requeues the task and clears the stale summary")
  1093. check(any("bash -n rejected" in c["body"] for c in detail["comments"]),
  1094. "failure explanation kept as a bot comment")
  1095. check(any(c["body"] == "Task retried by user" for c in detail["comments"]),
  1096. "retry lands its audit comment")
  1097. check(len(detail["comments"]) >= comments_before + 1,
  1098. "retry keeps the comment history")
  1099. check(wait_task_done(auth, flaky, timeout=60) is not None,
  1100. "retried task dispatches again and completes")
  1101. detail = task_state(auth, flaky)
  1102. check(any("restored the session context" in p["summary"]
  1103. for p in detail.get("progress", [])),
  1104. "daemon resume reported on the first status after the restore")
  1105. check(len(detail["progress"]) > progress_before,
  1106. "resume note appended to the progress timeline")
  1107. # Manual resume: a task stuck working on an offline saddle.
  1108. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1109. "project_id": "1",
  1110. "title": "Stuck task",
  1111. "priority": "2",
  1112. })
  1113. stuck = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1114. if t["title"] == "Stuck task"][0])
  1115. check(wait_for(lambda: task_state(auth, stuck).get("status") == "working" or False,
  1116. timeout=60, what="stuck task starts working") is not None,
  1117. "stuck task reaches working")
  1118. conn = db()
  1119. conn.execute("update saddles set status = 'offline' where name = 'fake-saddle'")
  1120. conn.commit()
  1121. conn.close()
  1122. detail = task_state(auth, stuck)
  1123. check(detail.get("resume_available") is True,
  1124. "task page offers resume while its saddle is offline")
  1125. act(auth, detail["resume"], {})
  1126. detail = task_state(auth, stuck)
  1127. check(detail["status"] == "queued",
  1128. "manual resume requeues the stuck task")
  1129. check(any(c["body"] == "Saddle became unreachable; task requeued"
  1130. for c in detail["comments"]),
  1131. "manual resume lands the interruption comment")
  1132. check(all(s["status"] == "offline"
  1133. for s in slot_public(auth, "/saddles", "saddles")["saddles"]),
  1134. "saddle stays offline after the manual requeue")
  1135. # Bringing the saddle back lets the requeued task resume and finish.
  1136. fake.state = "idle"
  1137. fake_card = saddle_card("fake-saddle")
  1138. act(auth, fake_card["refresh"], {})
  1139. check(any(s["status"] == "idle"
  1140. for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1141. if s["name"] == "fake-saddle"),
  1142. "refreshed saddle returns idle")
  1143. check(wait_task_done(auth, stuck, timeout=60) is not None,
  1144. "requeued task resumes on the refreshed saddle and completes")
  1145. print("== rejected entries (non-fatal) ==")
  1146. # Ingest API: a rejected entry stores on the session and streams
  1147. # through SSE; the task is untouched.
  1148. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1149. {"type": "output", "session_id": session_id, "data": {
  1150. "command": "bash -n script.sh",
  1151. "output": "syntax error near line 3 (recoverable)",
  1152. "exit_code": 1,
  1153. "type": "rejected"}})
  1154. check(status == 200, "rejected entry accepted by the ingest API")
  1155. request = urllib.request.Request(WEB + "/terminal-stream/%d" % session_id)
  1156. with urllib.request.urlopen(request, timeout=15) as stream:
  1157. rejected_event = None
  1158. deadline = time.monotonic() + 8
  1159. while time.monotonic() < deadline and rejected_event is None:
  1160. line = stream.readline().decode().strip()
  1161. if not line.startswith("data: ") or line == "data: ping":
  1162. continue
  1163. event = json.loads(line[6:])
  1164. if event.get("type") == "rejected":
  1165. rejected_event = event
  1166. check(rejected_event is not None
  1167. and "syntax error near line 3" in (rejected_event.get("output") or ""),
  1168. "terminal stream carries rejected entries with their reason")
  1169. # The page template renders them with the distinct non-fatal style.
  1170. status, page = http("GET", "/tasks/%d/terminal" % stuck, timeout=15)
  1171. check(status == 200 and "term-rejected" in page,
  1172. "terminal page renders rejected entries in their own style")
  1173. print("== B8: ANSI SGR in the terminal view ==")
  1174. # Byte-exact SGR delivery: the daemon's coloured chunks flow through
  1175. # the store + SSE untouched (the client renderer styles them).
  1176. coloured = "\x1b[1;32mbold green\x1b[0m then \x1b[38;5;196m256-red\x1b[0m\n"
  1177. conn = db()
  1178. conn.execute("insert into session_raw_log (session_id, seq, chunk)"
  1179. " values (?, 900, ?)", (session_id, coloured))
  1180. conn.commit()
  1181. conn.close()
  1182. request = urllib.request.Request(WEB + "/terminal-stream/%d" % session_id)
  1183. with urllib.request.urlopen(request, timeout=15) as stream:
  1184. coloured_event = None
  1185. deadline = time.monotonic() + 8
  1186. while time.monotonic() < deadline and coloured_event is None:
  1187. line = stream.readline().decode().strip()
  1188. if not line.startswith("data: ") or line == "data: ping":
  1189. continue
  1190. event = json.loads(line[6:])
  1191. if event.get("type") == "raw" and "\x1b[1;32m" in (event.get("text") or ""):
  1192. coloured_event = event
  1193. check(coloured_event is not None
  1194. and "\x1b[38;5;196m" in coloured_event["text"],
  1195. "SGR sequences stream byte-exact to the client renderer")
  1196. status, page = http("GET", "/tasks/%d/terminal" % stuck, timeout=15)
  1197. check(status == 200 and "makeAnsiRenderer" in page and "colour256" in page,
  1198. "terminal page embeds the ANSI renderer (SGR + 256-colour palette)")
  1199. # Dispatch path: a rejected entry from /output flows into the audit
  1200. # trail without failing (or finishing) the task.
  1201. fake.queue_output("rejected", "echo 'too long' | saddle",
  1202. "max_tokens exceeded (recoverable)")
  1203. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1204. "project_id": "1",
  1205. "title": "Rejected ride",
  1206. "priority": "2",
  1207. })
  1208. rejected_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1209. if t["title"] == "Rejected ride"][0])
  1210. check(wait_task_done(auth, rejected_task, timeout=60) is not None,
  1211. "task completes normally past rejected entries")
  1212. conn = db()
  1213. stored = conn.execute(
  1214. "select count(*) from session_commands sc join sessions s on s.id = sc.session_id"
  1215. " where s.task_id = ? and sc.type = 'rejected'", (rejected_task,)).fetchone()[0]
  1216. conn.close()
  1217. check(stored >= 1,
  1218. "rejected entries stored in the audit trail (%d rows)" % stored)
  1219. check(task_state(auth, rejected_task)["status"] == "done"
  1220. and "fake daemon finished" in (task_state(auth, rejected_task).get("summary") or ""),
  1221. "rejected entries never fail the task")
  1222. print("== B7: suspended state + per-subtask resume ==")
  1223. fake.suspend_after_start = True
  1224. pushes_before = len(fake.start_payloads)
  1225. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1226. "project_id": "1",
  1227. "title": "Suspend parent",
  1228. "priority": "2",
  1229. })
  1230. parent7 = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1231. if t["title"] == "Suspend parent"][0])
  1232. check(wait_for(lambda: task_state(auth, parent7).get("status") == "suspended"
  1233. or False, timeout=60, what="parent parks as suspended") is not None,
  1234. "daemon 'suspended' state parks the task")
  1235. detail = task_state(auth, parent7)
  1236. check(detail.get("display") == "waiting on subtasks",
  1237. "suspended task displays as waiting on subtasks")
  1238. check(any(s["status"] == "idle"
  1239. for s in slot_public(auth, "/saddles", "saddles")["saddles"]),
  1240. "suspension frees the saddle")
  1241. first_push = fake.start_payloads[pushes_before]
  1242. check(first_push.get("subtasks") == [],
  1243. "the /start payload carries the subtasks array (empty here)")
  1244. # Two subtask events land while parked (staged, not dispatched):
  1245. # both must coalesce into one resume with a full report.
  1246. conn = db()
  1247. conn.execute("insert into tasks (project_id, title, status, priority, parent_task_id,"
  1248. " summary, completed_at, created_at) values (1, 'Child one', 'done', 5, ?,"
  1249. " 'built and verified the flange', strftime('%s','now','+1 second'),"
  1250. " strftime('%s','now'))", (parent7,))
  1251. conn.execute("insert into tasks (project_id, title, status, priority, parent_task_id,"
  1252. " summary, completed_at, created_at) values (1, 'Child two', 'failed', 5, ?,"
  1253. " 'the harness refused to start', strftime('%s','now','+1 second'),"
  1254. " strftime('%s','now'))", (parent7,))
  1255. conn.commit()
  1256. conn.close()
  1257. def parent_push_count():
  1258. return len([p for p in fake.start_payloads
  1259. if int(p.get("task", {}).get("id") or 0) == parent7])
  1260. check(wait_for(lambda: parent_push_count() >= 2 or False,
  1261. timeout=45, what="suspended parent resumes") is not None,
  1262. "subtask events resume the suspended parent")
  1263. parent_pushes = [p for p in fake.start_payloads
  1264. if int(p.get("task", {}).get("id") or 0) == parent7]
  1265. check(len(parent_pushes) >= 2,
  1266. "the parent's resume is a fresh /start for the same task")
  1267. resume_push = parent_pushes[-1]
  1268. notice = resume_push.get("resume_notice") or ""
  1269. check("Child one" in notice and "completed" in notice
  1270. and "built and verified the flange" in notice,
  1271. "resume notice reports the finished subtask with its summary")
  1272. check("Child two" in notice and "failed" in notice
  1273. and "the harness refused to start" in notice,
  1274. "coalesced: the second event rides the same resume notice")
  1275. subtask_entries = {(s["title"], s["status"]) for s in resume_push.get("subtasks", [])}
  1276. check(("Child one", "done") in subtask_entries
  1277. and ("Child two", "failed") in subtask_entries,
  1278. "subtasks array carries the children's states at dispatch time")
  1279. check(wait_task_done(auth, parent7, timeout=60) is not None,
  1280. "resumed parent completes")
  1281. detail = task_state(auth, parent7)
  1282. check(any("restored the session context" in p["summary"]
  1283. for p in detail.get("progress", [])),
  1284. "resumed flag reported on the first status after the restore")
  1285. print("== R3 B1: subtask status push ==")
  1286. # A parked (suspended) parent gives delivery a stable open session.
  1287. fake.suspend_after_start = True
  1288. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1289. "project_id": "1",
  1290. "title": "Push parent",
  1291. "priority": "2",
  1292. })
  1293. push_parent = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1294. if t["title"] == "Push parent"][0])
  1295. check(wait_for(lambda: task_state(auth, push_parent).get("status") == "suspended"
  1296. or False, timeout=60, what="push parent parks") is not None,
  1297. "push parent parks with an open session")
  1298. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1299. "project_id": "1",
  1300. "title": "Push child",
  1301. "parent_task_id": str(push_parent),
  1302. })
  1303. push_child = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1304. if t["title"] == "Push child"][0])
  1305. def events_for(subtask_id):
  1306. return [e for e in fake.subtask_status_events
  1307. if int(e.get("subtask_id") or 0) == subtask_id]
  1308. check(wait_for(lambda: len(events_for(push_child)) > 0 or False,
  1309. timeout=30, what="queued subtask event") is not None,
  1310. "subtask creation pushes a queued status event")
  1311. first_event = events_for(push_child)[0]
  1312. check(int(first_event.get("parent_task_id") or 0) == push_parent
  1313. and first_event.get("title") == "Push child"
  1314. and first_event.get("status") in ("queued", "working"),
  1315. "status event carries parent id, title and a wire status (%s)"
  1316. % first_event.get("status"))
  1317. # Real lifecycle: the child dispatches (working) and completes (done
  1318. # with summary) — the parent's daemon hears every transition.
  1319. check(wait_for(lambda: any(e.get("status") == "done" and "finished" in (e.get("summary") or "")
  1320. for e in events_for(push_child)) or False,
  1321. timeout=90, what="done subtask event") is not None,
  1322. "subtask completion pushes done with the summary")
  1323. check(any(e.get("status") == "working" for e in events_for(push_child)),
  1324. "dispatch pushes a working status event")
  1325. # Best-effort retry: while the daemon 500s, events stay queued and
  1326. # land once it recovers.
  1327. fake.fail_subtask_status = True
  1328. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1329. "project_id": "1",
  1330. "title": "Push child two",
  1331. "parent_task_id": str(push_parent),
  1332. })
  1333. push_child_two = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1334. if t["title"] == "Push child two"][0])
  1335. time.sleep(7)
  1336. check(len(events_for(push_child_two)) == 0,
  1337. "failed pushes stay queued (no event delivered)")
  1338. fake.fail_subtask_status = False
  1339. check(wait_for(lambda: len(events_for(push_child_two)) > 0 or False,
  1340. timeout=30, what="retried subtask event") is not None,
  1341. "recovered pushes deliver on a later tick")
  1342. print("== R3 B2: stale-busy saddle healing ==")
  1343. # The observed incident: a saddle left busy with current_task_id 0.
  1344. conn = db()
  1345. conn.execute("update saddles set status = 'busy', current_task_id = 0,"
  1346. " allocated_at = strftime('%s','now') where name = 'fake-saddle'")
  1347. conn.commit()
  1348. conn.close()
  1349. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1350. "project_id": "1",
  1351. "title": "Heal dispatch",
  1352. "priority": "2",
  1353. })
  1354. heal_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1355. if t["title"] == "Heal dispatch"][0])
  1356. check(wait_task_done(auth, heal_task, timeout=60) is not None,
  1357. "busy-without-task heals and the queued task dispatches")
  1358. with open(os.path.join(WORK, "app.log")) as handle:
  1359. app_log = handle.read()
  1360. check("Healing stale-busy saddle" in app_log
  1361. and "busy with no current task" in app_log,
  1362. "the busy@0 heal is logged")
  1363. # Contradiction: the daemon reports idle while the web believes the
  1364. # saddle is running the orphaned task.
  1365. conn = db()
  1366. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  1367. " values (1, 'Orphan task', 'working', 2, strftime('%s','now'))")
  1368. orphan = conn.execute("select max(id) from tasks").fetchone()[0]
  1369. conn.execute("update saddles set status = 'busy', current_task_id = ?,"
  1370. " allocated_at = strftime('%s','now') where name = 'fake-saddle'",
  1371. (orphan,))
  1372. conn.commit()
  1373. conn.close()
  1374. fake.state = "idle"
  1375. check(wait_task_done(auth, orphan, timeout=60) is not None,
  1376. "contradicted saddle heals, orphan requeues and completes")
  1377. with open(os.path.join(WORK, "app.log")) as handle:
  1378. app_log = handle.read()
  1379. check("daemon idle while the web believes" in app_log,
  1380. "the contradiction heal is logged")
  1381. print("== R4 B1: synchronous subtask callback ==")
  1382. conn = db()
  1383. callback_rows = conn.execute(
  1384. "select token from api_tokens where saddle_id = 0"
  1385. " and token like 'saddle-callback-%'").fetchall()
  1386. conn.close()
  1387. r4_token = callback_rows[0][0] if callback_rows else callback_token
  1388. # Parent with a live parked session (suspended) hosts the callback.
  1389. fake.suspend_after_start = True
  1390. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1391. "project_id": "1",
  1392. "title": "Callback parent",
  1393. "priority": "2",
  1394. })
  1395. cb_parent = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1396. if t["title"] == "Callback parent"][0])
  1397. check(wait_for(lambda: task_state(auth, cb_parent).get("status") == "suspended"
  1398. or False, timeout=60, what="callback parent parks") is not None,
  1399. "callback parent parks")
  1400. status, _ = saddle_api("POST", "/api/saddle/subtask", None,
  1401. {"parent_task_id": cb_parent, "title": "no token"})
  1402. check(status == 401, "subtask callback rejects a missing token")
  1403. anchor = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1404. if t["title"] == "Heal dispatch"][0])
  1405. status, body = saddle_api("POST", "/api/saddle/subtask", r4_token, {
  1406. "parent_task_id": cb_parent,
  1407. "title": "Wire the flange",
  1408. "description": "torque to spec",
  1409. "depends_on": [anchor],
  1410. "session_id": 1,
  1411. })
  1412. check(status == 200 and body.get("ok") is True and int(body.get("task_id") or 0) > 0,
  1413. "callback creates the subtask synchronously")
  1414. subtask_id = int(body.get("task_id"))
  1415. detail = task_state(auth, subtask_id)
  1416. check(detail["title"] == "Wire the flange" and int(detail["project_id"]) == 1
  1417. and int(detail["parent_task_id"]) == cb_parent,
  1418. "subtask row inherits the parent's project and linkage")
  1419. check(detail.get("task_branch") == task_state(auth, cb_parent).get("task_branch"),
  1420. "subtask shares the parent's task branch")
  1421. conn = db()
  1422. dep_rows = conn.execute(
  1423. "select depends_on_task_id from task_dependencies where task_id = ?",
  1424. (subtask_id,)).fetchall()
  1425. conn.close()
  1426. check([r[0] for r in dep_rows] == [anchor],
  1427. "depends_on wired as task_dependencies")
  1428. # Idempotency + entry-poll fallback dedup.
  1429. status, body2 = saddle_api("POST", "/api/saddle/subtask", r4_token, {
  1430. "parent_task_id": cb_parent, "title": "Wire the flange"})
  1431. check(status == 200 and int(body2.get("task_id") or 0) == subtask_id,
  1432. "retried callback returns the same task id")
  1433. conn = db()
  1434. before = conn.execute("select count(*) from tasks where parent_task_id = ?",
  1435. (cb_parent,)).fetchone()[0]
  1436. conn.close()
  1437. conn = db()
  1438. cb_session = conn.execute(
  1439. "select id from sessions where task_id = ? and ended_at is null",
  1440. (cb_parent,)).fetchone()[0]
  1441. conn.close()
  1442. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1443. {"type": "subtask", "session_id": cb_session, "data": {
  1444. "title": "Wire the flange", "description": "again"}})
  1445. conn = db()
  1446. after = conn.execute("select count(*) from tasks where parent_task_id = ?",
  1447. (cb_parent,)).fetchone()[0]
  1448. timeline = conn.execute(
  1449. "select count(*) from session_commands where session_id = ?"
  1450. " and type = 'subtask'", (cb_session,)).fetchone()[0]
  1451. conn.close()
  1452. check(after == before,
  1453. "entry-poll fallback dedupes against the callback's row")
  1454. check(timeline >= 1, "timeline entry recorded on the parent's session")
  1455. # Validation: unknown parent, unknown depends_on, ancestor cycle.
  1456. status, body = saddle_api("POST", "/api/saddle/subtask", r4_token,
  1457. {"parent_task_id": 99999, "title": "ghost"})
  1458. check(status == 400, "unknown parent rejected")
  1459. status, body = saddle_api("POST", "/api/saddle/subtask", r4_token,
  1460. {"parent_task_id": cb_parent, "title": "bad dep",
  1461. "depends_on": [99999]})
  1462. check(status == 400 and "unknown task" in body.get("error", ""),
  1463. "unknown depends_on id rejected with a clear error")
  1464. status, body = saddle_api("POST", "/api/saddle/subtask", r4_token,
  1465. {"parent_task_id": cb_parent, "title": "cycle dep",
  1466. "depends_on": [cb_parent]})
  1467. check(status == 400 and "cycle" in body.get("error", ""),
  1468. "depending on an ancestor rejected as a cycle")
  1469. print("== R4 B2: subtask auto-approve ==")
  1470. # Settle earlier stragglers first: the round-3/B1 suspended parents
  1471. # resume (a fresh /start) once their last subtask completes — those
  1472. # pushes would consume the one-shot suspend flag below.
  1473. check(wait_task_done(auth, push_parent, timeout=90) is not None
  1474. and wait_task_done(auth, push_child_two, timeout=90) is not None
  1475. and wait_task_done(auth, cb_parent, timeout=90) is not None,
  1476. "earlier suspended parents settle before the auto-approve run")
  1477. # Parent parks; its toggle then covers all descendants. Children are
  1478. # created with an unmet 'gpu' requirement so they stay queued (and
  1479. # untouched) until the requirement is lifted for the final-resume leg.
  1480. fake.suspend_after_start = True
  1481. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1482. "project_id": "1",
  1483. "title": "Auto parent",
  1484. "priority": "2",
  1485. })
  1486. auto_parent = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1487. if t["title"] == "Auto parent"][0])
  1488. check(wait_for(lambda: task_state(auth, auto_parent).get("status") == "suspended"
  1489. or False, timeout=60, what="auto parent parks") is not None,
  1490. "auto parent parks")
  1491. detail = task_state(auth, auto_parent)
  1492. check(detail.get("auto_approve") is False,
  1493. "auto-approve defaults to off")
  1494. act(auth, detail["toggle_auto_approve"], {})
  1495. check(task_state(auth, auto_parent).get("auto_approve") is True,
  1496. "toggle turns auto-approve on")
  1497. gpu_option = int([o["id"] for o in slot_public(auth, "/tasks", "tasks")["capability_options"]
  1498. if o["name"] == "gpu"][0])
  1499. status, body = saddle_api("POST", "/api/saddle/subtask", r4_token,
  1500. {"parent_task_id": auto_parent,
  1501. "title": "Auto child", "depends_on": []})
  1502. auto_child = int(body["task_id"])
  1503. status, body = saddle_api("POST", "/api/saddle/subtask", r4_token,
  1504. {"parent_task_id": auto_child, "title": "Auto grandchild"})
  1505. auto_grand = int(body["task_id"])
  1506. act(auth, task_state(auth, auto_child)["attach_capability"],
  1507. {"capability_id": str(gpu_option)})
  1508. act(auth, task_state(auth, auto_grand)["attach_capability"],
  1509. {"capability_id": str(gpu_option)})
  1510. # Transitive coverage: the GRANDCHILD's review is auto-answered
  1511. # (any ancestor set), answered-by 'auto', timeline entry recorded.
  1512. conn = db()
  1513. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  1514. " values (?, ?, strftime('%s','now'))", (auto_grand, fake_id))
  1515. conn.commit()
  1516. grand_session = conn.execute("select max(id) from sessions").fetchone()[0]
  1517. conn.close()
  1518. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1519. {"type": "review", "session_id": grand_session, "data": {
  1520. "summary": "the flange is wired"}})
  1521. grand_detail = task_state(auth, auto_grand)
  1522. grand_review = [b for b in grand_detail["blocks"] if b["block_type"] == "review"][0]
  1523. check(grand_review.get("answered") is True
  1524. and grand_review.get("answer") == "Auto-approved (subtask auto-approve is on)"
  1525. and grand_review.get("answered_by") == "auto",
  1526. "covered grandchild review auto-answered as 'auto'")
  1527. conn = db()
  1528. timeline_auto = conn.execute(
  1529. "select count(*) from session_commands where session_id = ?"
  1530. " and type = 'auto-approve'", (grand_session,)).fetchone()[0]
  1531. conn.close()
  1532. check(timeline_auto >= 1, "auto action visible in the timeline")
  1533. # Questions and RFCs still block for a human.
  1534. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1535. {"type": "block", "session_id": grand_session, "data": {
  1536. "question": "Which torque spec?", "type": "question"}})
  1537. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1538. {"type": "block", "session_id": grand_session, "data": {
  1539. "question": "RFC: approve the design", "type": "rfc",
  1540. "body": "# Design"}})
  1541. grand_detail = task_state(auth, auto_grand)
  1542. check(all(b.get("answered") is not True for b in grand_detail["blocks"]
  1543. if b["block_type"] in ("question", "rfc")),
  1544. "questions and RFCs are never auto-answered")
  1545. # The toggle covers DESCENDANTS only: the parent's own review waits.
  1546. conn = db()
  1547. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at,"
  1548. " outcome) values (?, ?, strftime('%s','now'), strftime('%s','now'),"
  1549. " 'done')", (auto_parent, fake_id))
  1550. conn.commit()
  1551. parent_session = conn.execute("select max(id) from sessions").fetchone()[0]
  1552. conn.close()
  1553. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1554. {"type": "review", "session_id": parent_session, "data": {
  1555. "summary": "the whole change"}})
  1556. parent_detail = task_state(auth, auto_parent)
  1557. parent_review = [b for b in parent_detail["blocks"] if b["block_type"] == "review"][0]
  1558. check(parent_review.get("answered") is not True,
  1559. "the top-level parent's own review is never auto-approved")
  1560. # All descendants terminal → the suspended parent resumes with the
  1561. # final-review instruction (lift the capability requirement first).
  1562. act(auth, task_state(auth, auto_child)["capabilities"][0]["detach"], {})
  1563. act(auth, task_state(auth, auto_grand)["capabilities"][0]["detach"], {})
  1564. def pushes_for(task_id):
  1565. return len([p for p in fake.start_payloads
  1566. if int(p.get("task", {}).get("id") or 0) == task_id])
  1567. before_pushes = pushes_for(auto_parent)
  1568. check(wait_for(lambda: pushes_for(auto_parent) > before_pushes or False,
  1569. timeout=90, what="auto parent resumes") is not None,
  1570. "terminal subtasks resume the suspended parent")
  1571. notice = ""
  1572. for p in fake.start_payloads:
  1573. if int(p.get("task", {}).get("id") or 0) == auto_parent:
  1574. notice = p.get("resume_notice") or ""
  1575. check("All subtasks are complete" in notice
  1576. and "ONE final review" in notice and "saddle review" in notice,
  1577. "resume notice ends with the final-review instruction")
  1578. print("== R4 B3: dispatch-failure observability ==")
  1579. # A dead saddle that alone carries the required tag attracts the
  1580. # dispatch; the push fails and the task learns why via a bot comment.
  1581. saddles_state = slot_public(auth, "/saddles", "saddles")
  1582. act(auth, saddles_state["register"], {"name": "dead-saddle",
  1583. "host": "127.0.0.1:1"})
  1584. dead_row = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1585. if s["name"] == "dead-saddle"][0]
  1586. act(auth, dead_row["attach_capability"], {"capability_id": str(gpu_option)})
  1587. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1588. "project_id": "1",
  1589. "title": "Dead saddle task",
  1590. "capability_id": [str(gpu_option)],
  1591. })
  1592. dead_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1593. if t["title"] == "Dead saddle task"][0])
  1594. check(wait_for(lambda: any("assignment push failed" in c["body"]
  1595. for c in task_state(auth, dead_task).get("comments", []))
  1596. or False, timeout=60, what="push-failure comment") is not None,
  1597. "failed push writes the reason on the task")
  1598. check(task_state(auth, dead_task)["status"] == "queued",
  1599. "push-failed task returns to the queue")
  1600. dead_rows = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1601. if s["name"] == "dead-saddle"]
  1602. check(dead_rows[0]["status"] == "offline",
  1603. "the failing saddle goes offline")
  1604. act(auth, dead_rows[0]["unregister"], {})
  1605. conn = db()
  1606. conn.execute("delete from task_capabilities where capability_id = ?"
  1607. " and task_id = ?", (gpu_option, dead_task))
  1608. conn.commit()
  1609. conn.close()
  1610. check(wait_task_done(auth, dead_task, timeout=60) is not None,
  1611. "the task recovers on the healthy saddle")
  1612. # Tasks caught working on a saddle that went offline requeue with a
  1613. # bot comment each tick.
  1614. fake.suspend_after_start = False
  1615. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1616. "project_id": "1",
  1617. "title": "Offline saddle task",
  1618. "priority": "2",
  1619. })
  1620. offline_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1621. if t["title"] == "Offline saddle task"][0])
  1622. check(wait_for(lambda: task_state(auth, offline_task).get("status") == "working"
  1623. or False, timeout=60, what="offline task starts working") is not None,
  1624. "task reaches working before its saddle disappears")
  1625. conn = db()
  1626. conn.execute("update saddles set status = 'offline' where name = 'fake-saddle'")
  1627. conn.commit()
  1628. conn.close()
  1629. # The requeue frees the saddle in the same tick, so 'queued' is
  1630. # transient; the durable evidence is the bot comment (and the task
  1631. # completing again on the healthy daemon).
  1632. check(wait_for(lambda: any(c["body"] == "saddle went offline; task requeued"
  1633. for c in task_state(auth, offline_task).get("comments", []))
  1634. or False, timeout=30, what="offline requeue comment") is not None,
  1635. "offline saddle requeues the task")
  1636. check(wait_task_done(auth, offline_task, timeout=60) is not None,
  1637. "requeued task completes again on the healthy daemon")
  1638. print("== R5 B1: /start parent context ==")
  1639. # A fresh subtask dispatch carries the parent object (plan clamped).
  1640. conn = db()
  1641. conn.execute("update tasks set plan = ? where id = ?",
  1642. ("# Parent plan\n\n" + "step. " * 1200, auto_parent))
  1643. conn.commit()
  1644. conn.close()
  1645. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1646. "project_id": "1",
  1647. "title": "Lineage subtask",
  1648. "priority": "3",
  1649. })
  1650. lineage_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1651. if t["title"] == "Lineage subtask"][0])
  1652. conn = db()
  1653. conn.execute("update tasks set parent_task_id = ?, description = 'torque to spec'"
  1654. " where id = ?", (auto_parent, lineage_task))
  1655. conn.commit()
  1656. conn.close()
  1657. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == lineage_task
  1658. for p in fake.start_payloads) or False,
  1659. timeout=60, what="lineage subtask dispatches") is not None,
  1660. "lineage subtask dispatches")
  1661. lineage_push = [p for p in fake.start_payloads
  1662. if int(p.get("task", {}).get("id") or 0) == lineage_task][-1]
  1663. parent_obj = lineage_push.get("parent")
  1664. check(parent_obj is not None
  1665. and int(parent_obj.get("id") or 0) == auto_parent
  1666. and parent_obj.get("title") == "Auto parent"
  1667. and parent_obj.get("status") in ("suspended", "working", "done"),
  1668. "subtask /start carries the parent object")
  1669. check(parent_obj.get("description") == "torque to spec"
  1670. or "Parent plan" in (parent_obj.get("plan") or ""),
  1671. "parent description/plan content flows through")
  1672. check(len(parent_obj.get("plan") or "") <= 4000,
  1673. "parent plan clamped to ~4000 chars (%d)"
  1674. % len(parent_obj.get("plan") or ""))
  1675. root_pushes = [p for p in fake.start_payloads
  1676. if int(p.get("task", {}).get("id") or 0) == offline_task]
  1677. check(all("parent" not in p for p in root_pushes),
  1678. "root task /start carries no parent object")
  1679. print("== R5 B2: task-reading API ==")
  1680. status, _ = saddle_api("GET", "/api/saddle/tasks", None)
  1681. check(status == 401, "tasks endpoint rejects a missing token")
  1682. status, _ = saddle_api("GET", "/api/saddle/task/%d" % auto_child, None)
  1683. check(status == 401, "task detail endpoint rejects a missing token")
  1684. status, body = saddle_api("GET", "/api/saddle/tasks", r4_token)
  1685. check(status == 200 and len(body.get("tasks", [])) > 5,
  1686. "tasks endpoint lists tasks without filters")
  1687. row = [t for t in body["tasks"] if int(t["id"]) == auto_child][0]
  1688. check(row["title"] == "Auto child" and int(row["parent_task_id"]) == auto_parent
  1689. and row["status"] in ("done", "queued", "working"),
  1690. "compact rows carry id/title/status/parent_task_id")
  1691. status, body = saddle_api("GET", "/api/saddle/tasks?project_id=1", r4_token)
  1692. other_project = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  1693. if p["name"] == "diff-fabrica"][0])
  1694. check(all(True for _ in [1]) # project 1 dominates the data set
  1695. and not any(int(t["id"]) == 0 for t in body["tasks"]),
  1696. "project_id filter accepted")
  1697. status, body = saddle_api("GET",
  1698. "/api/saddle/tasks?project_id=%d" % other_project, r4_token)
  1699. check(all(t["title"].startswith("Diff") for t in body["tasks"]),
  1700. "other project lists only its own tasks")
  1701. status, body = saddle_api("GET", "/api/saddle/tasks?q=FLANGE", r4_token)
  1702. titles = [t["title"] for t in body["tasks"]]
  1703. check("Wire the flange" in titles,
  1704. "q matches titles case-insensitively")
  1705. status, body = saddle_api("GET", "/api/saddle/tasks?q=torque%20to%20spec", r4_token)
  1706. check(any(t["title"] == "Lineage subtask" for t in body["tasks"]),
  1707. "q matches description text")
  1708. status, body = saddle_api("GET", "/api/saddle/tasks?q=parent%20plan", r4_token)
  1709. check(any(t["title"] == "Auto parent" for t in body["tasks"]),
  1710. "q matches plan text")
  1711. status, body = saddle_api("GET", "/api/saddle/task/%d" % auto_child, r4_token)
  1712. task_view = body.get("task", {})
  1713. check(status == 200 and int(task_view.get("id") or 0) == auto_child
  1714. and task_view.get("parent_title") == "Auto parent"
  1715. and int(task_view.get("parent_task_id") or 0) == auto_parent,
  1716. "single-task view joins the parent title")
  1717. check("status" in task_view and "description" in task_view
  1718. and "plan" in task_view and "summary" in task_view,
  1719. "single-task view carries the full detail fields")
  1720. status, body = saddle_api("GET", "/api/saddle/task/99999", r4_token)
  1721. check(status == 404, "unknown task id returns 404")
  1722. print("== R6 F1: a hanging request cannot freeze the tick ==")
  1723. # One wedged /output (never responds) blocks a poll; the Soup
  1724. # timeout must fail it and later ticks keep dispatching.
  1725. task_state(auth, lineage_task)
  1726. conn = db()
  1727. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  1728. " values (1, 'Hang survivor', 'queued', 2, strftime('%s','now'))")
  1729. hang_task = conn.execute("select max(id) from tasks").fetchone()[0]
  1730. conn.close()
  1731. fake.hang_next["/output"] = 1
  1732. # Dispatch a task first so a poll is in flight against the hang,
  1733. # then verify a later task still dispatches (tick not frozen).
  1734. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1735. "project_id": "1",
  1736. "title": "Hang runner",
  1737. "priority": "3",
  1738. })
  1739. hang_runner = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1740. if t["title"] == "Hang runner"][0])
  1741. check(wait_task_done(auth, hang_runner, timeout=90) is not None,
  1742. "dispatching task survives a hung daemon request")
  1743. # The hung poll itself fails after the timeout; its task requeues
  1744. # or completes on later ticks — the system kept moving either way.
  1745. with open(os.path.join(WORK, "app.log")) as handle:
  1746. app_log = handle.read()
  1747. check("tick exceeded" not in app_log or "Dispatch tick failed" in app_log,
  1748. "a hung request never freezes the tick latch")
  1749. print("== R6 F2: refresh must not corrupt parked bookkeeping ==")
  1750. fake.suspend_after_start = True
  1751. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1752. "project_id": "1",
  1753. "title": "Parked refresh parent",
  1754. "priority": "2",
  1755. })
  1756. parked = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1757. if t["title"] == "Parked refresh parent"][0])
  1758. check(wait_for(lambda: task_state(auth, parked).get("status") == "suspended"
  1759. or False, timeout=60, what="parked parent suspends") is not None,
  1760. "parent parks before the refresh")
  1761. fake_card = saddle_card("fake-saddle")
  1762. act(auth, fake_card["refresh"], {})
  1763. fake_card = saddle_card("fake-saddle")
  1764. check(fake_card["status"] == "idle" and int(fake_card["current_task_id"] or 0) == 0,
  1765. "refresh on a parked (suspended) daemon leaves the saddle idle")
  1766. # The parked task keeps its open session and resumes normally.
  1767. conn = db()
  1768. conn.execute("insert into tasks (project_id, title, status, priority, parent_task_id,"
  1769. " summary, completed_at, created_at) values (1, 'Parked child', 'done', 5,"
  1770. " ?, 'child finished', strftime('%s','now','+1 second'),"
  1771. " strftime('%s','now'))", (parked,))
  1772. conn.commit()
  1773. conn.close()
  1774. check(wait_task_done(auth, parked, timeout=90) is not None,
  1775. "parked parent still resumes after the refresh")
  1776. print("== R6 F3: raw-log probe retries instead of deciding once ==")
  1777. fake.suspend_after_start = False
  1778. fake.fail_log_count = 1 # the seed-time probe fails exactly once
  1779. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1780. "project_id": "1",
  1781. "title": "Raw retry task",
  1782. "priority": "2",
  1783. })
  1784. raw_retry = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1785. if t["title"] == "Raw retry task"][0])
  1786. def raw_rows_for(task_id):
  1787. conn = db()
  1788. try:
  1789. return conn.execute(
  1790. "select count(*) from session_raw_log where session_id in"
  1791. " (select id from sessions where task_id = ?)", (task_id,)).fetchone()[0]
  1792. finally:
  1793. conn.close()
  1794. check(wait_for(lambda: raw_rows_for(raw_retry) > 0 or False,
  1795. timeout=60, what="raw log rows appear after retry") is not None,
  1796. "a failed seed probe retries and the raw log fills")
  1797. check(wait_task_done(auth, raw_retry, timeout=60) is not None,
  1798. "raw retry task completes")
  1799. print("== R6 F4: stranded assigned recovery ==")
  1800. # The live incident's shape: task assigned, session open, zero
  1801. # output ever, daemon idle. Grace period 10s in the harness env.
  1802. fake.state = "idle"
  1803. conn = db()
  1804. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  1805. " values (1, 'Stranded assigned', 'assigned', 2, strftime('%s','now'))")
  1806. stranded = conn.execute("select max(id) from tasks").fetchone()[0]
  1807. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  1808. " values (?, ?, strftime('%s','now','-180 seconds'))", (stranded, fake_id))
  1809. # Saddle row idle (the busy@task shape is the stale-busy heal's
  1810. # case); this exercises the strand pass specifically.
  1811. conn.execute("update saddles set status = 'idle', current_task_id = 0,"
  1812. " allocated_at = null where name = 'fake-saddle'")
  1813. conn.commit()
  1814. conn.close()
  1815. check(wait_for(lambda: any(c["body"] == "task stranded with no daemon output; task requeued"
  1816. for c in task_state(auth, stranded).get("comments", []))
  1817. or False, timeout=40, what="stranded requeue comment") is not None,
  1818. "stranded assignment requeues with a bot comment")
  1819. check(wait_task_done(auth, stranded, timeout=90) is not None,
  1820. "recovered task dispatches and completes")
  1821. print("== R7 B1: cancel reaches the daemon ==")
  1822. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1823. "project_id": "1",
  1824. "title": "Cancel live",
  1825. "priority": "2",
  1826. })
  1827. cancel_live = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1828. if t["title"] == "Cancel live"][0])
  1829. check(wait_for(lambda: task_state(auth, cancel_live).get("status") == "working"
  1830. or False, timeout=60, what="cancel-live working") is not None,
  1831. "task reaches working before the cancel")
  1832. act(auth, task_state(auth, cancel_live)["cancel"], {})
  1833. check(wait_for(lambda: cancel_live in fake.abort_log or False,
  1834. timeout=30, what="daemon abort recorded") is not None,
  1835. "cancelling POSTs /abort to the daemon")
  1836. check(any(c["body"] == "cancelled; daemon aborted"
  1837. for c in task_state(auth, cancel_live).get("comments", [])),
  1838. "the abort outcome is narrated")
  1839. check(task_state(auth, cancel_live)["status"] == "failed",
  1840. "cancelled task lands failed as before")
  1841. # Transport/500 failure on abort fences the saddle; recovery probe
  1842. # clears the fence; nothing dispatches while fenced.
  1843. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1844. "project_id": "1",
  1845. "title": "Fence runner",
  1846. "priority": "2",
  1847. })
  1848. fence_runner = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1849. if t["title"] == "Fence runner"][0])
  1850. check(wait_for(lambda: task_state(auth, fence_runner).get("status") == "working"
  1851. or False, timeout=60, what="fence runner working") is not None,
  1852. "second task reaches working")
  1853. fake.abort_failures = 1
  1854. act(auth, task_state(auth, fence_runner)["cancel"], {})
  1855. check(any(c["body"] == "cancelled; daemon unreachable — saddle fenced"
  1856. for c in task_state(auth, fence_runner).get("comments", [])),
  1857. "failed abort narrates the fence")
  1858. check(saddle_card("fake-saddle")["status"] == "recovering",
  1859. "saddle fenced as recovering")
  1860. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1861. "project_id": "1",
  1862. "title": "During fence",
  1863. "priority": "3",
  1864. })
  1865. during_fence = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1866. if t["title"] == "During fence"][0])
  1867. time.sleep(7)
  1868. check(task_state(auth, during_fence)["status"] == "queued",
  1869. "fenced saddle is not dispatchable")
  1870. # A real daemon lands idle once its (unaborted) round ends; the
  1871. # fake's scripted lifecycle parks on 'done', so model that.
  1872. fake.state = "idle"
  1873. check(wait_for(lambda: saddle_card("fake-saddle")["status"] == "idle" or False,
  1874. timeout=30, what="fence clears") is not None,
  1875. "an idle probe clears the fence")
  1876. check(wait_task_done(auth, during_fence, timeout=60) is not None,
  1877. "queued work dispatches once the fence clears")
  1878. print("== R7 B2: 409-aware dispatch ==")
  1879. # Zombie: the daemon (per the fake) still runs an old completed task;
  1880. # one 409, then abort + retry recovers without churning sessions.
  1881. fake.state = "idle"
  1882. fake.zombie_409 = 1
  1883. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1884. "project_id": "1",
  1885. "title": "Zombie recovery",
  1886. "priority": "2",
  1887. })
  1888. zombie_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1889. if t["title"] == "Zombie recovery"][0])
  1890. check(wait_task_done(auth, zombie_task, timeout=90) is not None,
  1891. "zombie conflict recovers and the task completes")
  1892. detail = task_state(auth, zombie_task)
  1893. check(any("recovered zombie session" in c["body"] for c in detail.get("comments", [])),
  1894. "the zombie recovery is narrated")
  1895. conn = db()
  1896. zombie_sessions = conn.execute(
  1897. "select count(*) from sessions where task_id = ?", (zombie_task,)).fetchone()[0]
  1898. conn.close()
  1899. check(zombie_sessions == 1,
  1900. "no session churn: one row across the failed and retried push (%d)"
  1901. % zombie_sessions)
  1902. # Live conflict: the daemon claims to run a task the web still sees
  1903. # live — fence + alert, never abort live work.
  1904. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1905. "project_id": "1",
  1906. "title": "Conflict live task",
  1907. "priority": "2",
  1908. })
  1909. conflict_live = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1910. if t["title"] == "Conflict live task"][0])
  1911. check(wait_for(lambda: task_state(auth, conflict_live).get("status") == "working"
  1912. or False, timeout=60, what="conflict task working") is not None,
  1913. "live task reaches working")
  1914. # Hold the daemon mid-working and desynchronise the web's view:
  1915. # double-booking means the web believes the saddle free while the
  1916. # daemon still claims the live task.
  1917. fake.hold_state = True
  1918. fake.conflict_running = conflict_live
  1919. conn = db()
  1920. conn.execute("update saddles set status = 'idle', current_task_id = 0,"
  1921. " allocated_at = null where name = 'fake-saddle'")
  1922. conn.commit()
  1923. conn.close()
  1924. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1925. "project_id": "1",
  1926. "title": "Conflict newcomer",
  1927. "priority": "3",
  1928. })
  1929. conflict_new = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1930. if t["title"] == "Conflict newcomer"][0])
  1931. check(wait_for(lambda: saddle_card("fake-saddle")["status"] == "recovering" or False,
  1932. timeout=30, what="double-booked saddle fenced") is not None,
  1933. "double-booked saddle is fenced")
  1934. check(any("double-booked" in c["body"]
  1935. for c in task_state(auth, conflict_live).get("comments", [])),
  1936. "the live task gets the alert comment")
  1937. check(any("dispatch refused" in c["body"]
  1938. for c in task_state(auth, conflict_new).get("comments", [])),
  1939. "the refused task gets its comment")
  1940. conn = db()
  1941. new_sessions = conn.execute(
  1942. "select outcome from sessions where task_id = ?", (conflict_new,)).fetchall()
  1943. conn.close()
  1944. check(len(new_sessions) == 1 and new_sessions[0][0] == "push_failed",
  1945. "failed push marks the session push_failed (no churn)")
  1946. check(conflict_live not in fake.abort_log,
  1947. "the live task is never aborted")
  1948. fake.conflict_running = 0
  1949. fake.hold_state = False
  1950. fake.state = "idle"
  1951. act(auth, task_state(auth, conflict_live)["complete"],
  1952. {"summary": "finished before the conflict"})
  1953. check(wait_for(lambda: task_state(auth, conflict_live).get("status") == "done"
  1954. or False, timeout=30, what="live task completed") is not None,
  1955. "the live task completes without an abort")
  1956. check(wait_for(lambda: saddle_card("fake-saddle")["status"] == "idle" or False,
  1957. timeout=40, what="fence clears after conflict") is not None,
  1958. "fence clears once the daemon goes idle")
  1959. conn = db()
  1960. after_clear = conn.execute(
  1961. "select count(*) from sessions where task_id = ?", (conflict_new,)).fetchone()[0]
  1962. conn.close()
  1963. check(after_clear == 1, "still one session row for the refused task")
  1964. check(wait_task_done(auth, conflict_new, timeout=90) is not None,
  1965. "the refused task dispatches after the fence clears")
  1966. print("== R7 B3: wedged daemon, health panel, raw log, vanishing daemon ==")
  1967. # Raw-log polling starts from the FIRST push (no probe failure):
  1968. # a normally dispatched task accumulates raw rows immediately.
  1969. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1970. "project_id": "1",
  1971. "title": "Raw from first push",
  1972. "priority": "2",
  1973. })
  1974. raw_first = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1975. if t["title"] == "Raw from first push"][0])
  1976. def raw_count(task_id):
  1977. conn = db()
  1978. try:
  1979. return conn.execute(
  1980. "select count(*) from session_raw_log where session_id in"
  1981. " (select id from sessions where task_id = ?)", (task_id,)).fetchone()[0]
  1982. finally:
  1983. conn.close()
  1984. check(wait_for(lambda: raw_count(raw_first) > 0 or False,
  1985. timeout=60, what="raw rows from first push") is not None,
  1986. "raw-log polling runs from the first push (session-4 gap)")
  1987. check(wait_task_done(auth, raw_first, timeout=60) is not None,
  1988. "raw-first task completes")
  1989. # Health panel: after the polls above the snapshot knows the fake.
  1990. card = saddle_card("fake-saddle")
  1991. check(card.get("health") in ("healthy", "stale")
  1992. and card.get("daemon_state") in ("working", "idle", "done")
  1993. and card.get("uptime_display", "") != ""
  1994. and card.get("last_contact_display", "") not in ("", "never"),
  1995. "saddles page shows daemon state, uptime and last contact")
  1996. # Alive-but-wedged: a working daemon whose last activity is stale
  1997. # (threshold 3s in the harness) fences the saddle and requeues the
  1998. # task with a bot comment.
  1999. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2000. "project_id": "1",
  2001. "title": "Wedge victim",
  2002. "priority": "2",
  2003. })
  2004. wedge = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2005. if t["title"] == "Wedge victim"][0])
  2006. check(wait_for(lambda: task_state(auth, wedge).get("status") == "working"
  2007. or False, timeout=60, what="wedge victim working") is not None,
  2008. "wedge victim reaches working")
  2009. fake.hold_state = True
  2010. fake.freeze_activity = True
  2011. check(wait_for(lambda: any("saddle wedged" in c["body"]
  2012. for c in task_state(auth, wedge).get("comments", []))
  2013. or False, timeout=40, what="wedge comment") is not None,
  2014. "stale activity wedges the saddle with a bot comment")
  2015. check(saddle_card("fake-saddle")["status"] == "recovering",
  2016. "wedged saddle is fenced")
  2017. card = saddle_card("fake-saddle")
  2018. check(card.get("health") == "fenced",
  2019. "health badge reports fenced")
  2020. fake.hold_state = False
  2021. fake.freeze_activity = False
  2022. # The fake's scripted lifecycle parks on 'done' when released
  2023. # mid-working; a real daemon lands idle after its round.
  2024. fake.state = "idle"
  2025. check(wait_for(lambda: saddle_card("fake-saddle")["health"] in ("healthy", "stale")
  2026. or False, timeout=40, what="health recovers") is not None,
  2027. "health badge recovers with the fence")
  2028. check(wait_task_done(auth, wedge, timeout=90) is not None,
  2029. "wedged task requeues and completes after recovery")
  2030. print("== R8: raw-log ingestion is lossless ==")
  2031. # Dynamic scripted ring: empty at seed (the pre-push probe
  2032. # baselines at next=1), then the daemon "produces" the corpus on
  2033. # /start — seq 1 coloured prompt run, 2 plain, 3 a bare CRLF
  2034. # between prompts, 4..6 following. Every non-empty served chunk
  2035. # must land, exactly once.
  2036. corpus = [
  2037. {"seq": 1, "text": "\x1b[01;32muser@host\x1b[00m:\x1b[01;34m~/task-1\x1b[00m$ "},
  2038. {"seq": 2, "text": "echo hello\r\n"},
  2039. {"seq": 3, "text": "\r\n"},
  2040. {"seq": 4, "text": "hello\r\n"},
  2041. {"seq": 5, "text": "\x1b[01;32muser@host\x1b[00m:\x1b[01;34m~/task-1\x1b[00m$ "},
  2042. {"seq": 6, "text": "done\r\n"},
  2043. ]
  2044. fake.scripted_corpus = corpus
  2045. fake.scripted_log = []
  2046. fake.scripted_next = 1
  2047. fake.state = "working"
  2048. fake.hold_state = True
  2049. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2050. "project_id": "1",
  2051. "title": "Lossless log task",
  2052. "priority": "2",
  2053. })
  2054. lossless = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2055. if t["title"] == "Lossless log task"][0])
  2056. def stored_seqs(task_id):
  2057. conn = db()
  2058. try:
  2059. return [r[0] for r in conn.execute(
  2060. "select seq from session_raw_log where session_id in"
  2061. " (select id from sessions where task_id = ?)"
  2062. " order by seq", (task_id,))]
  2063. finally:
  2064. conn.close()
  2065. check(wait_for(lambda: task_state(auth, lossless).get("status") == "working"
  2066. or False, timeout=60, what="lossless task working") is not None,
  2067. "lossless task dispatches with a pre-push probe on an empty ring")
  2068. check(wait_for(lambda: stored_seqs(lossless) == [1, 2, 3, 4, 5, 6] or False,
  2069. timeout=30, what="all six chunks stored") is not None,
  2070. "every served chunk lands in session_raw_log, CRLF-only included (%s)"
  2071. % stored_seqs(lossless))
  2072. time.sleep(7)
  2073. check(stored_seqs(lossless) == [1, 2, 3, 4, 5, 6],
  2074. "no duplicates or losses on later polls")
  2075. request = urllib.request.Request(
  2076. WEB + "/terminal-stream/%d" % [r[0] for r in db().execute(
  2077. "select id from sessions where task_id = ?", (lossless,))][0])
  2078. with urllib.request.urlopen(request, timeout=15) as stream:
  2079. texts = []
  2080. deadline = time.monotonic() + 8
  2081. while time.monotonic() < deadline and len(texts) < 6:
  2082. line = stream.readline().decode().strip()
  2083. if not line.startswith("data: ") or line == "data: ping":
  2084. continue
  2085. event = json.loads(line[6:])
  2086. if event.get("type") == "raw":
  2087. texts.append(event.get("text") or "")
  2088. check("\r\n" in texts and len(texts) == 6,
  2089. "SSE serves the whitespace chunk unfiltered")
  2090. fake.hold_state = False
  2091. fake.state = "idle"
  2092. fake.scripted_log = None
  2093. fake.scripted_corpus = None
  2094. check(wait_task_done(auth, lossless, timeout=60) is not None,
  2095. "lossless task completes")
  2096. print("== R9 B1/B2: git identity + ssh key ==")
  2097. # The key travels on /status into the saddle row and the page view.
  2098. fake.ssh_public_key = "ssh-ed25519 AAAAC3NzaC1lZDI1teStKey saddle-1@fedora"
  2099. fake.state = "idle"
  2100. fake_card = saddle_card("fake-saddle")
  2101. check(fake_card.get("ssh_public_key", "") == "",
  2102. "no key shown before the daemon reports one")
  2103. act(auth, fake_card["refresh"], {})
  2104. check(wait_for(lambda: "AAAAC3NzaC1lZDI1teStKey" in
  2105. saddle_card("fake-saddle").get("ssh_public_key", "") or False,
  2106. timeout=30, what="key lands on the row") is not None,
  2107. "reported ssh_public_key persists onto the saddle row")
  2108. conn = db()
  2109. row_key = conn.execute("select ssh_public_key from saddles where name = 'fake-saddle'"
  2110. ).fetchone()[0]
  2111. conn.close()
  2112. check(row_key == fake.ssh_public_key,
  2113. "the key is stored verbatim in the database")
  2114. # Identity edit flows through the UI into the /start payload.
  2115. fake_card = saddle_card("fake-saddle")
  2116. act(auth, fake_card["update_identity"],
  2117. {"git_name": "clanker-bot", "git_email": "bot@unitatem.net"})
  2118. fake_card = saddle_card("fake-saddle")
  2119. check(fake_card.get("git_name") == "clanker-bot"
  2120. and fake_card.get("git_email") == "bot@unitatem.net",
  2121. "inline edit saves the git identity")
  2122. pushes_before = len(fake.start_payloads)
  2123. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2124. "project_id": "1",
  2125. "title": "Identity task",
  2126. "priority": "2",
  2127. })
  2128. identity_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2129. if t["title"] == "Identity task"][0])
  2130. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == identity_task
  2131. for p in fake.start_payloads) or False,
  2132. timeout=60, what="identity task pushed") is not None,
  2133. "identity task dispatches")
  2134. payload = [p for p in fake.start_payloads
  2135. if int(p.get("task", {}).get("id") or 0) == identity_task][-1]
  2136. identity = payload.get("git_identity") or {}
  2137. check(identity.get("name") == "clanker-bot"
  2138. and identity.get("email") == "bot@unitatem.net",
  2139. "/start carries the saddle's git_identity")
  2140. # Earlier pushes (identity unset) carry no git_identity member.
  2141. check(all("git_identity" not in p for p in fake.start_payloads[:-1]),
  2142. "unset identity omits the member (daemon fallback applies)")
  2143. # Clearing the identity omits it from later pushes.
  2144. fake_card = saddle_card("fake-saddle")
  2145. act(auth, fake_card["update_identity"], {"git_name": "", "git_email": ""})
  2146. check(saddle_card("fake-saddle").get("git_name", "") == "",
  2147. "clearing the identity empties the row")
  2148. check(wait_task_done(auth, identity_task, timeout=60) is not None,
  2149. "identity task completes")
  2150. print("== R10: branch_advanced + gap forensics ==")
  2151. # --- branch_advanced on the /poll verdict channel ---
  2152. fake.state = "working"
  2153. fake.hold_state = True
  2154. conn = db()
  2155. conn.execute("insert into tasks (project_id, title, status, priority,"
  2156. " created_at) values (1, 'Poll grandparent', 'working', 5,"
  2157. " strftime('%s','now','-300 seconds'))")
  2158. poll_grand = conn.execute("select max(id) from tasks").fetchone()[0]
  2159. conn.execute("insert into tasks (project_id, title, status, priority,"
  2160. " parent_task_id, created_at) values (1, 'Poll answer parent',"
  2161. " 'blocked', 5, ?, strftime('%s','now','-120 seconds'))",
  2162. (poll_grand,))
  2163. poll_parent = conn.execute("select max(id) from tasks").fetchone()[0]
  2164. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  2165. " values (?, ?, strftime('%s','now','-120 seconds'))",
  2166. (poll_parent, fake_id))
  2167. poll_session = conn.execute("select max(id) from sessions").fetchone()[0]
  2168. conn.execute("insert into task_blocks (task_id, question, type, answer,"
  2169. " answered_at, created_at) values (?, 'Which DB?', 'question',"
  2170. " 'SQLite', strftime('%s','now','-60 seconds'),"
  2171. " strftime('%s','now','-100 seconds'))", (poll_parent,))
  2172. conn.execute("update saddles set status = 'busy', current_task_id = ?,"
  2173. " allocated_at = strftime('%s','now') where name = 'fake-saddle'",
  2174. (poll_parent,))
  2175. conn.commit()
  2176. conn.close()
  2177. status, body = saddle_api("GET", "/api/saddle/%d/poll" % fake_id, fake_token)
  2178. check(status == 200 and len(body.get("answers", [])) == 1
  2179. and body["answers"][0].get("branch_advanced") is False,
  2180. "/poll verdicts carry branch_advanced=false with no siblings")
  2181. # A sibling under the same parent completed after the park marker.
  2182. conn = db()
  2183. conn.execute("insert into tasks (project_id, title, status, priority,"
  2184. " parent_task_id, summary, completed_at, created_at)"
  2185. " values (1, 'Poll sibling', 'done', 5, ?, 'sibling finished',"
  2186. " strftime('%s','now'), strftime('%s','now','-200 seconds'))",
  2187. (poll_grand,))
  2188. conn.execute("insert into task_blocks (task_id, question, type, answer,"
  2189. " answered_at, created_at) values (?, 'Second question?',"
  2190. " 'question', 'Yes', strftime('%s','now'),"
  2191. " strftime('%s','now','-90 seconds'))", (poll_parent,))
  2192. conn.commit()
  2193. conn.close()
  2194. status, body = saddle_api("GET", "/api/saddle/%d/poll" % fake_id, fake_token)
  2195. check(status == 200 and len(body.get("answers", [])) == 1
  2196. and body["answers"][0].get("branch_advanced") is True,
  2197. "sibling completion after park flips branch_advanced to true")
  2198. # Release the staged task: cancel it so the held-working poll loop
  2199. # does not carry it into the race subsection.
  2200. act(auth, task_state(auth, poll_parent)["cancel"], {})
  2201. fake.hold_state = False
  2202. fake.state = "idle"
  2203. # --- the /log snapshot race loses nothing ---
  2204. fake.state = "working"
  2205. fake.hold_state = True
  2206. fake.scripted_corpus = [
  2207. {"seq": 1, "text": "prompt-one\r\n"},
  2208. {"seq": 2, "text": "echo a\r\n"},
  2209. {"seq": 3, "text": "a\r\n"},
  2210. {"seq": 4, "text": "prompt-two\r\n"},
  2211. ]
  2212. fake.scripted_log = []
  2213. fake.scripted_next = 1
  2214. fake.race_texts = ["raced-five\r\n", "raced-six\r\n"]
  2215. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2216. "project_id": "1",
  2217. "title": "Race forensics task",
  2218. "priority": "2",
  2219. })
  2220. race_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2221. if t["title"] == "Race forensics task"][0])
  2222. def race_seqs():
  2223. conn = db()
  2224. try:
  2225. return [r[0] for r in conn.execute(
  2226. "select seq from session_raw_log where session_id in"
  2227. " (select id from sessions where task_id = ?)"
  2228. " order by seq", (race_task,))]
  2229. finally:
  2230. conn.close()
  2231. check(wait_for(lambda: race_seqs() == [1, 2, 3, 4, 5, 6] or False,
  2232. timeout=40, what="race chunks all stored") is not None,
  2233. "the snapshot race loses nothing: complete 1..6, no gaps (%s)"
  2234. % race_seqs())
  2235. time.sleep(7)
  2236. check(race_seqs() == [1, 2, 3, 4, 5, 6],
  2237. "race chunks stored exactly once")
  2238. fake.hold_state = False
  2239. fake.state = "idle"
  2240. fake.scripted_log = None
  2241. fake.scripted_corpus = None
  2242. check(wait_task_done(auth, race_task, timeout=60) is not None,
  2243. "race forensics task completes")
  2244. print("== R11: live blocks arrive without a reload ==")
  2245. # The browser flow on each pulse: statum.act(task.refresh) — the
  2246. # sealed GET action must rehydrate the task slot with the new
  2247. # block. (The channel chain itself — entrypoint subscribe on
  2248. # load, SSE set events on bump — was verified end-to-end against
  2249. # a real channel client during the investigation.)
  2250. fake.state = "working"
  2251. fake.hold_state = True
  2252. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2253. "project_id": "1",
  2254. "title": "Live block task",
  2255. "priority": "2",
  2256. })
  2257. live_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2258. if t["title"] == "Live block task"][0])
  2259. check(wait_for(lambda: task_state(auth, live_task).get("status") == "working"
  2260. or False, timeout=60, what="live task working") is not None,
  2261. "live-block task reaches working")
  2262. conn = db()
  2263. live_session = conn.execute(
  2264. "select id from sessions where task_id = ?", (live_task,)).fetchone()[0]
  2265. conn.close()
  2266. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  2267. {"type": "block", "session_id": live_session, "data": {
  2268. "question": "Pick one", "type": "question",
  2269. "options": ["A", "B"]}})
  2270. check(status == 200, "block raised via the daemon")
  2271. check(wait_for(lambda: any(b.get("question") == "Pick one"
  2272. for b in task_state(auth, live_task).get("blocks", []))
  2273. or False, timeout=30, what="block lands in state") is not None,
  2274. "the raised block reaches the task state")
  2275. detail = task_state(auth, live_task)
  2276. check(detail.get("refresh") is not None,
  2277. "the sealed GET refresh action is still authored")
  2278. status, _ = http("GET", detail["refresh"]["uri"], timeout=15)
  2279. check(status in (200, 401),
  2280. "the refresh URI resolves as a GET (client roundtrip shape)")
  2281. act(auth, detail["answer_action"] if "answer_action" in detail
  2282. else detail["blocks"][0]["answer_action"], {"answer": "A"})
  2283. fake.hold_state = False
  2284. fake.state = "idle"
  2285. check(wait_task_done(auth, live_task, timeout=60) is not None,
  2286. "live-block task completes after answering")
  2287. # The daemon vanishing mid-task: three refused polls → offline,
  2288. # task requeued with a bot comment, UI reflects.
  2289. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2290. "project_id": "1",
  2291. "title": "Vanish victim",
  2292. "priority": "2",
  2293. })
  2294. vanish = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2295. if t["title"] == "Vanish victim"][0])
  2296. check(wait_for(lambda: task_state(auth, vanish).get("status") == "working"
  2297. or False, timeout=60, what="vanish victim working") is not None,
  2298. "vanish victim reaches working")
  2299. fake.kill()
  2300. check(wait_for(lambda: saddle_card("fake-saddle")["status"] == "offline" or False,
  2301. timeout=60, what="daemon death → offline") is not None,
  2302. "vanishing daemon drives the saddle offline")
  2303. check(wait_for(lambda: any("unreachable" in c["body"]
  2304. for c in task_state(auth, vanish).get("comments", []))
  2305. or False, timeout=30, what="unreachable comment") is not None,
  2306. "the affected task gets an unreachable bot comment")
  2307. check(task_state(auth, vanish)["status"] == "queued",
  2308. "the task requeues after the daemon death")
  2309. card = saddle_card("fake-saddle")
  2310. check(card.get("health") == "offline",
  2311. "health badge reports offline")
  2312. # The unreachable row flag marks the detection window: a task the
  2313. # web still sees working while its saddle is offline/fenced, before
  2314. # the requeue pass moves it. Controlled window (the real
  2315. # transitions above are atomic with their requeues).
  2316. conn = db()
  2317. conn.execute("insert into tasks (project_id, title, status, priority,"
  2318. " created_at) values (1, 'Unreachable row', 'working', 5,"
  2319. " strftime('%s','now'))")
  2320. unreachable_row = conn.execute("select max(id) from tasks").fetchone()[0]
  2321. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  2322. " values (?, ?, strftime('%s','now'))", (unreachable_row, fake_id))
  2323. conn.commit()
  2324. conn.close()
  2325. row = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2326. if int(t["id"]) == unreachable_row][0]
  2327. check(row.get("unreachable") is True,
  2328. "queue row shows the unreachable state in the window")
  2329. finally:
  2330. # Exit-code diagnostic: distinguishes a crashed app (negative
  2331. # returncode, e.g. -11 SIGSEGV) from a clean shutdown. When
  2332. # tearing down mid-exception, also capture the still-alive
  2333. # app's stacks before killing it (a wedged-but-alive server
  2334. # otherwise leaves no evidence).
  2335. print("(app returncode at teardown: %s)" % app.poll())
  2336. if app.poll() is None and sys.exc_info()[0] is not None:
  2337. dump_app_stacks(app.pid)
  2338. app.terminate()
  2339. try:
  2340. app.wait(timeout=5)
  2341. except subprocess.TimeoutExpired:
  2342. app.kill()
  2343. print("%d passed, %d failed" % (passes, failures))
  2344. return 1 if failures else 0
  2345. if __name__ == "__main__":
  2346. sys.exit(main())