web_stack_test.py 171 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238
  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. - in-process fake saddle daemons speaking the wire contract: POST
  9. /register (plan 10: receives {saddle_token, web_base_url}, answers
  10. {ok, ssh_public_key, version}), POST /wake (records the wake; the
  11. daemon then asks POST /api/saddle/next-task), POST /task-update
  12. (cancel/comment/subtask-status), GET /status (scripted reflection —
  13. exceptional use only), and the phase-2 push channels home:
  14. POST /api/saddle/chunks (raw PTY batches) and POST /api/saddle/results
  15. (round entries + state transitions). The retired /start, /output and
  16. /log routes 404 like a post-phase-2 daemon.
  17. It then drives the app the way statum.js does (entrypoint loads + action
  18. POSTs) and asserts the Workstream B features against the wire contract:
  19. 3. plan-review blocks hide their duplicate body preview
  20. 5. rules CRUD/attach + the effective `rules` array in assignments
  21. 6. project notes, POST /api/saddle/note, `project_notes` + `callback`
  22. in assignments
  23. plus the raw-log side: pushed chunks -> session_raw_log + terminal
  24. raw view
  25. Plan 10 phase 1 (work acquisition flip):
  26. - per-saddle tokens: registration mints + /register-delivers them,
  27. legacy tokens migrate onto the row at startup, removal revokes
  28. - token auth on every /api/saddle/* endpoint
  29. - next-task allocation: concurrent asks race exactly one winner,
  30. affinity pinning for parked tasks, resume_notice on suspended resumes
  31. - dispatcher: wake -> ask -> allocate roundtrip, the lost-wake guard
  32. (no ask after a wake -> offline, re-wake the next capable), and the
  33. pre-flip /answer + /start resume paths kept as the rollback route
  34. Plan 10 phase 2 (telemetry flip):
  35. - pushed chunks: idempotent on (session_id, seq), ordered, landing in
  36. session_raw_log so the SSE terminal keeps working
  37. - pushed results: entries store like the /output path did (redelivery
  38. idempotent on the daemon entry ids), blocked raises the block row +
  39. parks + bumps the pulse (sealed refresh shows it), done/failed
  40. complete/fail the task, suspended parks for the affinity resume
  41. - staleness: a silent runner gets ONE exceptional GET /status probe —
  42. alive keeps it running, dead requeues the task with a bot comment and
  43. marks the saddle offline; a recovered daemon's ask flips offline rows
  44. back to idle
  45. - the deleted layers are gone: /output, /log and /start 404 on the
  46. daemon side, and nothing on the web side calls them
  47. Plan 10 phase 3 (capability awareness + UI):
  48. - assignment capability context: {saddle_tags, fleet_tags} on every
  49. payload, GET /api/saddle/capabilities (per-saddle token) feeding
  50. the daemon's `saddle capabilities` CLI
  51. - subtask callback capabilities: explicit-only attachment validated
  52. against the operator tag set, unknown tags rejected with the valid
  53. list in the error
  54. - task page: status block pinned to the top, blocking sections
  55. newest-first (sealed GET state)
  56. - home dashboard: pinned OPEN blocks as newest-first link-through
  57. cards (no inline answer forms) above the cross-task activity
  58. timeline (last ~50 events newest-first)
  59. - lost-wake-guard regression: a saddle that asks SLOWLY after its
  60. wake (busy winding down) still claims the task — the wake is never
  61. silently dropped, no re-wake storm fires, and the never-asks guard
  62. path (offline + re-wake of the next capable) stays green
  63. Prints PASS/FAIL lines Statum-style; exits non-zero on any failure.
  64. """
  65. import json
  66. import os
  67. import shutil
  68. import socket
  69. import sqlite3
  70. import subprocess
  71. import sys
  72. import threading
  73. import time
  74. import urllib.error
  75. import urllib.parse
  76. import urllib.request
  77. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  78. REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  79. APP = os.path.abspath(sys.argv[1]) if len(sys.argv) > 1 else os.path.join(REPO, "builddir", "clanker-saddle")
  80. WORK = os.environ.get("WEBSTACK_WORK", "/tmp/kilo/webstack-e2e")
  81. DB_PATH = os.path.join(WORK, "web.sqlite")
  82. passes = 0
  83. failures = 0
  84. def check(condition, label):
  85. global passes, failures
  86. if condition:
  87. passes += 1
  88. print("PASS %s" % label)
  89. else:
  90. failures += 1
  91. print("FAIL %s" % label)
  92. def free_port():
  93. with socket.socket() as sock:
  94. sock.bind(("127.0.0.1", 0))
  95. return sock.getsockname()[1]
  96. APP_PORT = free_port()
  97. DAEMON_PORT = free_port()
  98. WEB = "http://127.0.0.1:%d" % APP_PORT
  99. def http(method, url, data=None, headers=None, timeout=30):
  100. body = None
  101. if data is not None:
  102. pairs = []
  103. for k, v in data.items():
  104. for item in (v if isinstance(v, (list, tuple)) else [v]):
  105. pairs.append((k, item))
  106. body = "&".join("%s=%s" % (k, urllib.parse.quote(str(item))) for k, item in pairs).encode()
  107. request = urllib.request.Request(WEB + url if url.startswith("/") else url,
  108. data=body, method=method)
  109. if data is not None:
  110. request.add_header("Content-Type", "application/x-www-form-urlencoded")
  111. for key, value in (headers or {}).items():
  112. request.add_header(key, value)
  113. # Retry dropped/refused connections: the freshly started app can
  114. # close a very early keep-alive connection once while warming up,
  115. # and its first seconds can wobble under load.
  116. for attempt in range(3):
  117. try:
  118. with urllib.request.urlopen(request, timeout=timeout) as response:
  119. return response.status, response.read().decode()
  120. except urllib.error.HTTPError as error:
  121. return error.code, error.read().decode()
  122. except (urllib.error.URLError, OSError):
  123. if attempt >= 2:
  124. raise
  125. time.sleep(0.75)
  126. def directives(uri, auth=None):
  127. headers = {}
  128. if auth:
  129. headers["X-Statum-Slot"] = "key=%s; as_at=%s" % (auth["key"], auth["as_at"])
  130. status, body = http("GET", "/_statum/entrypoint?uri=" + urllib.parse.quote(uri.split("?")[0]),
  131. headers=headers)
  132. if status != 200:
  133. raise SystemExit("entrypoint %s -> HTTP %d: %s" % (uri, status, body[:300]))
  134. return json.loads(body)
  135. def slot_public(auth, uri, type_name):
  136. for directive in directives(uri, auth):
  137. if directive["type"] == "set":
  138. content = directive["snapshot_frame"].get("content")
  139. if not content:
  140. continue
  141. content = json.loads(content)
  142. if content["slot"]["type"] == type_name:
  143. return content["public"]
  144. raise SystemExit("no %s slot in entrypoint state for %s" % (type_name, uri))
  145. def act(auth, action, fields):
  146. headers = {"X-Statum-Slot": "key=%s; as_at=%s" % (auth["key"], auth["as_at"])}
  147. if action.get("private"):
  148. headers["X-Statum-Private"] = action["private"]
  149. status, body = http(action.get("method", "POST"), action["uri"], fields, headers)
  150. if status != 200:
  151. raise SystemExit("action %s -> HTTP %d: %s" % (action["uri"], status, body[:300]))
  152. return json.loads(body)
  153. def login(username, password):
  154. frames = directives("/login")
  155. content = json.loads(frames[0]["snapshot_frame"]["content"])
  156. action = content["public"]["login"]
  157. status, body = http(action.get("method", "POST"), action["uri"],
  158. {"username": username, "password": password})
  159. if status != 200:
  160. raise SystemExit("login -> HTTP %d: %s" % (status, body[:300]))
  161. for directive in json.loads(body):
  162. if directive["type"] == "set":
  163. frame = json.loads(directive["snapshot_frame"]["content"])
  164. if frame["slot"]["type"] == "auth":
  165. return {"key": frame["slot"]["key"], "as_at": frame["as_at"]}
  166. raise SystemExit("login response carried no auth slot: " + body[:300])
  167. def wait_for(predicate, timeout=60, what="condition", interval=0.5):
  168. deadline = time.monotonic() + timeout
  169. last = None
  170. while time.monotonic() < deadline:
  171. last = predicate()
  172. if last is not False and last is not None:
  173. return last
  174. time.sleep(interval)
  175. print(" (timeout waiting for %s; last: %s)" % (what, last))
  176. dump_threads()
  177. return None
  178. def dump_threads():
  179. """Stacks of suite threads not parked in sleep — pinpoints a wedged
  180. fake lifecycle when a wait times out."""
  181. import traceback
  182. shown = 0
  183. for thread_id, frame in sys._current_frames().items():
  184. stack = "".join(traceback.format_stack(frame)[-4:])
  185. if ("web_stack_test.py" in stack) and ("sleep" not in stack) and shown < 6:
  186. shown += 1
  187. print(" --- thread %s ---\n%s" % (thread_id, stack))
  188. def task_state(auth, task_id):
  189. return slot_public(auth, "/tasks/%d" % task_id, "task")
  190. def wait_task_done(auth, task_id, timeout=90):
  191. return wait_for(lambda: task_state(auth, task_id).get("status") == "done" or False,
  192. timeout=timeout, what="task %d -> done" % task_id)
  193. def task_id_of(title):
  194. conn = db()
  195. try:
  196. return conn.execute("select id from tasks where title = ?", (title,)).fetchone()[0]
  197. finally:
  198. conn.close()
  199. def saddle_api(method, path, token, payload=None):
  200. """Raw call against the saddle ingest API; returns (status, json)."""
  201. request = urllib.request.Request(WEB + path,
  202. data=json.dumps(payload or {}).encode(), method=method)
  203. request.add_header("Content-Type", "application/json")
  204. if token is not None:
  205. request.add_header("Authorization", "Bearer " + token)
  206. try:
  207. with urllib.request.urlopen(request, timeout=15) as response:
  208. return response.status, json.loads(response.read().decode() or "{}")
  209. except urllib.error.HTTPError as error:
  210. body = error.read().decode()
  211. try:
  212. return error.code, json.loads(body)
  213. except ValueError:
  214. return error.code, {"raw": body}
  215. def db():
  216. return sqlite3.connect(DB_PATH)
  217. class FakeSaddle:
  218. """In-process saddle daemon implementing the wire contract.
  219. Phase-2 push behaviour: the daemon asks POST /api/saddle/next-task
  220. whenever idle-awake (at registration, on POST /wake, after its task
  221. reaches a terminal state, and when a /status probe observes it
  222. parked idle — throttled), accepts assignments like POST /start used
  223. to, then PUSHES its telemetry home: raw PTY chunks via POST
  224. /api/saddle/chunks and round results with state transitions via
  225. POST /api/saddle/results (working at round start, terminal states
  226. when the scripted lifecycle ends them). /output, /log and /start are
  227. gone (404) like a post-phase-2 daemon; /task-update serves the
  228. cancel/comment/subtask-status kinds. Every trigger can be disabled
  229. per test for determinism; ask_now() performs a synchronous manual
  230. ask.
  231. """
  232. PROMPT = "bbarrow@fedora:/workspace/task-1$ "
  233. def __init__(self):
  234. self.lock = threading.Lock()
  235. self.start_payloads = [] # captured assignment payloads (/start + next-task 200s)
  236. self.state = "idle"
  237. self.summary = ""
  238. self.state_entered = time.monotonic()
  239. self.fail_next = False # next task drives the task to failed
  240. self.start_counts = {} # task id -> assignment count
  241. self.resumed_pending = False # crash-resume flag on the next /status
  242. self.suspend_on_title = None # this task (by title) parks as suspended
  243. self.output_seq = 100 # daemon-global entry ids for pushed results
  244. self.last_activity_epoch = int(time.time())
  245. self.subtask_status_events = [] # recorded /task-update subtask-status payloads
  246. self.fail_subtask_status = False # exercise the web's retry path
  247. self.hang_next = {} # path suffix -> hang count (never responds)
  248. self.abort_failures = 0 # cancel task-updates failing (500) while > 0
  249. self.abort_log = [] # task ids aborted via task-update cancel
  250. self.running_task = 0 # task id the daemon believes it runs
  251. self.running_title = "" # its title (suspend targeting)
  252. self.session_id = None # the web-side run row of the running task
  253. self.hold_state = False # freeze lifecycle + heartbeat pushes
  254. self.ssh_public_key = "" # reported on /status + /register
  255. self.started_mono = time.monotonic()
  256. self.freeze_activity = False # hold last_activity_epoch still
  257. self.silent = False # suppress pushes (staleness tests)
  258. self.dead = False # kill(): no serving AND no calls home
  259. self.status_hits = 0 # GET /status arrivals (probe accounting)
  260. self.comment_log = [] # recorded /task-update comment payloads
  261. self.scripted_corpus = None # chunk batch pushed when a task starts
  262. # --- plan 10 phase 1: ask/wake/register ---
  263. self.token = None # per-saddle token from POST /register
  264. self.register_log = [] # recorded /register bodies
  265. self.wake_log = [] # recorded POST /wake arrivals
  266. self.asks = [] # [{"status": int, "payload": dict|None}]
  267. self.ask_on_register = True
  268. self.ask_on_wake = True
  269. self.ask_on_terminal = True
  270. self.ask_on_idle_status = True
  271. self.ask_delay = 0.0 # seconds; a slow daemon delays its wake-triggered ask
  272. self.serve_register = True # False: 404 /register (pre-flip daemon)
  273. self.last_ask_trigger = 0.0
  274. self.port = None
  275. def set_state(self, state, summary=None):
  276. """Advances the scripted lifecycle."""
  277. self.state = state
  278. if summary is not None:
  279. self.summary = summary
  280. self.state_entered = time.monotonic()
  281. def touch_activity(self):
  282. if not self.freeze_activity:
  283. self.last_activity_epoch = int(time.time())
  284. def queue_output(self, entry_type, command, output):
  285. """Pushes a typed entry as a round-results push (the daemon's
  286. entry log riding the results channel)."""
  287. with self.lock:
  288. entry = {
  289. "id": self.output_seq,
  290. "command": command,
  291. "output": output,
  292. "exit_code": 1,
  293. "type": entry_type,
  294. "timestamp": "2026-09-06T00:00:00Z",
  295. }
  296. self.output_seq += 1
  297. self.push_results(self.state if self.state in ("working",) else "working",
  298. entries=[entry])
  299. # --- plan 10 phase 2: the push channels ---
  300. def push_chunks(self, chunks):
  301. """Pushes raw PTY chunks home: elements are texts (assigned
  302. fresh seqs) or {seq, text} dicts (a redelivery or explicit
  303. corpus). Pushes are suppressed while silent/hold_state (the
  304. staleness tests' silent runner)."""
  305. if self.dead or self.silent or self.token is None or self.session_id is None:
  306. return
  307. batch = []
  308. with self.lock:
  309. for chunk in chunks:
  310. if isinstance(chunk, dict):
  311. batch.append({"seq": int(chunk["seq"]), "text": chunk["text"]})
  312. else:
  313. batch.append({"seq": self.next_push_seq(), "text": chunk})
  314. try:
  315. saddle_api("POST", "/api/saddle/chunks", self.token,
  316. {"session_id": self.session_id, "chunks": batch})
  317. except (OSError, ValueError):
  318. pass # app restarting / shutting down mid-test
  319. def next_push_seq(self):
  320. # The daemon-side chunk counter for ad-hoc pushes.
  321. self._push_seq = getattr(self, "_push_seq", 0) + 1
  322. return self._push_seq
  323. def push_results(self, state, entries=None, block=None, summary=None, session_id=None):
  324. """Pushes one round-results payload home (state transition plus
  325. its entries). Returns the HTTP status when it went out, None
  326. when suppressed."""
  327. if self.dead or self.silent:
  328. return None
  329. if self.token is None:
  330. return None
  331. target = session_id if session_id is not None else self.session_id
  332. if target is None:
  333. return None
  334. payload = {"session_id": target, "state": state}
  335. if entries is not None:
  336. payload["entries"] = entries
  337. if block is not None:
  338. payload["block"] = block
  339. if summary is not None:
  340. payload["summary"] = summary
  341. try:
  342. status, _ = saddle_api("POST", "/api/saddle/results", self.token, payload)
  343. if status != 200:
  344. print(" [fake %s] push %s -> HTTP %s (task=%s)"
  345. % (self.port, state, status, self.running_task))
  346. return status
  347. except (OSError, ValueError) as error:
  348. print(" [fake %s] push %s failed: %r (task=%s)"
  349. % (self.port, state, error, self.running_task))
  350. return None
  351. # --- plan 10 phase 1: the ask path ---
  352. def ask_now(self):
  353. """Synchronously asks the web for work (a phase-1 daemon's idle
  354. ask). A 200 assignment is accepted exactly like POST /start;
  355. returns (status, payload|None)."""
  356. token = self.token
  357. if token is None:
  358. raise SystemExit("fake daemon asked before receiving its token")
  359. status, payload = saddle_api("POST", "/api/saddle/next-task", token)
  360. with self.lock:
  361. self.asks.append({"status": status, "payload": payload})
  362. if status == 200:
  363. self.accept_assignment(payload)
  364. return status, payload
  365. def _trigger_ask(self, reason):
  366. """Schedules a delayed ask (the daemon woke / went idle-awake).
  367. ask_delay models a SLOW asker — a daemon still winding down its
  368. round when the wake lands: it honours the wake, but its ask
  369. arrives late (still inside the web's lost-wake guard window)."""
  370. def run():
  371. if self.state in ("working", "failing"):
  372. return # a running daemon does not ask
  373. if self.ask_delay > 0:
  374. time.sleep(self.ask_delay)
  375. for attempt in range(3):
  376. try:
  377. status, _ = self.ask_now()
  378. if status in (200, 204):
  379. return
  380. print(" (ask %s -> HTTP %s, attempt %d)" % (reason, status, attempt + 1))
  381. except Exception as error: # app restarting / blips: retry
  382. print(" (ask %s failed: %r, attempt %d)" % (reason, error, attempt + 1))
  383. time.sleep(1.0)
  384. threading.Thread(target=lambda: (time.sleep(0.2), run()), daemon=True).start()
  385. def maybe_trigger_ask(self, reason, throttle=False):
  386. """Schedules an idle-awake ask. Protocol events (wake, abort,
  387. round end, park) ask singularly and immediately; only the
  388. /status-observation path throttles (a burst of probes must not
  389. hammer the ask endpoint)."""
  390. now = time.monotonic()
  391. if throttle and now - self.last_ask_trigger < 1.0:
  392. return
  393. self.last_ask_trigger = now
  394. self._trigger_ask(reason)
  395. def accept_assignment(self, payload):
  396. """A 200 next-task assignment: adopted exactly like POST /start."""
  397. self.start_payloads.append(payload)
  398. task = payload.get("task") or {}
  399. task_id = task.get("id")
  400. self.running_task = int(task_id or 0)
  401. self.running_title = task.get("title") or ""
  402. self.session_id = payload.get("session_id")
  403. count = self.start_counts.get(task_id, 0) + 1
  404. self.start_counts[task_id] = count
  405. if count > 1:
  406. # Crash-resume contract: re-pushing a task whose
  407. # workspace still exists restores it; the first
  408. # /status after the restore reports "resumed": true.
  409. self.resumed_pending = True
  410. self.set_state("failing" if self.fail_next else "working")
  411. self.fail_next = False
  412. # The round's opening telemetry: the flushed-so-far raw PTY
  413. # batch plus the working state push (>= 2 flushes per round
  414. # and the 10s timer are the real daemon's contract; the fake
  415. # pushes its batch up front and heartbeats while working).
  416. if self.scripted_corpus is not None:
  417. self.push_chunks([dict(chunk) for chunk in self.scripted_corpus])
  418. else:
  419. self.push_chunks([self.PROMPT, "echo hello\r\n", "hello\r\n"])
  420. self.push_results("working")
  421. class Handler(BaseHTTPRequestHandler):
  422. daemon = None # set on the class before serving
  423. protocol_version = "HTTP/1.1"
  424. def log_message(self, fmt, *args):
  425. pass
  426. def maybe_hang(self, path):
  427. """True when this request should hang forever (never respond),
  428. consuming one unit of the path's hang budget."""
  429. for suffix, count in list(self.daemon.hang_next.items()):
  430. if count > 0 and path.startswith(suffix):
  431. self.daemon.hang_next[suffix] = count - 1
  432. return True
  433. return False
  434. def _send(self, status, obj):
  435. body = json.dumps(obj).encode()
  436. self.send_response(status)
  437. self.send_header("Content-Type", "application/json")
  438. self.send_header("Content-Length", str(len(body)))
  439. self.end_headers()
  440. self.wfile.write(body)
  441. def do_POST(self):
  442. if self.maybe_hang(self.path):
  443. time.sleep(600)
  444. return
  445. self.daemon.touch_activity()
  446. length = int(self.headers.get("Content-Length") or 0)
  447. raw = self.rfile.read(length).decode() if length else "{}"
  448. if self.path == "/register":
  449. # Plan 10: the web delivers the per-saddle token + its
  450. # own base URL; the daemon persists the token for its
  451. # calls home and reports its ssh key + version.
  452. if not self.daemon.serve_register:
  453. self._send(404, {"error": "no such route"})
  454. return
  455. try:
  456. payload = json.loads(raw)
  457. except ValueError:
  458. payload = {"raw": raw}
  459. self.daemon.register_log.append(payload)
  460. if payload.get("saddle_token"):
  461. self.daemon.token = payload["saddle_token"]
  462. self._send(200, {"ok": True,
  463. "ssh_public_key": self.daemon.ssh_public_key,
  464. "version": "0.1-fake"})
  465. if self.daemon.ask_on_register:
  466. self.daemon.maybe_trigger_ask("register")
  467. return
  468. if self.path == "/wake":
  469. # Plan 10: a capable task is ready; a sleeping daemon
  470. # asks for work (immediately — a wake is a direct
  471. # command, never throttled).
  472. self.daemon.wake_log.append(time.monotonic())
  473. self._send(200, {"ok": True})
  474. if self.daemon.ask_on_wake:
  475. self.daemon.maybe_trigger_ask("wake")
  476. return
  477. if self.path == "/task-update":
  478. # Plan 10: cancel (abort machinery), comment (injected
  479. # turn) and subtask-status (live subtask set) — delivered
  480. # directly to a RUNNING daemon, no auth.
  481. try:
  482. payload = json.loads(raw)
  483. except ValueError:
  484. self._send(400, {"error": "bad json"})
  485. return
  486. kind = payload.get("kind")
  487. if kind == "cancel":
  488. if self.daemon.abort_failures > 0:
  489. self.daemon.abort_failures -= 1
  490. self._send(500, {"error": "cancel failed (simulated)"})
  491. return
  492. aborted = self.daemon.running_task
  493. self.daemon.set_state("idle")
  494. self.daemon.summary = ""
  495. self.daemon.running_task = 0
  496. self.daemon.session_id = None
  497. self.daemon.abort_log.append(aborted)
  498. self._send(200, {"ok": True, "aborted_task_id": aborted})
  499. # An aborted daemon returns to its idle loop: it asks.
  500. self.daemon.maybe_trigger_ask("aborted")
  501. elif kind == "comment":
  502. self.daemon.comment_log.append(payload)
  503. self._send(200, {"ok": True})
  504. elif kind == "subtask-status":
  505. if self.daemon.fail_subtask_status:
  506. self._send(500, {"error": "simulated failure"})
  507. return
  508. self.daemon.subtask_status_events.append(payload)
  509. self._send(200, {"ok": True})
  510. else:
  511. self._send(400, {"error": "unknown task-update kind"})
  512. return
  513. self._send(404, {"error": "no such route"})
  514. self.close_connection = True
  515. def do_GET(self):
  516. if self.maybe_hang(self.path):
  517. time.sleep(600)
  518. return
  519. if self.path != "/status":
  520. # /status itself is not daemon activity: the liveness
  521. # signal must reflect loop rounds / command completions.
  522. self.daemon.touch_activity()
  523. if self.path == "/status":
  524. self.daemon.status_hits += 1
  525. response = {"state": self.daemon.state, "summary": self.daemon.summary,
  526. "uptime_seconds": int(time.monotonic() - self.daemon.started_mono),
  527. "last_activity_epoch": self.daemon.last_activity_epoch,
  528. "ssh_public_key": self.daemon.ssh_public_key}
  529. if self.daemon.resumed_pending:
  530. response["resumed"] = True
  531. self.daemon.resumed_pending = False
  532. # A parked/terminal daemon is idle-awake: a phase-1
  533. # daemon asks (and sleeps on 204). Throttled so status
  534. # poll bursts do not hammer the ask endpoint.
  535. if self.daemon.ask_on_idle_status and self.daemon.state in (
  536. "idle", "done", "failed", "suspended"):
  537. self.daemon.maybe_trigger_ask("idle-status", throttle=True)
  538. self._send(200, response)
  539. else:
  540. self._send(404, {"error": "no such route"})
  541. self.close_connection = True
  542. def run_lifecycle(self):
  543. """Applies the scripted lifecycle on a timer (like a real daemon
  544. whose task ends on its own): working heartbeats chunks (the 10s
  545. flush timer's stand-in, keeping the staleness clock fed), works
  546. for ~8s, then pushes done/suspended; failing pushes failed after
  547. ~1s — and a task END makes the idle-awake daemon ask again."""
  548. while True:
  549. time.sleep(0.5)
  550. if self.hold_state or self.silent:
  551. # hold_state freezes the script; silent models a daemon
  552. # mid-round with nothing to flush — its round has not
  553. # ended, so no terminal push fires while quiet.
  554. continue
  555. if self.state == "failing":
  556. if time.monotonic() - self.state_entered >= 1:
  557. self.set_state("failed", "bash -n rejected the script (simulated)")
  558. self.push_results("failed",
  559. summary="bash -n rejected the script (simulated)")
  560. if self.ask_on_terminal:
  561. self.maybe_trigger_ask("terminal")
  562. elif self.state == "working":
  563. if time.monotonic() - self.state_entered >= 8:
  564. if self.suspend_on_title and self.suspend_on_title == self.running_title:
  565. # `saddle suspend`: park until a fresh assignment
  566. # resumes the workspace (title-targeted one-shot,
  567. # so an interleaved dispatch cannot eat the flag).
  568. self.set_state("suspended")
  569. self.suspend_on_title = None
  570. self.push_results("suspended")
  571. # A parked daemon is idle-awake: it asks (and
  572. # sleeps on 204) so a later wake can reach it.
  573. if self.ask_on_idle_status:
  574. self.maybe_trigger_ask("parked")
  575. else:
  576. self.set_state("done", "fake daemon finished")
  577. self.push_results("done", summary="fake daemon finished")
  578. if self.ask_on_terminal:
  579. self.maybe_trigger_ask("terminal")
  580. elif time.monotonic() - getattr(self, "last_heartbeat", 0) >= 2:
  581. # The flush timer: output keeps flowing, so chunks
  582. # keep arriving (the staleness window never opens on
  583. # a healthy runner).
  584. self.last_heartbeat = time.monotonic()
  585. self.push_chunks(["working-heartbeat\r\n"])
  586. def serve(self, port=None):
  587. """Binds the daemon's HTTP server. A requested port that is
  588. already taken (free_port() hands out recyclable ports — two
  589. calls can collide) falls back to an OS-assigned one instead of
  590. silently dying and impersonating whatever owns that port."""
  591. if port is None:
  592. port = DAEMON_PORT
  593. handler = type("BoundHandler", (FakeSaddle.Handler,), {"daemon": self})
  594. self.server = None
  595. try:
  596. self.server = ThreadingHTTPServer(("127.0.0.1", port), handler)
  597. except OSError:
  598. print("(fake daemon: port %d taken, falling back)" % port)
  599. self.server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
  600. self.port = self.server.server_address[1]
  601. threading.Thread(target=self.server.serve_forever, daemon=True).start()
  602. threading.Thread(target=self.run_lifecycle, daemon=True).start()
  603. return self.server
  604. def kill(self):
  605. """The daemon dies: it stops listening (connections refused) AND
  606. stops calling home — no pushes, no asks (a dead process has no
  607. outbound anything; in-flight handler threads may linger but the
  608. wire contract's traffic is one-directional now)."""
  609. self.dead = True
  610. if getattr(self, "server", None) is not None:
  611. self.server.shutdown()
  612. self.server.server_close()
  613. self.server = None
  614. def start_app():
  615. config = json.load(open(os.path.join(REPO, "web-config.json")))
  616. config["saddle_callback_base_url"] = WEB
  617. with open(os.path.join(WORK, "web-config.json"), "w") as handle:
  618. json.dump(config, handle)
  619. env = dict(os.environ)
  620. env.update({
  621. "SPRY_DB_PATH": DB_PATH,
  622. "SPRY_SEED_ADMIN_USERNAME": "admin",
  623. "SPRY_SEED_ADMIN_PASSWORD": "adminpass123",
  624. "SADDLE_LLM_BASE_URL": "http://127.0.0.1:%d" % DAEMON_PORT,
  625. "SADDLE_PROJECTS_ROOT": os.path.join(WORK, "workspace"),
  626. "SADDLE_HTTP_TIMEOUT_S": "5",
  627. "SADDLE_LOST_WAKE_S": "2",
  628. "SADDLE_STALE_S": "3",
  629. # Never inherit a caller-poisoned LD_LIBRARY_PATH (e.g. one that
  630. # resolves the ancient /lib64 copies): empty makes the loader use
  631. # the binary's RUNPATH, which is the dev stack it was built
  632. # against.
  633. "LD_LIBRARY_PATH": "",
  634. })
  635. log_previous = os.path.join(WORK, "app.log.1")
  636. if os.path.exists(os.path.join(WORK, "app.log")):
  637. shutil.move(os.path.join(WORK, "app.log"), log_previous)
  638. log = open(os.path.join(WORK, "app.log"), "w")
  639. command = [APP, str(APP_PORT)]
  640. if os.environ.get("WEBSTACK_GDB"):
  641. # Debugging aid: run the app under gdb; a crash backtrace lands in
  642. # app.log. WEBSTACK_GDB=1 meson test ... to enable.
  643. command = ["gdb", "-batch", "-quiet",
  644. "-ex", "handle SIGPIPE nostop noprint pass",
  645. "-ex", "run", "-ex", "bt", "--args", APP, str(APP_PORT)]
  646. process = subprocess.Popen(command, cwd=WORK, env=env,
  647. stdout=log, stderr=subprocess.STDOUT)
  648. outcome = wait_for(lambda: (app_ready() and "ready")
  649. or (process.poll() is not None and "app-exited-%d" % process.poll())
  650. or False, timeout=30, what="app ready")
  651. if outcome is None:
  652. raise SystemExit("app did not come up; see %s/app.log" % WORK)
  653. if str(outcome).startswith("app-exited-"):
  654. raise SystemExit("app exited during startup (%s); see %s/app.log"
  655. % outcome, WORK)
  656. return process
  657. def app_ready():
  658. try:
  659. status, _ = http("GET", "/login", timeout=3)
  660. return status == 200
  661. except (urllib.error.URLError, OSError):
  662. return False
  663. def dump_app_stacks(pid):
  664. """Best-effort thread backtrace of the (possibly wedged) app."""
  665. try:
  666. fds = os.listdir("/proc/%d/fd" % pid)
  667. print("(app open fds at dump: %d)" % len(fds))
  668. kinds = {}
  669. for fd in fds[:1200]:
  670. try:
  671. target = os.readlink("/proc/%d/fd/%s" % (pid, fd))
  672. except OSError:
  673. continue
  674. key = target.split(":", 1)[0] if ":" in target else target
  675. kinds[key] = kinds.get(key, 0) + 1
  676. print("(fd kinds: %s)" % sorted(kinds.items(), key=lambda kv: -kv[1])[:6])
  677. except OSError:
  678. pass
  679. for command in (["eu-stack", "-p", str(pid)],
  680. ["gdb", "-batch", "-quiet", "-p", str(pid),
  681. "-ex", "thread apply all bt"]):
  682. try:
  683. out = subprocess.run(command, capture_output=True, timeout=60)
  684. text = out.stdout.decode(errors="replace") + out.stderr.decode(errors="replace")
  685. if text.strip():
  686. print("(app stacks via %s)\n%s" % (command[0], text[:12000]))
  687. return
  688. except (OSError, subprocess.SubprocessError):
  689. continue
  690. def main():
  691. if not os.path.exists(APP):
  692. raise SystemExit("app binary not found at %s (build first)" % APP)
  693. fake = FakeSaddle()
  694. fake.serve()
  695. # A rare framework-level crash (stack corruption in Statum slot
  696. # signing during the FIRST login — shared-library codegen bug, moved
  697. # twice already) kills the app before any test runs; a clean restart
  698. # sidesteps it. Only tolerated while nothing has been checked yet.
  699. auth = None
  700. app = None
  701. for attempt in range(3):
  702. if os.path.exists(WORK):
  703. shutil.rmtree(WORK)
  704. os.makedirs(os.path.join(WORK, "workspace"))
  705. try:
  706. app = start_app()
  707. auth = login("admin", "adminpass123")
  708. break
  709. except (SystemExit, OSError, urllib.error.URLError):
  710. if passes > 0:
  711. raise
  712. if app is not None and app.poll() is None:
  713. app.terminate()
  714. try:
  715. app.wait(timeout=5)
  716. except subprocess.TimeoutExpired:
  717. app.kill()
  718. app = None
  719. print("(app died before login; restarting cleanly, attempt %d)" % (attempt + 1))
  720. if app is None or auth is None:
  721. raise SystemExit("app never came up; see %s/app.log" % WORK)
  722. try:
  723. check(True, "login yields an auth slot")
  724. print("== feature 3: plan review hides duplicate body ==")
  725. state = slot_public(auth, "/projects", "projects")
  726. act(auth, state["create"], {
  727. "name": "demo",
  728. "git_url": "https://example.com/demo.git",
  729. "default_branch": "main",
  730. })
  731. conn = db()
  732. conn.execute("insert into tasks (project_id, title, status, priority,"
  733. " is_design_task, plan, created_at)"
  734. " values (1, 'Plan review task', 'working', 5, 1, '# The plan\n\n1. Do it',"
  735. " strftime('%s','now'))")
  736. conn.commit()
  737. plan_task = conn.execute("select max(id) from tasks").fetchone()[0]
  738. saddles_state = slot_public(auth, "/saddles", "saddles")
  739. act(auth, saddles_state["register"], {"name": "fake-saddle",
  740. "host": "127.0.0.1:%d" % DAEMON_PORT})
  741. registered = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  742. if s["name"] == "fake-saddle"]
  743. check(len(registered) == 1 and registered[0]["token"].startswith("saddle-"),
  744. "fake saddle registered with an API token")
  745. fake_id = int(registered[0]["id"])
  746. fake_token = registered[0]["token"]
  747. # Plan 10 phase 1: registration delivers the per-saddle token to
  748. # the daemon via POST /register {saddle_token, web_base_url}.
  749. check(wait_for(lambda: len(fake.register_log) > 0 or False,
  750. timeout=15, what="/register delivery") is not None,
  751. "registration POSTs /register to the daemon")
  752. register_body = fake.register_log[0]
  753. check(register_body.get("saddle_token") == fake_token,
  754. "/register carries the minted per-saddle token")
  755. check(register_body.get("web_base_url") == WEB,
  756. "/register carries the web base URL")
  757. check(fake.token == fake_token,
  758. "daemon persisted the token (its asks use it)")
  759. token_conn = db()
  760. row_token = token_conn.execute("select token from saddles where id = ?",
  761. (fake_id,)).fetchone()[0]
  762. token_conn.close()
  763. check(row_token == fake_token,
  764. "per-saddle token lives on the saddle row")
  765. # The register-time ask (idle-awake daemon): 204, nothing
  766. # offerable yet — the saddle is asleep and wakeable.
  767. check(wait_for(lambda: any(a["status"] == 204 for a in fake.asks) or False,
  768. timeout=15, what="register-time ask") is not None,
  769. "the daemon's idle ask returns 204 (nothing offerable)")
  770. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  771. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  772. (plan_task, fake_id))
  773. conn.commit()
  774. session_id = conn.execute("select max(id) from sessions").fetchone()[0]
  775. conn.close()
  776. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  777. {"type": "block", "session_id": session_id, "data": {
  778. "question": "Plan submitted for review",
  779. "type": "rfc",
  780. "body": "# The plan\n\n1. Do it"}})
  781. check(status == 200 and body.get("block_id"), "plan-review block raised")
  782. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  783. {"type": "block", "session_id": session_id, "data": {
  784. "question": "Which database?",
  785. "type": "question",
  786. "options": ["SQLite", "Postgres"],
  787. "body": "# Storage choice"}})
  788. check(status == 200, "question block raised")
  789. detail = task_state(auth, plan_task)
  790. blocks = {b["block_type"]: b for b in detail["blocks"]}
  791. check(blocks["rfc"].get("is_plan_review") is True,
  792. "rfc block flagged as the plan review")
  793. check(blocks["rfc"].get("show_body") is False,
  794. "pending plan review hides the duplicate body preview")
  795. check(blocks["question"].get("show_body") is True,
  796. "question block keeps its body preview")
  797. act(auth, blocks["rfc"]["answer_action"], {"answer": "Plan approved. Proceed."})
  798. detail = task_state(auth, plan_task)
  799. rfc = [b for b in detail["blocks"] if b["block_type"] == "rfc"][0]
  800. check(rfc.get("show_body") is True,
  801. "answered plan review shows the body again (review section gone)")
  802. print("== B1: highlight-to-comment quote dialog ==")
  803. status, page = http("GET", "/tasks/%d" % plan_task, timeout=15)
  804. check(status == 200 and "quote-comment-dialog" in page and "quote-text" in page,
  805. "task page carries the quote-comment dialog the popover opens")
  806. check('name="quote"' in page and 'name="return_to"' in page,
  807. "quote dialog posts the quote and return-to fields")
  808. status, page = http("GET", "/tasks/%d/terminal" % plan_task, timeout=15)
  809. check(status == 200 and "quote-comment-dialog" in page,
  810. "terminal page keeps its quote dialog")
  811. print("== B3: review section hides the duplicate body ==")
  812. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  813. {"type": "block", "session_id": session_id, "data": {
  814. "question": "Review the diff",
  815. "type": "review",
  816. "body": "# The change\n\nReworks the flange module."}})
  817. check(status == 200 and body.get("block_id"), "review block raised")
  818. detail = task_state(auth, plan_task)
  819. review_block = [b for b in detail["blocks"] if b["block_type"] == "review"][0]
  820. check(detail.get("review_pending") is True,
  821. "review section shows while the review is unanswered")
  822. check(review_block.get("show_body") is False,
  823. "pending review block hides its duplicate body preview")
  824. check(review_block.get("body", "").startswith("# The change"),
  825. "review body itself still arrives in state (B2 counterpart)")
  826. act(auth, review_block["answer_action"], {"answer": "Human approved the review"})
  827. detail = task_state(auth, plan_task)
  828. review_block = [b for b in detail["blocks"] if b["block_type"] == "review"][0]
  829. check(review_block.get("show_body") is True,
  830. "answered review shows the body again (banner gone)")
  831. print("== B2: question block body above options ==")
  832. # Contract side (A2 will restore bodies end-to-end): a question
  833. # block raised with a heredoc body carries it; the body preview
  834. # rides above the options (template order) and survives answering
  835. # alongside the selected answer.
  836. detail = task_state(auth, plan_task)
  837. question = [b for b in detail["blocks"] if b["block_type"] == "question"][0]
  838. check(question.get("body") == "# Storage choice"
  839. and question.get("show_body") is True,
  840. "question block keeps its body markdown with the preview on")
  841. act(auth, question["answer_action"], {"option": "SQLite"})
  842. detail = task_state(auth, plan_task)
  843. question = [b for b in detail["blocks"] if b["block_type"] == "question"][0]
  844. check(question.get("answered") is True and question.get("answer") == "SQLite"
  845. and question.get("body") == "# Storage choice"
  846. and question.get("show_body") is True,
  847. "answered question shows body + selected answer")
  848. print("== B5: compare-changes SSH -> HTTPS ==")
  849. def diff_url_for_project(git_url, suffix):
  850. state = slot_public(auth, "/projects", "projects")
  851. act(auth, state["create"], {"name": "diff-%s" % suffix, "git_url": git_url})
  852. project_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  853. if p["name"] == "diff-%s" % suffix][0])
  854. conn = db()
  855. conn.execute("insert into tasks (project_id, title, status, task_branch,"
  856. " branch_from, created_at) values (?, ?, 'working', 'feature/x',"
  857. " 'main', strftime('%s','now'))", (project_id, "Diff %s" % suffix))
  858. conn.commit()
  859. task_id = conn.execute("select max(id) from tasks").fetchone()[0]
  860. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at,"
  861. " outcome) values (?, ?, strftime('%s','now'), strftime('%s','now'),"
  862. " 'done')", (task_id, fake_id))
  863. conn.commit()
  864. session = conn.execute("select max(id) from sessions").fetchone()[0]
  865. conn.close()
  866. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  867. {"type": "block", "session_id": session, "data": {
  868. "question": "Review the diff", "type": "review"}})
  869. return task_state(auth, task_id).get("review_diff_url") or ""
  870. check(diff_url_for_project("ssh://fabrica.unitatem.net:222/clanker/clanker-saddle.git",
  871. "fabrica")
  872. == "https://fabrica.unitatem.net/clanker/clanker-saddle/compare/main...feature/x",
  873. "ssh://git@host:port/owner/repo.git translates (port dropped)")
  874. check(diff_url_for_project("git@github.com:acme/widgets.git", "scp")
  875. == "https://github.com/acme/widgets/compare/main...feature/x",
  876. "git@host:owner/repo.git translates to the browse host")
  877. check(diff_url_for_project("https://example.com/plain/repo", "plain")
  878. == "https://example.com/plain/repo/compare/main...feature/x",
  879. "HTTPS URLs pass through unchanged")
  880. print("== feature 5: rules ==")
  881. rules_state = slot_public(auth, "/rules", "rules")
  882. for name, body in [
  883. ("Use Invercargill", "Never use libgee; use Invercargill enumerables."),
  884. ("Write Vala docs", "Every public class carries a doc comment."),
  885. ("Prefer meson", "Builds go through meson; no makefiles."),
  886. ("Co-dev rule", "Keep the wire contract exactly."),
  887. ("Reference rule", "Must never ride along."),
  888. ]:
  889. act(auth, rules_state["create"], {"name": name, "body": body})
  890. listed = {r["name"]: r for r in slot_public(auth, "/rules", "rules")["rules"]}
  891. check(len(listed) == 5, "five rules created and listed on /rules")
  892. def rule_id(name):
  893. rows = [r for r in slot_public(auth, "/rules", "rules")["rules"] if r["name"] == name]
  894. return int(rows[0]["id"])
  895. state = slot_public(auth, "/projects", "projects")
  896. act(auth, state["create"], {"name": "co", "git_url": "https://example.com/co.git"})
  897. act(auth, state["create"], {"name": "ref", "git_url": "https://example.com/ref.git"})
  898. co_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  899. if p["name"] == "co"][0])
  900. ref_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  901. if p["name"] == "ref"][0])
  902. project = slot_public(auth, "/projects/1", "project")
  903. act(auth, project["add_link"], {"linked_project_id": str(co_id),
  904. "relationship": "co-developed"})
  905. act(auth, project["add_link"], {"linked_project_id": str(ref_id),
  906. "relationship": "reference"})
  907. act(auth, project["attach_rule"], {"rule_id": str(rule_id("Use Invercargill"))})
  908. act(auth, project["attach_rule"], {"rule_id": str(rule_id("Prefer meson"))})
  909. project = slot_public(auth, "/projects/1", "project")
  910. check(sorted(r["name"] for r in project["rules"]) == ["Prefer meson", "Use Invercargill"],
  911. "project page lists its attached rules")
  912. co_project = slot_public(auth, "/projects/%d" % co_id, "project")
  913. act(auth, co_project["attach_rule"], {"rule_id": str(rule_id("Co-dev rule"))})
  914. ref_project = slot_public(auth, "/projects/%d" % ref_id, "project")
  915. act(auth, ref_project["attach_rule"], {"rule_id": str(rule_id("Reference rule"))})
  916. tasks_state = slot_public(auth, "/tasks", "tasks")
  917. act(auth, tasks_state["create"], {
  918. "project_id": "1",
  919. "title": "Rules dispatch",
  920. "description": "Effective rule set rides the /start payload.",
  921. "priority": "2",
  922. })
  923. rule_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  924. if t["title"] == "Rules dispatch"][0])
  925. detail = task_state(auth, rule_task)
  926. act(auth, detail["attach_rule"], {"rule_id": str(rule_id("Write Vala docs"))})
  927. act(auth, detail["attach_rule"], {"rule_id": str(rule_id("Use Invercargill"))})
  928. detail = task_state(auth, rule_task)
  929. check(sorted(r["name"] for r in detail["rules"]) == ["Use Invercargill", "Write Vala docs"],
  930. "task page lists its attached rules")
  931. check(wait_for(lambda: len(fake.start_payloads) > 0 or False,
  932. timeout=30, what="/start push") is not None,
  933. "dispatcher pushes the task to the fake saddle")
  934. payload = fake.start_payloads[-1]
  935. rule_names = [r["name"] for r in payload.get("rules", [])]
  936. check(rule_names == ["Write Vala docs", "Use Invercargill", "Prefer meson", "Co-dev rule"],
  937. "effective rules in /start: task, primary, co-developed order (%s)" % rule_names)
  938. check(all(r.get("body") for r in payload.get("rules", [])),
  939. "rules carry their bodies")
  940. check("Reference rule" not in rule_names,
  941. "reference project rules excluded")
  942. detail = task_state(auth, rule_task)
  943. act(auth, detail["rules"][0]["detach"], {})
  944. check([r["name"] for r in task_state(auth, rule_task)["rules"]] == ["Use Invercargill"],
  945. "detached task rule disappears")
  946. rules_rows = slot_public(auth, "/rules", "rules")["rules"]
  947. docs_row = [r for r in rules_rows if r["name"] == "Write Vala docs"][0]
  948. act(auth, docs_row["update"], {"name": "Write Vala docs", "body": "Doc comments or bust."})
  949. check(any(r["body"] == "Doc comments or bust."
  950. for r in slot_public(auth, "/rules", "rules")["rules"]),
  951. "rule edit saves the body")
  952. check(wait_task_done(auth, rule_task, timeout=60) is not None,
  953. "dispatched task completes against the fake daemon")
  954. print("== feature 6: project notes + callback ==")
  955. # Plan 10 phase 1: the shared saddle-callback token is gone —
  956. # the per-saddle token authorises the callback endpoints.
  957. callback_token = fake_token
  958. check(callback_token.startswith("saddle-") and "saddle-callback-" not in callback_token,
  959. "note callback authorised by the per-saddle token")
  960. status, _ = saddle_api("POST", "/api/saddle/note", None,
  961. {"project": "demo", "body": "x"})
  962. check(status == 401, "note endpoint rejects a missing token")
  963. status, _ = saddle_api("POST", "/api/saddle/note", "saddle-callback-not-real",
  964. {"project": "demo", "body": "x"})
  965. check(status == 401, "note endpoint rejects a wrong (legacy-style) token")
  966. status, body = saddle_api("POST", "/api/saddle/note", callback_token,
  967. {"task_id": rule_task, "project": "demo",
  968. "body": "style.css tokens live in :root"})
  969. check(status == 200 and body.get("ok") is True, "note accepted with the callback token")
  970. status, _ = saddle_api("POST", "/api/saddle/note", callback_token,
  971. {"project": "no-such-project", "body": "x"})
  972. check(status == 400, "unknown project rejected")
  973. status, _ = saddle_api("POST", "/api/saddle/note", callback_token,
  974. {"project": "demo", "body": " "})
  975. check(status == 400, "empty note body rejected")
  976. project = slot_public(auth, "/projects/1", "project")
  977. check(any("style.css tokens" in n["body"] and int(n["source_task_id"]) == rule_task
  978. for n in project["notes"]),
  979. "project page lists the note with its source task")
  980. act(auth, [n for n in project["notes"] if "style.css tokens" in n["body"]][0]["delete"], {})
  981. check(all("style.css tokens" not in n["body"]
  982. for n in slot_public(auth, "/projects/1", "project")["notes"]),
  983. "note deleted from the project page")
  984. # /start payload: notes of primary + co-developed (not reference),
  985. # oldest first; callback carries the configured base URL + token.
  986. saddle_api("POST", "/api/saddle/note", callback_token,
  987. {"project": "demo", "body": "note-one"})
  988. saddle_api("POST", "/api/saddle/note", callback_token,
  989. {"project": "demo", "body": "note-two"})
  990. saddle_api("POST", "/api/saddle/note", callback_token,
  991. {"project": "co", "body": "co-note"})
  992. conn = db()
  993. conn.execute("insert into project_notes (project_id, body, created_at)"
  994. " values (?, 'ref-note-must-not-ship', strftime('%s','now'))", (ref_id,))
  995. conn.commit()
  996. conn.close()
  997. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  998. "project_id": "1",
  999. "title": "Notes dispatch",
  1000. "description": "Project notes ride the /start payload.",
  1001. "priority": "2",
  1002. })
  1003. check(wait_for(lambda: len(fake.start_payloads) >= 2 or False,
  1004. timeout=30, what="second /start push") is not None,
  1005. "dispatcher pushes the notes task")
  1006. payload = fake.start_payloads[-1]
  1007. notes = payload.get("project_notes", [])
  1008. check([n["body"] for n in notes] == ["note-one", "note-two", "co-note"],
  1009. "project_notes: primary + co-developed, oldest first (%s)" % [n["body"] for n in notes])
  1010. check(all(n.get("project") for n in notes)
  1011. and notes[2]["project"] == "co",
  1012. "project_notes carry the project name")
  1013. check("ref-note-must-not-ship" not in [n["body"] for n in notes],
  1014. "reference project notes excluded")
  1015. callback = payload.get("callback", {})
  1016. check(callback.get("base_url") == WEB and callback.get("token") == callback_token,
  1017. "callback carries the configured base URL and the minted token")
  1018. # entry cap: 30 of 33 candidates
  1019. conn = db()
  1020. for i in range(33):
  1021. conn.execute("insert into project_notes (project_id, body, created_at)"
  1022. " values (?, ?, strftime('%s','now'))", (1, "bulk-%02d" % i))
  1023. conn.commit()
  1024. conn.close()
  1025. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1026. "project_id": "1",
  1027. "title": "Entry cap dispatch",
  1028. "priority": "2",
  1029. })
  1030. check(wait_for(lambda: len(fake.start_payloads) >= 3 or False,
  1031. timeout=30, what="third /start push") is not None,
  1032. "dispatcher pushes the entry-cap task")
  1033. notes = fake.start_payloads[-1].get("project_notes", [])
  1034. check(len(notes) == 30 and notes[0]["body"] == "note-one" and notes[1]["body"] == "note-two",
  1035. "project_notes capped at 30 entries, oldest kept (%d)" % len(notes))
  1036. # char cap: the giant note is truncated so the total stays <= 20000
  1037. conn = db()
  1038. conn.execute("delete from project_notes where body like 'bulk-%' or body = 'co-note'")
  1039. conn.execute("insert into project_notes (project_id, body, created_at)"
  1040. " values (?, ?, strftime('%s','now'))", (1, "giant!" + "x" * 25000,))
  1041. conn.commit()
  1042. conn.close()
  1043. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1044. "project_id": "1",
  1045. "title": "Char cap dispatch",
  1046. "priority": "2",
  1047. })
  1048. check(wait_for(lambda: len(fake.start_payloads) >= 4 or False,
  1049. timeout=30, what="fourth /start push") is not None,
  1050. "dispatcher pushes the char-cap task")
  1051. notes = fake.start_payloads[-1].get("project_notes", [])
  1052. total = sum(len(n["body"]) for n in notes)
  1053. check(len(notes) == 3 and total == 20000 and notes[2]["body"].startswith("giant!"),
  1054. "project_notes char cap: head kept, giant truncated (entries=%d, chars=%d)"
  1055. % (len(notes), total))
  1056. print("== phase 2: pushed chunks -> raw log + terminal view ==")
  1057. # Wait for the last dispatch to finish so its pushes landed.
  1058. check(wait_task_done(auth, task_id_of("Char cap dispatch"), timeout=60) is not None,
  1059. "char-cap task completes")
  1060. conn = db()
  1061. raw_session = conn.execute(
  1062. "select s.id from sessions s join tasks t on t.id = s.task_id"
  1063. " where t.title = 'Char cap dispatch' order by s.id desc limit 1").fetchone()[0]
  1064. rows = conn.execute("select seq, chunk from session_raw_log where session_id = ?"
  1065. " order by seq", (raw_session,)).fetchall()
  1066. conn.close()
  1067. check(len(rows) >= 3, "session_raw_log captured the pushed chunks (%d)" % len(rows))
  1068. seqs = [r[0] for r in rows]
  1069. check(seqs == sorted(seqs) and len(set(seqs)) == len(seqs),
  1070. "pushed chunks stored once, seq strictly increasing")
  1071. text = "".join(r[1] for r in rows)
  1072. check(fake.PROMPT in text and "echo hello" in text and "hello" in text,
  1073. "pushed raw log keeps the prompt and echoed output byte-exact")
  1074. check("working-heartbeat" in text,
  1075. "the flush-timer heartbeat chunks keep arriving mid-round")
  1076. terminal = slot_public(auth, "/tasks/%d/terminal" % task_id_of("Char cap dispatch"),
  1077. "terminal")
  1078. check(terminal.get("has_raw_log") is True and int(terminal["session_id"]) == raw_session,
  1079. "terminal view selects raw rendering for the raw session")
  1080. # Old sessions (typed entries, no raw rows) keep the fallback view.
  1081. conn = db()
  1082. conn.execute("insert into session_commands (session_id, command_text, output_text,"
  1083. " type, started_at) values (?, 'ls', 'old-output', 'command',"
  1084. " strftime('%s','now'))", (session_id,))
  1085. conn.commit()
  1086. conn.close()
  1087. legacy = slot_public(auth, "/tasks/%d/terminal" % plan_task, "terminal")
  1088. check(legacy.get("has_raw_log") is False,
  1089. "legacy session falls back to the entry-type terminal view")
  1090. request = urllib.request.Request(WEB + "/terminal-stream/%d" % raw_session)
  1091. with urllib.request.urlopen(request, timeout=15) as stream:
  1092. raw_events = []
  1093. deadline = time.monotonic() + 8
  1094. while time.monotonic() < deadline and len(raw_events) < 3:
  1095. line = stream.readline().decode().strip()
  1096. if not line.startswith("data: ") or line == "data: ping":
  1097. continue
  1098. event = json.loads(line[6:])
  1099. if event.get("type") == "raw":
  1100. raw_events.append(event)
  1101. check(len(raw_events) >= 3 and raw_events[0]["text"] == fake.PROMPT
  1102. and raw_events[0]["seq"] < raw_events[1]["seq"],
  1103. "terminal stream serves pushed chunks in seq order (prompt first)")
  1104. print("== phase 2: chunks/results ingestion — auth, idempotency ==")
  1105. # Token auth on both push channels (plan 10: the per-saddle
  1106. # bearer authorises every daemon->web call).
  1107. status, _ = saddle_api("POST", "/api/saddle/chunks", None,
  1108. {"session_id": raw_session, "chunks": []})
  1109. check(status == 401, "chunks endpoint rejects a missing token")
  1110. status, _ = saddle_api("POST", "/api/saddle/results", "saddle-bogus-token",
  1111. {"session_id": raw_session, "state": "working"})
  1112. check(status == 401, "results endpoint rejects a wrong token")
  1113. status, _ = saddle_api("POST", "/api/saddle/chunks", fake_token,
  1114. {"session_id": 99999, "chunks": []})
  1115. check(status == 400, "chunks for an unknown session rejected")
  1116. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  1117. {"session_id": raw_session, "state": "done"})
  1118. check(status == 200, "the owning saddle's session accepts its results")
  1119. # Pushed chunk idempotency: re-pushing a batch (the outbox's
  1120. # at-least-once redelivery after a lost response) consumes the
  1121. # duplicates and stores only the tail.
  1122. conn = db()
  1123. before = conn.execute("select count(*) from session_raw_log where session_id = ?",
  1124. (raw_session,)).fetchone()[0]
  1125. conn.close()
  1126. redelivery = [{"seq": r[0], "text": r[1]} for r in rows[:3]]
  1127. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token,
  1128. {"session_id": raw_session, "chunks": redelivery})
  1129. check(status == 200 and body.get("ok") is True and int(body.get("stored") or 0) == 0,
  1130. "a fully-duplicate batch stores nothing (duplicates consumed)")
  1131. fresh = [{"seq": 9000, "text": "late-flush\r\n"},
  1132. {"seq": 9001, "text": ""}] # truly empty text: no row
  1133. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token,
  1134. {"session_id": raw_session, "chunks": fresh})
  1135. check(status == 200 and int(body.get("stored") or 0) == 1,
  1136. "a partial-redelivery batch stores only the new chunks")
  1137. conn = db()
  1138. after = conn.execute("select count(*) from session_raw_log where session_id = ?",
  1139. (raw_session,)).fetchone()[0]
  1140. empty_row = conn.execute(
  1141. "select count(*) from session_raw_log where session_id = ? and seq = 9001",
  1142. (raw_session,)).fetchone()[0]
  1143. conn.close()
  1144. check(after == before + 1 and empty_row == 0,
  1145. "redelivered chunks never duplicate rows; empty text stores nothing")
  1146. # Pushed entries: today's OutputEntry shape with the daemon's
  1147. # global entry ids — a redelivered results push stores its
  1148. # entries exactly once.
  1149. def command_rows(session):
  1150. conn = db()
  1151. try:
  1152. return conn.execute(
  1153. "select command_text, type from session_commands"
  1154. " where session_id = ? order by id", (session,)).fetchall()
  1155. finally:
  1156. conn.close()
  1157. entries = [{"id": 8101, "command": "sed -n 1p README.md", "output": "# demo",
  1158. "exit_code": 0, "type": "command", "timestamp": "2026-09-06T00:00:00Z"}]
  1159. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  1160. {"session_id": raw_session, "state": "working",
  1161. "entries": entries})
  1162. check(status == 200, "entries push accepted")
  1163. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  1164. {"session_id": raw_session, "state": "working",
  1165. "entries": entries})
  1166. check(status == 200, "redelivered entries push accepted (at-least-once)")
  1167. stored = command_rows(raw_session)
  1168. check(len([r for r in stored if r[0] == "sed -n 1p README.md"]) == 1,
  1169. "redelivered entries store exactly once (entry-id cursor)")
  1170. # The retired daemon routes 404 (phase 2 deleted /output, /log
  1171. # and /start serving) — and the web app never calls them.
  1172. for method, path in (("GET", "/output?since=0"), ("GET", "/log?since=0"),
  1173. ("POST", "/start")):
  1174. request = urllib.request.Request(
  1175. "http://127.0.0.1:%d%s" % (fake.port, path),
  1176. data=b"{}" if method == "POST" else None, method=method)
  1177. try:
  1178. urllib.request.urlopen(request, timeout=5)
  1179. gone = False
  1180. except urllib.error.HTTPError as error:
  1181. gone = error.code == 404
  1182. check(gone, "the fake daemon's %s %s is deleted (404)" % (method, path))
  1183. with open(os.path.join(WORK, "app.log")) as handle:
  1184. app_log = handle.read()
  1185. check("Saddle output request" not in app_log and "Saddle log request" not in app_log,
  1186. "the web never polls /output or /log anymore")
  1187. print("== capabilities: tag-based routing ==")
  1188. saddles_state = slot_public(auth, "/saddles", "saddles")
  1189. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  1190. act(auth, saddles_state["create_capability"], {"name": "bigmem"})
  1191. saddles_state = slot_public(auth, "/saddles", "saddles")
  1192. caps = {c["name"]: c for c in saddles_state["capabilities"]}
  1193. check(len(caps) == 2 and all(int(c["saddle_count"]) == 0 and int(c["task_count"]) == 0
  1194. for c in caps.values()),
  1195. "capabilities created and listed with zero usage")
  1196. def saddle_card(name):
  1197. rows = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1198. if s["name"] == name]
  1199. return rows[0]
  1200. fake_card = saddle_card("fake-saddle")
  1201. check(fake_card["capabilities"] == [],
  1202. "saddle card starts with no capability chips")
  1203. # A task requiring 'gpu' waits while the only idle saddle lacks it;
  1204. # a later task without requirements still dispatches (skip-and-continue).
  1205. tasks_state = slot_public(auth, "/tasks", "tasks")
  1206. act(auth, tasks_state["create"], {
  1207. "project_id": "1",
  1208. "title": "GPU task",
  1209. "priority": "2",
  1210. })
  1211. gpu_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1212. if t["title"] == "GPU task"][0])
  1213. detail = task_state(auth, gpu_task)
  1214. act(auth, detail["attach_capability"], {"capability_id": str(int(caps["gpu"]["id"]))})
  1215. detail = task_state(auth, gpu_task)
  1216. check([c["name"] for c in detail["capabilities"]] == ["gpu"],
  1217. "task page lists the required capability")
  1218. # The only idle saddle lacks the tag, so the queue flags the wait
  1219. # (read before any other task claims the idle saddle).
  1220. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1221. if int(t["id"]) == gpu_task][0]
  1222. check(queue["status"] == "queued" and queue["capabilities"] == ["gpu"]
  1223. and queue.get("waiting_for_saddle") is True,
  1224. "queue row shows the waiting task with its tag and wait flag")
  1225. act(auth, tasks_state["create"], {
  1226. "project_id": "1",
  1227. "title": "Any-saddle task",
  1228. "priority": "3",
  1229. })
  1230. any_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1231. if t["title"] == "Any-saddle task"][0])
  1232. check(wait_for(lambda: task_state(auth, any_task).get("status") != "queued" or False,
  1233. timeout=30, what="uncapable task dispatches") is not None,
  1234. "task without requirements dispatches past the waiting task")
  1235. def capability_wait_logged():
  1236. with open(os.path.join(WORK, "app.log")) as handle:
  1237. app_log = handle.read()
  1238. return "waits for a capable saddle" in app_log and "requires: gpu" in app_log
  1239. check(wait_for(capability_wait_logged, timeout=20,
  1240. what="capability wait log") is not None,
  1241. "dispatcher logs the capability wait")
  1242. # Attaching the tag to the saddle releases the task.
  1243. fake_card = saddle_card("fake-saddle")
  1244. act(auth, fake_card["attach_capability"], {"capability_id": str(int(caps["gpu"]["id"]))})
  1245. fake_card = saddle_card("fake-saddle")
  1246. check([c["name"] for c in fake_card["capabilities"]] == ["gpu"],
  1247. "saddle card shows the attached chip")
  1248. check(wait_task_done(auth, gpu_task, timeout=60) is not None,
  1249. "task dispatches once the saddle carries the required tag")
  1250. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1251. if int(t["id"]) == gpu_task][0]
  1252. check(queue.get("waiting_for_saddle") is not True,
  1253. "wait flag clears once dispatched")
  1254. # Multi-tag: gpu + bigmem required, only gpu carried → waits; adding
  1255. # bigmem completes the superset. Both requirements ride the create
  1256. # form (atomic — attaching them one at a time would race a tick
  1257. # into dispatching on the partial set).
  1258. act(auth, tasks_state["create"], {
  1259. "project_id": "1",
  1260. "title": "Big task",
  1261. "priority": "2",
  1262. "capability_id": [str(int(caps["gpu"]["id"])), str(int(caps["bigmem"]["id"]))],
  1263. })
  1264. big_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1265. if t["title"] == "Big task"][0])
  1266. check(wait_for(lambda: ([t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1267. if int(t["id"]) == big_task][0].get("waiting_for_saddle")
  1268. is True) or False, timeout=30, what="big task waits") is not None,
  1269. "task waits when the saddle's tags are not a superset")
  1270. fake_card = saddle_card("fake-saddle")
  1271. act(auth, fake_card["attach_capability"], {"capability_id": str(int(caps["bigmem"]["id"]))})
  1272. check(wait_task_done(auth, big_task, timeout=60) is not None,
  1273. "task dispatches once the superset is complete")
  1274. # Detach a requirement; delete a capability everywhere.
  1275. detail = task_state(auth, big_task)
  1276. act(auth, [c for c in detail["capabilities"] if c["name"] == "bigmem"][0]["detach"], {})
  1277. check([c["name"] for c in task_state(auth, big_task)["capabilities"]] == ["gpu"],
  1278. "detached requirement disappears from the task")
  1279. bigmem_row = [c for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  1280. if c["name"] == "bigmem"][0]
  1281. act(auth, bigmem_row["delete"], {})
  1282. saddles_state = slot_public(auth, "/saddles", "saddles")
  1283. check(all(c["name"] != "bigmem" for c in saddles_state["capabilities"]),
  1284. "deleted capability gone from the catalogue")
  1285. check([c["name"] for c in task_state(auth, big_task)["capabilities"]] == ["gpu"],
  1286. "deleting a capability drops its task requirements")
  1287. check(all(c["name"] != "bigmem"
  1288. for c in saddle_card("fake-saddle")["capabilities"]),
  1289. "deleting a capability drops it from saddles")
  1290. print("== B4: required capabilities on the create form ==")
  1291. tasks_state = slot_public(auth, "/tasks", "tasks")
  1292. gpu_option = [o for o in tasks_state.get("capability_options", [])
  1293. if o["name"] == "gpu"][0]
  1294. check(len(tasks_state.get("capability_options", [])) >= 1,
  1295. "queue page offers capability options in the create form")
  1296. conn = db()
  1297. before = conn.execute("select count(*) from tasks").fetchone()[0]
  1298. conn.close()
  1299. act(auth, tasks_state["create"], {
  1300. "project_id": "1",
  1301. "title": "Bad cap task",
  1302. "capability_id": [gpu_option["id"], "999"],
  1303. })
  1304. conn = db()
  1305. after = conn.execute("select count(*) from tasks").fetchone()[0]
  1306. conn.close()
  1307. check(after == before, "unknown capability id rejects the create")
  1308. act(auth, tasks_state["create"], {
  1309. "project_id": "1",
  1310. "title": "Cap-on-create task",
  1311. "capability_id": [gpu_option["id"]],
  1312. })
  1313. cap_create = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1314. if t["title"] == "Cap-on-create task"][0])
  1315. detail = task_state(auth, cap_create)
  1316. check([c["name"] for c in detail["capabilities"]] == ["gpu"],
  1317. "capabilities from the create form land on the task")
  1318. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1319. if int(t["id"]) == cap_create][0]
  1320. check(queue["capabilities"] == ["gpu"],
  1321. "queue row shows the created task's requirements")
  1322. # The waiting flag must hold it back until the capable saddle frees
  1323. # up (the fake saddle still carries gpu from the routing checks).
  1324. check(queue.get("waiting_for_saddle") is not True,
  1325. "capable saddle available: no wait flag on the new task")
  1326. print("== B6: computed display state ==")
  1327. conn = db()
  1328. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  1329. " values (1, 'Parent', 'done', 5, strftime('%s','now'))")
  1330. parent6 = conn.execute("select max(id) from tasks").fetchone()[0]
  1331. # The post-mortem case: stored done WITH an unanswered review block.
  1332. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  1333. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  1334. (parent6, fake_id))
  1335. session6 = conn.execute("select max(id) from sessions").fetchone()[0]
  1336. conn.commit()
  1337. conn.close()
  1338. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1339. {"type": "block", "session_id": session6, "data": {
  1340. "question": "Review the final diff", "type": "review"}})
  1341. detail = task_state(auth, parent6)
  1342. check(detail.get("display") == "review requested" and detail.get("terminal") is True,
  1343. "unanswered review overrides the stored done status (terminal flag keeps stored truth)")
  1344. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1345. if int(t["id"]) == parent6][0]
  1346. check(queue["display"] == "review requested",
  1347. "queue row shows the computed review-requested display")
  1348. # Delegation: with the review answered, open subtasks delegate.
  1349. conn = db()
  1350. conn.execute("update task_blocks set answered_at = strftime('%s','now'),"
  1351. " answer = 'Human approved the review' where task_id = ?", (parent6,))
  1352. conn.execute("insert into tasks (project_id, title, status, priority, parent_task_id,"
  1353. " created_at) values (1, 'Sub A', 'working', 5, ?, strftime('%s','now'))",
  1354. (parent6,))
  1355. conn.execute("insert into tasks (project_id, title, status, priority, parent_task_id,"
  1356. " created_at) values (1, 'Sub B', 'done', 5, ?, strftime('%s','now'))",
  1357. (parent6,))
  1358. conn.commit()
  1359. conn.close()
  1360. detail = task_state(auth, parent6)
  1361. check(detail.get("display") == "delegating 1/2" and detail.get("subtask_open") == 1,
  1362. "open subtasks show the delegating breakdown (%s)" % detail.get("display"))
  1363. # Flags track the stored status once the display falls through
  1364. # (subtasks terminal first — delegating leads while any are open).
  1365. conn = db()
  1366. conn.execute("update tasks set status = 'failed', completed_at = strftime('%s','now')"
  1367. " where id = ?", (parent6,))
  1368. conn.execute("update tasks set status = 'failed', completed_at = strftime('%s','now')"
  1369. " where title = 'Sub A'")
  1370. conn.commit()
  1371. conn.close()
  1372. detail = task_state(auth, parent6)
  1373. check(detail.get("display") == "failed" and detail.get("failed") is True
  1374. and detail.get("terminal") is True,
  1375. "failed task with answered review and terminal subtasks shows failed + terminal flags")
  1376. print("== retry + resume ==")
  1377. # A daemon-side failure fails the task with its explanation.
  1378. fake.fail_next = True
  1379. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1380. "project_id": "1",
  1381. "title": "Flaky task",
  1382. "priority": "2",
  1383. })
  1384. flaky = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1385. if t["title"] == "Flaky task"][0])
  1386. check(wait_for(lambda: task_state(auth, flaky).get("status") == "failed" or False,
  1387. timeout=60, what="flaky task fails") is not None,
  1388. "daemon failure fails the task")
  1389. detail = task_state(auth, flaky)
  1390. check("bash -n rejected" in (detail.get("summary") or ""),
  1391. "failure summary shows the daemon's explanation")
  1392. # Retry: summary moves into a comment and clears, task requeues,
  1393. # history stays, and the re-dispatch restores the workspace.
  1394. comments_before = len(detail.get("comments", []))
  1395. progress_before = len(detail.get("progress", []))
  1396. act(auth, detail["retry"], {})
  1397. detail = task_state(auth, flaky)
  1398. check(detail["status"] == "queued" and (detail.get("summary") or "") == "",
  1399. "retry requeues the task and clears the stale summary")
  1400. check(any("bash -n rejected" in c["body"] for c in detail["comments"]),
  1401. "failure explanation kept as a bot comment")
  1402. check(any(c["body"] == "Task retried by user" for c in detail["comments"]),
  1403. "retry lands its audit comment")
  1404. check(len(detail["comments"]) >= comments_before + 1,
  1405. "retry keeps the comment history")
  1406. pushes_before = len([p for p in fake.start_payloads
  1407. if int(p.get("task", {}).get("id") or 0) == flaky])
  1408. check(wait_for(lambda: len([p for p in fake.start_payloads
  1409. if int(p.get("task", {}).get("id") or 0) == flaky])
  1410. > pushes_before or False, timeout=60,
  1411. what="flaky task re-dispatched") is not None,
  1412. "retried task dispatches again")
  1413. # The resumed arc surfaces on the next /status read — in the
  1414. # push world that is the operator's manual refresh.
  1415. act(auth, saddle_card("fake-saddle")["refresh"], {})
  1416. check(wait_task_done(auth, flaky, timeout=60) is not None,
  1417. "retried task completes on the restored workspace")
  1418. detail = task_state(auth, flaky)
  1419. check(any("restored the session context" in p["summary"]
  1420. for p in detail.get("progress", [])),
  1421. "daemon resume reported on the first status after the restore")
  1422. check(len(detail["progress"]) > progress_before,
  1423. "resume note appended to the progress timeline")
  1424. # Manual resume: a task stuck working on an offline saddle.
  1425. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1426. "project_id": "1",
  1427. "title": "Stuck task",
  1428. "priority": "2",
  1429. })
  1430. stuck = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1431. if t["title"] == "Stuck task"][0])
  1432. check(wait_for(lambda: task_state(auth, stuck).get("status") == "working" or False,
  1433. timeout=60, what="stuck task starts working") is not None,
  1434. "stuck task reaches working")
  1435. conn = db()
  1436. conn.execute("update saddles set status = 'offline' where name = 'fake-saddle'")
  1437. conn.commit()
  1438. conn.close()
  1439. detail = task_state(auth, stuck)
  1440. check(detail.get("resume_available") is True,
  1441. "task page offers resume while its saddle is offline")
  1442. act(auth, detail["resume"], {})
  1443. detail = task_state(auth, stuck)
  1444. check(detail["status"] == "queued",
  1445. "manual resume requeues the stuck task")
  1446. check(any(c["body"] == "Saddle became unreachable; task requeued"
  1447. for c in detail["comments"]),
  1448. "manual resume lands the interruption comment")
  1449. check(all(s["status"] == "offline"
  1450. for s in slot_public(auth, "/saddles", "saddles")["saddles"]),
  1451. "saddle stays offline after the manual requeue")
  1452. # Bringing the saddle back lets the requeued task resume and finish.
  1453. fake.state = "idle"
  1454. fake_card = saddle_card("fake-saddle")
  1455. act(auth, fake_card["refresh"], {})
  1456. check(any(s["status"] == "idle"
  1457. for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1458. if s["name"] == "fake-saddle"),
  1459. "refreshed saddle returns idle")
  1460. # The refreshed daemon is idle-awake: it asks (the real loop's
  1461. # own ask; driven directly for determinism).
  1462. status, _ = fake.ask_now()
  1463. check(status == 200, "the refreshed daemon's ask claims the requeued task")
  1464. check(wait_task_done(auth, stuck, timeout=60) is not None,
  1465. "requeued task resumes on the refreshed saddle and completes")
  1466. print("== rejected entries (non-fatal) ==")
  1467. # Ingest API: a rejected entry stores on the session and streams
  1468. # through SSE; the task is untouched.
  1469. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1470. {"type": "output", "session_id": session_id, "data": {
  1471. "command": "bash -n script.sh",
  1472. "output": "syntax error near line 3 (recoverable)",
  1473. "exit_code": 1,
  1474. "type": "rejected"}})
  1475. check(status == 200, "rejected entry accepted by the ingest API")
  1476. request = urllib.request.Request(WEB + "/terminal-stream/%d" % session_id)
  1477. with urllib.request.urlopen(request, timeout=15) as stream:
  1478. rejected_event = None
  1479. deadline = time.monotonic() + 8
  1480. while time.monotonic() < deadline and rejected_event is None:
  1481. line = stream.readline().decode().strip()
  1482. if not line.startswith("data: ") or line == "data: ping":
  1483. continue
  1484. event = json.loads(line[6:])
  1485. if event.get("type") == "rejected":
  1486. rejected_event = event
  1487. check(rejected_event is not None
  1488. and "syntax error near line 3" in (rejected_event.get("output") or ""),
  1489. "terminal stream carries rejected entries with their reason")
  1490. # The page template renders them with the distinct non-fatal style.
  1491. status, page = http("GET", "/tasks/%d/terminal" % stuck, timeout=15)
  1492. check(status == 200 and "term-rejected" in page,
  1493. "terminal page renders rejected entries in their own style")
  1494. print("== B8: ANSI SGR in the terminal view ==")
  1495. # Byte-exact SGR delivery: the daemon's coloured chunks flow through
  1496. # the store + SSE untouched (the client renderer styles them).
  1497. coloured = "\x1b[1;32mbold green\x1b[0m then \x1b[38;5;196m256-red\x1b[0m\n"
  1498. conn = db()
  1499. conn.execute("insert into session_raw_log (session_id, seq, chunk)"
  1500. " values (?, 900, ?)", (session_id, coloured))
  1501. conn.commit()
  1502. conn.close()
  1503. request = urllib.request.Request(WEB + "/terminal-stream/%d" % session_id)
  1504. with urllib.request.urlopen(request, timeout=15) as stream:
  1505. coloured_event = None
  1506. deadline = time.monotonic() + 8
  1507. while time.monotonic() < deadline and coloured_event is None:
  1508. line = stream.readline().decode().strip()
  1509. if not line.startswith("data: ") or line == "data: ping":
  1510. continue
  1511. event = json.loads(line[6:])
  1512. if event.get("type") == "raw" and "\x1b[1;32m" in (event.get("text") or ""):
  1513. coloured_event = event
  1514. check(coloured_event is not None
  1515. and "\x1b[38;5;196m" in coloured_event["text"],
  1516. "SGR sequences stream byte-exact to the client renderer")
  1517. status, page = http("GET", "/tasks/%d/terminal" % stuck, timeout=15)
  1518. check(status == 200 and "makeAnsiRenderer" in page and "colour256" in page,
  1519. "terminal page embeds the ANSI renderer (SGR + 256-colour palette)")
  1520. # Dispatch path: a rejected entry in a round's results push flows
  1521. # into the audit trail without failing (or finishing) the task.
  1522. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1523. "project_id": "1",
  1524. "title": "Rejected ride",
  1525. "priority": "2",
  1526. })
  1527. rejected_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1528. if t["title"] == "Rejected ride"][0])
  1529. check(wait_for(lambda: task_state(auth, rejected_task).get("status") == "working"
  1530. or False, timeout=60, what="rejected-ride working") is not None,
  1531. "rejected-ride task reaches working")
  1532. fake.queue_output("rejected", "echo 'too long' | saddle",
  1533. "max_tokens exceeded (recoverable)")
  1534. check(wait_task_done(auth, rejected_task, timeout=60) is not None,
  1535. "task completes normally past rejected entries")
  1536. conn = db()
  1537. stored = conn.execute(
  1538. "select count(*) from session_commands sc join sessions s on s.id = sc.session_id"
  1539. " where s.task_id = ? and sc.type = 'rejected'", (rejected_task,)).fetchone()[0]
  1540. conn.close()
  1541. check(stored >= 1,
  1542. "rejected entries stored in the audit trail (%d rows)" % stored)
  1543. check(task_state(auth, rejected_task)["status"] == "done"
  1544. and "fake daemon finished" in (task_state(auth, rejected_task).get("summary") or ""),
  1545. "rejected entries never fail the task")
  1546. print("== B7: suspended state + per-subtask resume ==")
  1547. fake.suspend_on_title = "Suspend parent"
  1548. pushes_before = len(fake.start_payloads)
  1549. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1550. "project_id": "1",
  1551. "title": "Suspend parent",
  1552. "priority": "2",
  1553. })
  1554. parent7 = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1555. if t["title"] == "Suspend parent"][0])
  1556. check(wait_for(lambda: task_state(auth, parent7).get("status") == "suspended"
  1557. or False, timeout=60, what="parent parks as suspended") is not None,
  1558. "daemon 'suspended' state parks the task")
  1559. detail = task_state(auth, parent7)
  1560. check(detail.get("display") == "waiting on subtasks",
  1561. "suspended task displays as waiting on subtasks")
  1562. check(any(s["status"] == "idle"
  1563. for s in slot_public(auth, "/saddles", "saddles")["saddles"]),
  1564. "suspension frees the saddle")
  1565. first_push = fake.start_payloads[pushes_before]
  1566. check(first_push.get("subtasks") == [],
  1567. "the /start payload carries the subtasks array (empty here)")
  1568. # Two subtask events land while parked (staged, not dispatched):
  1569. # both must coalesce into one resume with a full report.
  1570. conn = db()
  1571. conn.execute("insert into tasks (project_id, title, status, priority, parent_task_id,"
  1572. " summary, completed_at, created_at) values (1, 'Child one', 'done', 5, ?,"
  1573. " 'built and verified the flange', strftime('%s','now','+1 second'),"
  1574. " strftime('%s','now'))", (parent7,))
  1575. conn.execute("insert into tasks (project_id, title, status, priority, parent_task_id,"
  1576. " summary, completed_at, created_at) values (1, 'Child two', 'failed', 5, ?,"
  1577. " 'the harness refused to start', strftime('%s','now','+1 second'),"
  1578. " strftime('%s','now'))", (parent7,))
  1579. conn.commit()
  1580. conn.close()
  1581. def parent_push_count():
  1582. return len([p for p in fake.start_payloads
  1583. if int(p.get("task", {}).get("id") or 0) == parent7])
  1584. check(wait_for(lambda: parent_push_count() >= 2 or False,
  1585. timeout=45, what="suspended parent resumes") is not None,
  1586. "subtask events resume the suspended parent")
  1587. parent_pushes = [p for p in fake.start_payloads
  1588. if int(p.get("task", {}).get("id") or 0) == parent7]
  1589. check(len(parent_pushes) >= 2,
  1590. "the parent's resume is a fresh /start for the same task")
  1591. resume_push = parent_pushes[-1]
  1592. notice = resume_push.get("resume_notice") or ""
  1593. check("Child one" in notice and "completed" in notice
  1594. and "built and verified the flange" in notice,
  1595. "resume notice reports the finished subtask with its summary")
  1596. check("Child two" in notice and "failed" in notice
  1597. and "the harness refused to start" in notice,
  1598. "coalesced: the second event rides the same resume notice")
  1599. subtask_entries = {(s["title"], s["status"]) for s in resume_push.get("subtasks", [])}
  1600. check(("Child one", "done") in subtask_entries
  1601. and ("Child two", "failed") in subtask_entries,
  1602. "subtasks array carries the children's states at dispatch time")
  1603. # The resumed arc surfaces on a /status read while the resumed
  1604. # round still runs — the operator's manual refresh in the push
  1605. # world.
  1606. act(auth, saddle_card("fake-saddle")["refresh"], {})
  1607. check(wait_task_done(auth, parent7, timeout=60) is not None,
  1608. "resumed parent completes")
  1609. detail = task_state(auth, parent7)
  1610. check(any("restored the session context" in p["summary"]
  1611. for p in detail.get("progress", [])),
  1612. "resumed flag reported on the first status after the restore")
  1613. print("== R3 B1: subtask status push ==")
  1614. # A parked (suspended) parent gives delivery a stable open session.
  1615. fake.suspend_on_title = "Push parent"
  1616. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1617. "project_id": "1",
  1618. "title": "Push parent",
  1619. "priority": "2",
  1620. })
  1621. push_parent = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1622. if t["title"] == "Push parent"][0])
  1623. check(wait_for(lambda: task_state(auth, push_parent).get("status") == "suspended"
  1624. or False, timeout=60, what="push parent parks") is not None,
  1625. "push parent parks with an open session")
  1626. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1627. "project_id": "1",
  1628. "title": "Push child",
  1629. "parent_task_id": str(push_parent),
  1630. })
  1631. push_child = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1632. if t["title"] == "Push child"][0])
  1633. def events_for(subtask_id):
  1634. return [e for e in fake.subtask_status_events
  1635. if int(e.get("subtask_id") or 0) == subtask_id]
  1636. check(wait_for(lambda: len(events_for(push_child)) > 0 or False,
  1637. timeout=30, what="queued subtask event") is not None,
  1638. "subtask creation pushes a queued status event")
  1639. first_event = events_for(push_child)[0]
  1640. check(int(first_event.get("parent_task_id") or 0) == push_parent
  1641. and first_event.get("title") == "Push child"
  1642. and first_event.get("status") in ("queued", "working"),
  1643. "status event carries parent id, title and a wire status (%s)"
  1644. % first_event.get("status"))
  1645. # Real lifecycle: the child dispatches (working) and completes (done
  1646. # with summary) — the parent's daemon hears every transition.
  1647. check(wait_for(lambda: any(e.get("status") == "done"
  1648. for e in events_for(push_child)) or False,
  1649. timeout=90, what="done subtask event") is not None,
  1650. "subtask completion pushes the done transition")
  1651. check(any(e.get("status") == "working" for e in events_for(push_child)),
  1652. "dispatch pushes a working status event")
  1653. # Best-effort retry: while the daemon 500s, events stay queued and
  1654. # land once it recovers. The parent's resumed run re-parks (the
  1655. # ask-flow resume races this section otherwise: its completion
  1656. # would close the parked session the events are delivered to).
  1657. fake.fail_subtask_status = True
  1658. fake.suspend_on_title = "Push parent"
  1659. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1660. "project_id": "1",
  1661. "title": "Push child two",
  1662. "parent_task_id": str(push_parent),
  1663. })
  1664. push_child_two = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1665. if t["title"] == "Push child two"][0])
  1666. time.sleep(7)
  1667. check(len(events_for(push_child_two)) == 0,
  1668. "failed pushes stay queued (no event delivered)")
  1669. fake.fail_subtask_status = False
  1670. check(wait_for(lambda: len(events_for(push_child_two)) > 0 or False,
  1671. timeout=30, what="retried subtask event") is not None,
  1672. "recovered pushes deliver on a later tick")
  1673. print("== R4 B1: synchronous subtask callback ==")
  1674. # Plan 10: the subtask callback is per-saddle-token authenticated.
  1675. r4_token = fake_token
  1676. # Parent with a live parked session (suspended) hosts the callback.
  1677. fake.suspend_on_title = "Callback parent"
  1678. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1679. "project_id": "1",
  1680. "title": "Callback parent",
  1681. "priority": "2",
  1682. })
  1683. cb_parent = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1684. if t["title"] == "Callback parent"][0])
  1685. check(wait_for(lambda: task_state(auth, cb_parent).get("status") == "suspended"
  1686. or False, timeout=60, what="callback parent parks") is not None,
  1687. "callback parent parks")
  1688. status, _ = saddle_api("POST", "/api/saddle/subtask", None,
  1689. {"parent_task_id": cb_parent, "title": "no token"})
  1690. check(status == 401, "subtask callback rejects a missing token")
  1691. anchor = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1692. if t["title"] == "Rules dispatch"][0])
  1693. status, body = saddle_api("POST", "/api/saddle/subtask", r4_token, {
  1694. "parent_task_id": cb_parent,
  1695. "title": "Wire the flange",
  1696. "description": "torque to spec",
  1697. "depends_on": [anchor],
  1698. "session_id": 1,
  1699. })
  1700. check(status == 200 and body.get("ok") is True and int(body.get("task_id") or 0) > 0,
  1701. "callback creates the subtask synchronously")
  1702. subtask_id = int(body.get("task_id"))
  1703. detail = task_state(auth, subtask_id)
  1704. check(detail["title"] == "Wire the flange" and int(detail["project_id"]) == 1
  1705. and int(detail["parent_task_id"]) == cb_parent,
  1706. "subtask row inherits the parent's project and linkage")
  1707. check(detail.get("task_branch") == task_state(auth, cb_parent).get("task_branch"),
  1708. "subtask shares the parent's task branch")
  1709. conn = db()
  1710. dep_rows = conn.execute(
  1711. "select depends_on_task_id from task_dependencies where task_id = ?",
  1712. (subtask_id,)).fetchall()
  1713. conn.close()
  1714. check([r[0] for r in dep_rows] == [anchor],
  1715. "depends_on wired as task_dependencies")
  1716. # Idempotency + entry-poll fallback dedup.
  1717. status, body2 = saddle_api("POST", "/api/saddle/subtask", r4_token, {
  1718. "parent_task_id": cb_parent, "title": "Wire the flange"})
  1719. check(status == 200 and int(body2.get("task_id") or 0) == subtask_id,
  1720. "retried callback returns the same task id")
  1721. conn = db()
  1722. before = conn.execute("select count(*) from tasks where parent_task_id = ?",
  1723. (cb_parent,)).fetchone()[0]
  1724. conn.close()
  1725. conn = db()
  1726. cb_session = conn.execute(
  1727. "select id from sessions where task_id = ? and ended_at is null",
  1728. (cb_parent,)).fetchone()[0]
  1729. conn.close()
  1730. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1731. {"type": "subtask", "session_id": cb_session, "data": {
  1732. "title": "Wire the flange", "description": "again"}})
  1733. conn = db()
  1734. after = conn.execute("select count(*) from tasks where parent_task_id = ?",
  1735. (cb_parent,)).fetchone()[0]
  1736. timeline = conn.execute(
  1737. "select count(*) from session_commands where session_id = ?"
  1738. " and type = 'subtask'", (cb_session,)).fetchone()[0]
  1739. conn.close()
  1740. check(after == before,
  1741. "entry-poll fallback dedupes against the callback's row")
  1742. check(timeline >= 1, "timeline entry recorded on the parent's session")
  1743. # Validation: unknown parent, unknown depends_on, ancestor cycle.
  1744. status, body = saddle_api("POST", "/api/saddle/subtask", r4_token,
  1745. {"parent_task_id": 99999, "title": "ghost"})
  1746. check(status == 400, "unknown parent rejected")
  1747. status, body = saddle_api("POST", "/api/saddle/subtask", r4_token,
  1748. {"parent_task_id": cb_parent, "title": "bad dep",
  1749. "depends_on": [99999]})
  1750. check(status == 400 and "unknown task" in body.get("error", ""),
  1751. "unknown depends_on id rejected with a clear error")
  1752. status, body = saddle_api("POST", "/api/saddle/subtask", r4_token,
  1753. {"parent_task_id": cb_parent, "title": "cycle dep",
  1754. "depends_on": [cb_parent]})
  1755. check(status == 400 and "cycle" in body.get("error", ""),
  1756. "depending on an ancestor rejected as a cycle")
  1757. print("== R4 B2: subtask auto-approve ==")
  1758. # Settle earlier stragglers first: the round-3/B1 suspended parents
  1759. # resume (a fresh /start) once their last subtask completes — those
  1760. # pushes would consume the one-shot suspend flag below.
  1761. check(wait_task_done(auth, push_parent, timeout=90) is not None
  1762. and wait_task_done(auth, push_child_two, timeout=90) is not None
  1763. and wait_task_done(auth, cb_parent, timeout=90) is not None,
  1764. "earlier suspended parents settle before the auto-approve run")
  1765. # Parent parks; its toggle then covers all descendants. Children are
  1766. # created with an unmet 'gpu' requirement so they stay queued (and
  1767. # untouched) until the requirement is lifted for the final-resume leg.
  1768. fake.suspend_on_title = "Auto parent"
  1769. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1770. "project_id": "1",
  1771. "title": "Auto parent",
  1772. "priority": "2",
  1773. })
  1774. auto_parent = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1775. if t["title"] == "Auto parent"][0])
  1776. check(wait_for(lambda: task_state(auth, auto_parent).get("status") == "suspended"
  1777. or False, timeout=60, what="auto parent parks") is not None,
  1778. "auto parent parks")
  1779. detail = task_state(auth, auto_parent)
  1780. check(detail.get("auto_approve") is False,
  1781. "auto-approve defaults to off")
  1782. act(auth, detail["toggle_auto_approve"], {})
  1783. check(task_state(auth, auto_parent).get("auto_approve") is True,
  1784. "toggle turns auto-approve on")
  1785. gpu_option = int([o["id"] for o in slot_public(auth, "/tasks", "tasks")["capability_options"]
  1786. if o["name"] == "gpu"][0])
  1787. status, body = saddle_api("POST", "/api/saddle/subtask", r4_token,
  1788. {"parent_task_id": auto_parent,
  1789. "title": "Auto child", "depends_on": []})
  1790. auto_child = int(body["task_id"])
  1791. status, body = saddle_api("POST", "/api/saddle/subtask", r4_token,
  1792. {"parent_task_id": auto_child, "title": "Auto grandchild"})
  1793. auto_grand = int(body["task_id"])
  1794. act(auth, task_state(auth, auto_child)["attach_capability"],
  1795. {"capability_id": str(gpu_option)})
  1796. act(auth, task_state(auth, auto_grand)["attach_capability"],
  1797. {"capability_id": str(gpu_option)})
  1798. # Transitive coverage: the GRANDCHILD's review is auto-answered
  1799. # (any ancestor set), answered-by 'auto', timeline entry recorded.
  1800. conn = db()
  1801. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  1802. " values (?, ?, strftime('%s','now'))", (auto_grand, fake_id))
  1803. conn.commit()
  1804. grand_session = conn.execute("select max(id) from sessions").fetchone()[0]
  1805. conn.close()
  1806. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1807. {"type": "review", "session_id": grand_session, "data": {
  1808. "summary": "the flange is wired"}})
  1809. grand_detail = task_state(auth, auto_grand)
  1810. grand_review = [b for b in grand_detail["blocks"] if b["block_type"] == "review"][0]
  1811. check(grand_review.get("answered") is True
  1812. and grand_review.get("answer") == "Auto-approved (subtask auto-approve is on)"
  1813. and grand_review.get("answered_by") == "auto",
  1814. "covered grandchild review auto-answered as 'auto'")
  1815. conn = db()
  1816. timeline_auto = conn.execute(
  1817. "select count(*) from session_commands where session_id = ?"
  1818. " and type = 'auto-approve'", (grand_session,)).fetchone()[0]
  1819. conn.close()
  1820. check(timeline_auto >= 1, "auto action visible in the timeline")
  1821. # Questions and RFCs still block for a human.
  1822. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1823. {"type": "block", "session_id": grand_session, "data": {
  1824. "question": "Which torque spec?", "type": "question"}})
  1825. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1826. {"type": "block", "session_id": grand_session, "data": {
  1827. "question": "RFC: approve the design", "type": "rfc",
  1828. "body": "# Design"}})
  1829. grand_detail = task_state(auth, auto_grand)
  1830. check(all(b.get("answered") is not True for b in grand_detail["blocks"]
  1831. if b["block_type"] in ("question", "rfc")),
  1832. "questions and RFCs are never auto-answered")
  1833. # The toggle covers DESCENDANTS only: the parent's own review waits.
  1834. conn = db()
  1835. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at,"
  1836. " outcome) values (?, ?, strftime('%s','now'), strftime('%s','now'),"
  1837. " 'done')", (auto_parent, fake_id))
  1838. conn.commit()
  1839. parent_session = conn.execute("select max(id) from sessions").fetchone()[0]
  1840. conn.close()
  1841. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1842. {"type": "review", "session_id": parent_session, "data": {
  1843. "summary": "the whole change"}})
  1844. parent_detail = task_state(auth, auto_parent)
  1845. parent_review = [b for b in parent_detail["blocks"] if b["block_type"] == "review"][0]
  1846. check(parent_review.get("answered") is not True,
  1847. "the top-level parent's own review is never auto-approved")
  1848. # All descendants terminal → the suspended parent resumes with the
  1849. # final-review instruction (lift the capability requirement first).
  1850. act(auth, task_state(auth, auto_child)["capabilities"][0]["detach"], {})
  1851. act(auth, task_state(auth, auto_grand)["capabilities"][0]["detach"], {})
  1852. def pushes_for(task_id):
  1853. return len([p for p in fake.start_payloads
  1854. if int(p.get("task", {}).get("id") or 0) == task_id])
  1855. before_pushes = pushes_for(auto_parent)
  1856. check(wait_for(lambda: pushes_for(auto_parent) > before_pushes or False,
  1857. timeout=90, what="auto parent resumes") is not None,
  1858. "terminal subtasks resume the suspended parent")
  1859. notice = ""
  1860. for p in fake.start_payloads:
  1861. if int(p.get("task", {}).get("id") or 0) == auto_parent:
  1862. notice = p.get("resume_notice") or ""
  1863. check("All subtasks are complete" in notice
  1864. and "ONE final review" in notice and "saddle review" in notice,
  1865. "resume notice ends with the final-review instruction")
  1866. print("== phase 1: ask/allocation — token auth + concurrent race ==")
  1867. # Plan 10 phase 1. Registration mints per-saddle tokens; the
  1868. # ask endpoint authenticates by them; concurrent asks race to
  1869. # exactly one winner through the allocation transaction.
  1870. status, _ = saddle_api("POST", "/api/saddle/next-task", None)
  1871. check(status == 401, "next-task rejects a missing token")
  1872. status, _ = saddle_api("POST", "/api/saddle/next-task", "saddle-bogus-token")
  1873. check(status == 401, "next-task rejects a wrong token")
  1874. status, body = saddle_api("POST", "/api/saddle/next-task", fake_token)
  1875. check(status == 204, "next-task answers 204 (nothing offerable — daemon sleeps)")
  1876. # Two more racers: real daemons on their own ports; fake2 reports
  1877. # its ssh key at /register so the key lands on the row directly.
  1878. fake2 = FakeSaddle()
  1879. fake2.ssh_public_key = "ssh-ed25519 AAAAFake2RacerKey saddle-2@fedora"
  1880. fake2.serve(port=free_port())
  1881. fake3 = FakeSaddle()
  1882. fake3.serve(port=free_port())
  1883. saddles_state = slot_public(auth, "/saddles", "saddles")
  1884. act(auth, saddles_state["register"], {"name": "racer-two",
  1885. "host": "127.0.0.1:%d" % fake2.port})
  1886. act(auth, saddles_state["register"], {"name": "racer-three",
  1887. "host": "127.0.0.1:%d" % fake3.port})
  1888. check(wait_for(lambda: len(fake2.register_log) > 0 and len(fake3.register_log) > 0
  1889. or False, timeout=15, what="racers registered") is not None,
  1890. "both racers received /register")
  1891. check(wait_for(lambda: "AAAAFake2RacerKey" in
  1892. [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1893. if s["name"] == "racer-two"][0].get("ssh_public_key", "") or False,
  1894. timeout=15, what="register-reported key") is not None,
  1895. "the ssh key reported at /register lands on the saddle row")
  1896. racer_cards = {}
  1897. for name, daemon in (("fake-saddle", fake), ("racer-two", fake2), ("racer-three", fake3)):
  1898. card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1899. if s["name"] == name][0]
  1900. racer_cards[daemon] = {"id": int(card["id"]), "token": card["token"]}
  1901. # Revocation: a registered saddle's token works until the saddle
  1902. # is removed, then nothing authorises its calls.
  1903. fake4 = FakeSaddle()
  1904. fake4.ask_on_register = False # a pre-flip daemon: never asks
  1905. fake4.serve(port=free_port())
  1906. saddles_state = slot_public(auth, "/saddles", "saddles")
  1907. act(auth, saddles_state["register"], {"name": "old-daemon",
  1908. "host": "127.0.0.1:%d" % fake4.port})
  1909. old_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1910. if s["name"] == "old-daemon"][0]
  1911. status, _ = saddle_api("POST", "/api/saddle/next-task", old_card["token"])
  1912. check(status in (200, 204),
  1913. "the old daemon's fresh token authenticates next-task")
  1914. status, _ = saddle_api("POST", "/api/saddle/note", old_card["token"],
  1915. {"project": "demo", "body": "from the old daemon"})
  1916. check(status == 200, "note accepts any registered saddle's token")
  1917. act(auth, old_card["unregister"], {})
  1918. status, _ = saddle_api("POST", "/api/saddle/next-task", old_card["token"])
  1919. check(status == 401, "removing the saddle revokes its token")
  1920. status, _ = saddle_api("POST", "/api/saddle/note", old_card["token"],
  1921. {"project": "demo", "body": "should fail"})
  1922. check(status == 401, "revocation covers the note endpoint too")
  1923. # Deterministic race: settle the queue first (the auto-approve
  1924. # stragglers must finish — their parked resumes stay offerable
  1925. # otherwise and would steal the race's asks), freeze every
  1926. # daemon's self-ask triggers, put all three to sleep (204),
  1927. # then fire one task worth of concurrent asks.
  1928. check(wait_task_done(auth, auto_child, timeout=90) is not None
  1929. and wait_task_done(auth, auto_grand, timeout=90) is not None
  1930. and wait_task_done(auth, auto_parent, timeout=90) is not None,
  1931. "the auto-approve stragglers settle before the race")
  1932. for daemon in (fake, fake2, fake3):
  1933. daemon.ask_on_register = False
  1934. daemon.ask_on_wake = False
  1935. daemon.ask_on_terminal = False
  1936. daemon.ask_on_idle_status = False
  1937. time.sleep(1.5) # let any in-flight triggered asks land
  1938. def queued_count():
  1939. conn = db()
  1940. try:
  1941. return conn.execute(
  1942. "select count(*) from tasks where status = 'queued'").fetchone()[0]
  1943. finally:
  1944. conn.close()
  1945. check(wait_for(lambda: queued_count() == 0 or False,
  1946. timeout=60, what="queue settles before the race") is not None,
  1947. "the queue settles before the race")
  1948. sleep_statuses = [daemon.ask_now()[0] for daemon in (fake, fake2, fake3)]
  1949. check(sleep_statuses == [204, 204, 204],
  1950. "all three racers sleep (204) before the task exists")
  1951. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1952. "project_id": "1",
  1953. "title": "Race task",
  1954. "priority": "2",
  1955. })
  1956. race_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1957. if t["title"] == "Race task"][0])
  1958. race_results = []
  1959. def race_ask(daemon):
  1960. # A real racing daemon accepts the assignment it wins — the
  1961. # manual ask path does exactly that on a 200.
  1962. race_results.append(daemon.ask_now())
  1963. threads = [threading.Thread(target=race_ask, args=(daemon,))
  1964. for daemon in (fake, fake2, fake3)]
  1965. for thread in threads:
  1966. thread.start()
  1967. for thread in threads:
  1968. thread.join()
  1969. race_statuses = sorted(r[0] for r in race_results)
  1970. check(race_statuses == [200, 204, 204],
  1971. "concurrent asks race to exactly one winner (%s)" % race_statuses)
  1972. winner = [r for r in race_results if r[0] == 200][0][1]
  1973. check(int(winner["task"]["id"]) == race_task, "the winner's payload carries the task")
  1974. check(int(winner["session_id"]) > 0, "the assignment carries the session id")
  1975. conn = db()
  1976. race_sessions = conn.execute(
  1977. "select count(*) from sessions where task_id = ?", (race_task,)).fetchone()[0]
  1978. conn.close()
  1979. check(race_sessions == 1,
  1980. "exactly one session row — the transaction serialised the claims (%d)"
  1981. % race_sessions)
  1982. check(wait_task_done(auth, race_task, timeout=60) is not None,
  1983. "the raced task completes on the winning daemon")
  1984. for daemon in (fake, fake2, fake3):
  1985. daemon.ask_on_register = True
  1986. daemon.ask_on_wake = True
  1987. daemon.ask_on_terminal = True
  1988. daemon.ask_on_idle_status = True
  1989. # Re-establish sleeping explicitly: the winner's post-race
  1990. # re-ask timing is not deterministic, and the affinity section
  1991. # below needs every racer provably asleep. Any stray offerable
  1992. # drains into these asks first.
  1993. def all_asleep():
  1994. return all(daemon.ask_now()[0] == 204 for daemon in (fake, fake2, fake3))
  1995. check(wait_for(lambda: all_asleep() or False, timeout=30,
  1996. what="racers re-sleep after the race") is not None,
  1997. "all racers re-sleep after the race")
  1998. print("== phase 1: workspace affinity pins parked tasks ==")
  1999. # A suspended parent parked on racer-two may be resumed ONLY by
  2000. # racer-two: a tag-capable non-affine saddle asking gets 204, and
  2001. # the wake targets the affine saddle. Only racer-two carries the
  2002. # tag at dispatch time (the race's winner is nondeterministic, so
  2003. # the park must not depend on which racers are free); racer-three
  2004. # gains it afterwards to prove the pinning is by workspace, not
  2005. # tags.
  2006. saddles_state = slot_public(auth, "/saddles", "saddles")
  2007. act(auth, saddles_state["create_capability"], {"name": "affinity-tag"})
  2008. affinity_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  2009. if c["name"] == "affinity-tag"][0])
  2010. racer2_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2011. if s["name"] == "racer-two"][0]
  2012. racer3_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2013. if s["name"] == "racer-three"][0]
  2014. act(auth, racer2_card["attach_capability"], {"capability_id": str(affinity_cap)})
  2015. fake2.suspend_on_title = "Affinity parent"
  2016. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2017. "project_id": "1",
  2018. "title": "Affinity parent",
  2019. "priority": "2",
  2020. "capability_id": [str(affinity_cap)],
  2021. })
  2022. affinity_parent = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2023. if t["title"] == "Affinity parent"][0])
  2024. check(wait_for(lambda: task_state(auth, affinity_parent).get("status") == "suspended"
  2025. or False, timeout=60, what="affinity parent parks") is not None,
  2026. "affinity parent parks (suspended) on the tag-carrying racer")
  2027. conn = db()
  2028. affinity_session = conn.execute(
  2029. "select saddle_id from sessions where task_id = ? and ended_at is null",
  2030. (affinity_parent,)).fetchone()[0]
  2031. conn.close()
  2032. check(affinity_session == int(racer2_card["id"]),
  2033. "the parked workspace sits on racer-two (the only tag-carrier)")
  2034. # Now racer-three carries the tag too — the pinning is by
  2035. # workspace, not tags.
  2036. # A terminal subtask makes the parked task resume-offerable —
  2037. # affine to racer-two only. The park is observed the moment the
  2038. # suspended push lands (no poller lag to compensate), so the
  2039. # child is inserted only after racer-two's ask triggers are
  2040. # frozen and the wake measurement armed — its completion stamped
  2041. # one second ahead so completed_at > suspended_at holds.
  2042. fake2.ask_on_wake = False
  2043. fake2.ask_on_idle_status = False
  2044. wakes_before_2 = len(fake2.wake_log)
  2045. time.sleep(1.2) # any in-flight park-time trigger ask lands (204)
  2046. conn = db()
  2047. conn.execute("insert into tasks (project_id, title, status, priority, parent_task_id,"
  2048. " summary, completed_at, created_at) values (1, 'Affinity child', 'done',"
  2049. " 5, ?, 'affinity child finished', strftime('%s','now','+1 second'),"
  2050. " strftime('%s','now'))", (affinity_parent,))
  2051. conn.commit()
  2052. conn.close()
  2053. act(auth, racer3_card["attach_capability"], {"capability_id": str(affinity_cap)})
  2054. status, _ = fake3.ask_now()
  2055. check(status == 204,
  2056. "a tag-capable non-affine saddle is refused the parked task (204)")
  2057. check(wait_for(lambda: len(fake2.wake_log) > wakes_before_2 or False,
  2058. timeout=30, what="affine wake") is not None,
  2059. "the dispatcher's wake targets the affine saddle")
  2060. status, resume_payload = fake2.ask_now()
  2061. fake2.ask_on_wake = True # restored whatever the claim returned
  2062. fake2.ask_on_idle_status = True
  2063. check(status == 200 and int(resume_payload["task"]["id"]) == affinity_parent,
  2064. "the affine saddle's ask claims the parked task")
  2065. check("Affinity child" in (resume_payload.get("resume_notice") or "")
  2066. and "affinity child finished" in (resume_payload.get("resume_notice") or ""),
  2067. "the resume assignment carries the subtask report notice")
  2068. check(wait_task_done(auth, affinity_parent, timeout=60) is not None,
  2069. "the resumed parent completes")
  2070. print("== phase 1: lost wake -> offline + re-wake of the next capable ==")
  2071. # racer-three sleeps through wakes (a daemon that died after its
  2072. # last 204): the guard window (SADDLE_LOST_WAKE_S=2) passes with
  2073. # no ask, the saddle goes offline, and the work moves to the
  2074. # next capable sleeping saddle.
  2075. fake3.ask_on_wake = False
  2076. fake3.ask_on_idle_status = False # sleeps through everything
  2077. saddles_state = slot_public(auth, "/saddles", "saddles")
  2078. act(auth, saddles_state["create_capability"], {"name": "lostwake"})
  2079. lostwake_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  2080. if c["name"] == "lostwake"][0])
  2081. racer3_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2082. if s["name"] == "racer-three"][0]
  2083. act(auth, racer3_card["attach_capability"], {"capability_id": str(lostwake_cap)})
  2084. # Racer-three must be asleep to be woken: park it with a manual
  2085. # 204 ask (nothing offerable for it — the task below is not
  2086. # created yet).
  2087. status, _ = fake3.ask_now()
  2088. check(status == 204, "racer-three sleeps before the lost-wake run")
  2089. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2090. "project_id": "1",
  2091. "title": "Lost wake task",
  2092. "priority": "2",
  2093. "capability_id": [str(lostwake_cap)],
  2094. })
  2095. lost_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2096. if t["title"] == "Lost wake task"][0])
  2097. check(wait_for(lambda: len(fake3.wake_log) > 0 or False,
  2098. timeout=30, what="wake sent to racer-three") is not None,
  2099. "the only capable sleeping saddle is woken")
  2100. check(wait_for(lambda: [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2101. if s["name"] == "racer-three"][0]["status"] == "offline"
  2102. or False, timeout=30, what="lost-wake -> offline") is not None,
  2103. "no ask after the wake: the saddle goes offline (lost-wake guard)")
  2104. check(task_state(auth, lost_task)["status"] == "queued",
  2105. "the task is untouched while its wake was pending")
  2106. # Re-wake the next capable: the healthy saddle gains the tag and
  2107. # picks the work up via its own wake -> ask -> allocate roundtrip.
  2108. fake_card = saddle_card("fake-saddle")
  2109. act(auth, fake_card["attach_capability"], {"capability_id": str(lostwake_cap)})
  2110. wakes_before = len(fake.wake_log)
  2111. check(wait_for(lambda: len(fake.wake_log) > wakes_before or False,
  2112. timeout=30, what="re-wake of the next capable") is not None,
  2113. "the next capable sleeping saddle is woken for the task")
  2114. check(wait_task_done(auth, lost_task, timeout=60) is not None,
  2115. "wake -> ask -> allocate: the task completes on the healthy saddle")
  2116. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == lost_task
  2117. for p in fake.start_payloads) or False,
  2118. timeout=10, what="lost task assignment captured") is not None,
  2119. "the re-woken saddle's ask produced the assignment")
  2120. fake3.ask_on_wake = True
  2121. fake3.ask_on_idle_status = True
  2122. print("== phase 3: capability context, catalogue, subtask tags ==")
  2123. # Assignment capability context (plan 10 phase 3): every
  2124. # assignment carries {saddle_tags: the allocated saddle's tags,
  2125. # fleet_tags: every tag name known across the fleet} — the
  2126. # daemon renders it into its system prompt. fake-saddle carries
  2127. # gpu + lostwake; the catalogue is affinity-tag, gpu, lostwake.
  2128. fake2.ask_on_register = False
  2129. fake2.ask_on_wake = False
  2130. fake2.ask_on_terminal = False
  2131. fake2.ask_on_idle_status = False
  2132. time.sleep(1.2) # any in-flight trigger asks land
  2133. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2134. "project_id": "1",
  2135. "title": "Capabilities context",
  2136. "priority": "2",
  2137. })
  2138. cap_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2139. if t["title"] == "Capabilities context"][0])
  2140. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == cap_task
  2141. for p in fake.start_payloads) or False,
  2142. timeout=60, what="capabilities-context task dispatched") is not None,
  2143. "the capabilities-context task dispatches")
  2144. cap_payload = [p for p in fake.start_payloads
  2145. if int(p.get("task", {}).get("id") or 0) == cap_task][-1]
  2146. context = cap_payload.get("capabilities") or {}
  2147. check(context.get("saddle_tags") == ["gpu", "lostwake"],
  2148. "assignment saddle_tags = the allocated saddle's tags (%s)"
  2149. % context.get("saddle_tags"))
  2150. check(context.get("fleet_tags") == ["affinity-tag", "gpu", "lostwake"],
  2151. "assignment fleet_tags = every tag name known across the fleet (%s)"
  2152. % context.get("fleet_tags"))
  2153. check(wait_task_done(auth, cap_task, timeout=60) is not None,
  2154. "capabilities-context task completes")
  2155. # GET /api/saddle/capabilities feeds the daemon's `saddle
  2156. # capabilities` CLI: per-saddle-token auth, tag order by name,
  2157. # each tag with the saddles carrying it (name order).
  2158. status, _ = saddle_api("GET", "/api/saddle/capabilities", None)
  2159. check(status == 401, "capabilities endpoint rejects a missing token")
  2160. status, body = saddle_api("GET", "/api/saddle/capabilities", "saddle-bogus")
  2161. check(status == 401, "capabilities endpoint rejects a wrong token")
  2162. status, body = saddle_api("GET", "/api/saddle/capabilities", fake_token)
  2163. catalogue = {t["name"]: t["saddles"] for t in body.get("tags", [])}
  2164. check(status == 200 and body.get("ok") is True
  2165. and [t["name"] for t in body.get("tags", [])]
  2166. == ["affinity-tag", "gpu", "lostwake"],
  2167. "catalogue lists every tag by name")
  2168. check(catalogue.get("gpu") == ["fake-saddle"]
  2169. and catalogue.get("affinity-tag") == ["racer-three", "racer-two"]
  2170. and catalogue.get("lostwake") == ["fake-saddle", "racer-three"],
  2171. "each tag names its carrying saddles in name order (%s)" % catalogue)
  2172. # Subtask capabilities (`saddle subtask --capability`): explicit
  2173. # only — never inherited — and validated against the operator
  2174. # tag set; unknown tags reject with the valid list in the error
  2175. # (the agent reads it verbatim in the CLI output).
  2176. conn = db()
  2177. tasks_before = conn.execute("select count(*) from tasks").fetchone()[0]
  2178. conn.close()
  2179. status, body = saddle_api("POST", "/api/saddle/subtask", r4_token, {
  2180. "parent_task_id": auto_parent, "title": "Bad tag subtask",
  2181. "capabilities": ["gpu", "warp-drive"]})
  2182. conn = db()
  2183. tasks_after = conn.execute("select count(*) from tasks").fetchone()[0]
  2184. conn.close()
  2185. check(status == 400 and tasks_after == tasks_before,
  2186. "an unknown capability tag rejects the subtask call")
  2187. error_text = body.get("error", "")
  2188. check("warp-drive" in error_text and "valid tags" in error_text
  2189. and "gpu" in error_text and "lostwake" in error_text,
  2190. "the rejection names the unknown tag and the valid list (%s)" % error_text)
  2191. status, _ = saddle_api("POST", "/api/saddle/subtask", r4_token, {
  2192. "parent_task_id": auto_parent, "title": "Bad shape subtask",
  2193. "capabilities": "gpu"})
  2194. check(status == 400, "a non-array capabilities member rejects")
  2195. # Explicit-only: a parent requiring 'lostwake' (the lost-wake
  2196. # task) gets a subtask tagged just 'gpu' — nothing inherited.
  2197. status, body = saddle_api("POST", "/api/saddle/subtask", r4_token, {
  2198. "parent_task_id": lost_task, "title": "Explicit tag subtask",
  2199. "capabilities": ["gpu"]})
  2200. check(status == 200 and body.get("ok") is True,
  2201. "a valid tag creates the subtask synchronously")
  2202. tagged_subtask = int(body["task_id"])
  2203. detail = task_state(auth, tagged_subtask)
  2204. check([c["name"] for c in detail.get("capabilities", [])] == ["gpu"],
  2205. "the subtask carries exactly the explicit tag (no inheritance)")
  2206. check([c["name"] for c in task_state(auth, lost_task).get("capabilities", [])]
  2207. == ["lostwake"],
  2208. "the parent keeps its own requirement")
  2209. conn = db()
  2210. tag_rows = conn.execute(
  2211. "select c.name from task_capabilities tc"
  2212. " join capabilities c on c.id = tc.capability_id"
  2213. " where tc.task_id = ?", (tagged_subtask,)).fetchall()
  2214. conn.close()
  2215. check([r[0] for r in tag_rows] == ["gpu"],
  2216. "the task_capabilities rows record the explicit tag")
  2217. # The queued subtask dispatches (gpu-carrier) and settles before
  2218. # the slow-wake run needs an empty queue.
  2219. check(wait_task_done(auth, tagged_subtask, timeout=90) is not None,
  2220. "the tagged subtask dispatches and completes")
  2221. print("== phase 3: task page — status on top, blocks newest-first ==")
  2222. detail = task_state(auth, plan_task)
  2223. block_ids = [int(b["id"]) for b in detail.get("blocks", [])]
  2224. check(len(block_ids) >= 3 and block_ids == sorted(block_ids, reverse=True),
  2225. "the blocks section orders newest-first via the sealed GET state (%s)"
  2226. % block_ids)
  2227. status, page = http("GET", "/tasks/%d" % plan_task, timeout=15)
  2228. check(status == 200 and "status-head" in page
  2229. and page.index("status-head") < page.index("<h3>Description</h3>")
  2230. and page.index("status-head") < page.index("<h3>Plan</h3>"),
  2231. "the status block sits at the very top of the task page")
  2232. print("== phase 3: dashboard — pinned blocks + activity timeline ==")
  2233. # Pinned OPEN blocking items as link-through cards, newest
  2234. # first; no inline answer forms (the card links to the task
  2235. # page). At this point: the auto-approve grandchild's question
  2236. # and RFC plus the parent's own review are all unanswered.
  2237. dash = slot_public(auth, "/", "dashboard")
  2238. pinned = dash.get("pinned", [])
  2239. pinned_ids = [int(b["id"]) for b in pinned]
  2240. check(len(pinned_ids) >= 3 and pinned_ids == sorted(pinned_ids, reverse=True),
  2241. "pinned open blocks order newest-first (%s)" % pinned_ids)
  2242. check({b["block_type"] for b in pinned} >= {"question", "rfc", "review"},
  2243. "pinned cards cover questions, RFCs and reviews")
  2244. check(all(b["question"] and b["task_title"] and int(b["task_id"]) > 0
  2245. for b in pinned)
  2246. and all("answer_action" not in b for b in pinned),
  2247. "pinned cards are link-through only (task title, kind badge, question)")
  2248. # The activity timeline: last <= 50 events, newest first, fed
  2249. # from the existing tables. Fixture rows a few seconds old
  2250. # guarantee the progress kind and a human-authored comment ride
  2251. # along; the probe block below proves same-source ordering.
  2252. conn = db()
  2253. conn.execute("insert into task_comments (task_id, author, body, created_at)"
  2254. " values (?, 'user:admin', 'timeline fixture comment by a human',"
  2255. " strftime('%s','now','-5 seconds'))", (cap_task,))
  2256. conn.execute("insert into task_progress (task_id, summary, created_at)"
  2257. " values (?, 'timeline fixture progress',"
  2258. " strftime('%s','now','-5 seconds'))",
  2259. (cap_task,))
  2260. conn.commit()
  2261. conn.close()
  2262. dash = slot_public(auth, "/", "dashboard")
  2263. activity = dash.get("activity", [])
  2264. epochs = [int(e["at_epoch"]) for e in activity]
  2265. check(0 < len(activity) <= 50 and epochs == sorted(epochs, reverse=True),
  2266. "the timeline shows the last <=50 events newest-first (%d events)"
  2267. % len(activity))
  2268. kinds = {e["kind"] for e in activity}
  2269. check({"created", "started", "dispatch", "comment", "progress", "completed"} <= kinds,
  2270. "the timeline covers status changes, dispatches, comments, progress and"
  2271. " completions (%s)" % sorted(kinds))
  2272. check(any(e["kind"] == "comment" and e["text"].startswith("user:admin:")
  2273. and "fixture comment" in e["text"] for e in activity),
  2274. "comment events carry author + snippet")
  2275. # A freshly raised block pins immediately (newest card) and
  2276. # lands in the timeline as block-raised; answering it records
  2277. # block-answered.
  2278. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  2279. {"type": "block", "session_id": grand_session, "data": {
  2280. "question": "Timeline probe: approve the dashboard flow",
  2281. "type": "rfc", "body": "# Probe"}})
  2282. dash = slot_public(auth, "/", "dashboard")
  2283. check(dash["pinned"][0]["question"] == "Timeline probe: approve the dashboard flow"
  2284. and int(dash["pinned"][0]["task_id"]) == auto_grand,
  2285. "the freshest open block pins as the first card")
  2286. check(dash["activity"][0]["kind"] == "block-raised"
  2287. and "Timeline probe" in dash["activity"][0]["text"],
  2288. "the raised block lands atop the timeline")
  2289. probe_block = [b for b in task_state(auth, auto_grand)["blocks"]
  2290. if b["question"] == "Timeline probe: approve the dashboard flow"][0]
  2291. act(auth, probe_block["answer_action"], {"answer": "Ship the dashboard"})
  2292. dash = slot_public(auth, "/", "dashboard")
  2293. activity = dash.get("activity", [])
  2294. raised_at = next((i for i, e in enumerate(activity)
  2295. if e["kind"] == "block-raised" and "Timeline probe" in e["text"]), -1)
  2296. answered_at = next((i for i, e in enumerate(activity)
  2297. if e["kind"] == "block-answered"
  2298. and "Ship the dashboard" in e["text"]), -1)
  2299. check(answered_at >= 0 and raised_at >= 0 and answered_at < raised_at,
  2300. "the answered event sorts above its raised event (newest-first, same source)")
  2301. check(all(b["question"] != "Timeline probe: approve the dashboard flow"
  2302. for b in dash["pinned"]),
  2303. "the answered block leaves the pinned cards")
  2304. print("== phase 3 regression: a slow ask after a wake is never dropped ==")
  2305. # The daemon worker's lost-wake-guard regression: a saddle whose
  2306. # ask arrives SLOWLY after the wake (busy winding down when the
  2307. # wake lands) must not lose the wake — the delayed ask (inside
  2308. # the guard window) claims the task, no re-wake storm fires
  2309. # while it is pending, and the saddle stays healthy. The
  2310. # never-asks path (guard -> offline + re-wake of the next
  2311. # capable) is proven by the racer-three section above.
  2312. check(wait_for(lambda: queued_count() == 0 or False,
  2313. timeout=60, what="queue settles before the slow-wake run") is not None,
  2314. "the queue settles before the slow-wake run")
  2315. status, _ = fake2.ask_now()
  2316. check(status == 204, "the slow-ask racer sleeps before its wake")
  2317. saddles_state = slot_public(auth, "/saddles", "saddles")
  2318. act(auth, saddles_state["create_capability"], {"name": "slowwake"})
  2319. slowwake_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")
  2320. ["capabilities"] if c["name"] == "slowwake"][0])
  2321. racer2_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2322. if s["name"] == "racer-two"][0]
  2323. act(auth, racer2_card["attach_capability"], {"capability_id": str(slowwake_cap)})
  2324. fake2.ask_delay = 1.2 # slow: asks well after the wake, inside the 2s guard
  2325. fake2.ask_on_wake = True
  2326. wakes_before_slow = len(fake2.wake_log)
  2327. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2328. "project_id": "1",
  2329. "title": "Slow wake task",
  2330. "priority": "2",
  2331. "capability_id": [str(slowwake_cap)],
  2332. })
  2333. slow_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2334. if t["title"] == "Slow wake task"][0])
  2335. check(wait_for(lambda: len(fake2.wake_log) > wakes_before_slow or False,
  2336. timeout=30, what="the slow-ask racer woken") is not None,
  2337. "the only capable sleeping saddle is woken")
  2338. check(wait_task_done(auth, slow_task, timeout=120) is not None,
  2339. "the delayed ask claims the task — the wake was not dropped")
  2340. check(any(a.get("status") == 200
  2341. and int((a.get("payload") or {}).get("task", {}).get("id") or 0)
  2342. == slow_task for a in fake2.asks),
  2343. "the slow ask's 200 carries the task")
  2344. check(len(fake2.wake_log) == wakes_before_slow + 1,
  2345. "the pending-wake skip re-wakes nobody while the slow ask is in flight")
  2346. racer2_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2347. if s["name"] == "racer-two"][0]
  2348. check(racer2_card["status"] in ("idle", "busy"),
  2349. "the slow asker never went offline (guard did not fire)")
  2350. fake2.ask_delay = 0.0
  2351. fake2.ask_on_wake = False # stays out of the pool below
  2352. # The racers leave the dispatch pool: the remaining sections
  2353. # (rollback resume, R5-R11) predate multi-daemon routing and
  2354. # assert against the primary fake's payloads. racer-three is
  2355. # already offline (the lost-wake guard); racer-two joins it.
  2356. conn = db()
  2357. conn.execute("update saddles set status = 'offline' where name = 'racer-two'")
  2358. conn.commit()
  2359. conn.close()
  2360. # Tasks caught working on a saddle that went offline requeue with a
  2361. # bot comment each tick.
  2362. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2363. "project_id": "1",
  2364. "title": "Offline saddle task",
  2365. "priority": "2",
  2366. })
  2367. offline_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2368. if t["title"] == "Offline saddle task"][0])
  2369. check(wait_for(lambda: task_state(auth, offline_task).get("status") == "working"
  2370. or False, timeout=60, what="offline task starts working") is not None,
  2371. "task reaches working before its saddle disappears")
  2372. conn = db()
  2373. conn.execute("update saddles set status = 'offline' where name = 'fake-saddle'")
  2374. conn.commit()
  2375. conn.close()
  2376. # The requeue frees the saddle in the same tick, so 'queued' is
  2377. # transient; the durable evidence is the bot comment (and the task
  2378. # completing again on the healthy daemon).
  2379. check(wait_for(lambda: any(c["body"] == "saddle went offline; task requeued"
  2380. for c in task_state(auth, offline_task).get("comments", []))
  2381. or False, timeout=30, what="offline requeue comment") is not None,
  2382. "offline saddle requeues the task")
  2383. check(wait_task_done(auth, offline_task, timeout=60) is not None,
  2384. "requeued task completes again on the healthy daemon")
  2385. print("== R5 B1: /start parent context ==")
  2386. # A fresh subtask dispatch carries the parent object (plan clamped).
  2387. conn = db()
  2388. conn.execute("update tasks set plan = ? where id = ?",
  2389. ("# Parent plan\n\n" + "step. " * 1200, auto_parent))
  2390. conn.commit()
  2391. conn.close()
  2392. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2393. "project_id": "1",
  2394. "title": "Lineage subtask",
  2395. "priority": "3",
  2396. })
  2397. lineage_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2398. if t["title"] == "Lineage subtask"][0])
  2399. conn = db()
  2400. conn.execute("update tasks set parent_task_id = ?, description = 'torque to spec'"
  2401. " where id = ?", (auto_parent, lineage_task))
  2402. conn.commit()
  2403. conn.close()
  2404. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == lineage_task
  2405. for p in fake.start_payloads) or False,
  2406. timeout=60, what="lineage subtask dispatches") is not None,
  2407. "lineage subtask dispatches")
  2408. lineage_push = [p for p in fake.start_payloads
  2409. if int(p.get("task", {}).get("id") or 0) == lineage_task][-1]
  2410. parent_obj = lineage_push.get("parent")
  2411. check(parent_obj is not None
  2412. and int(parent_obj.get("id") or 0) == auto_parent
  2413. and parent_obj.get("title") == "Auto parent"
  2414. and parent_obj.get("status") in ("suspended", "working", "done"),
  2415. "subtask /start carries the parent object")
  2416. check(parent_obj.get("description") == "torque to spec"
  2417. or "Parent plan" in (parent_obj.get("plan") or ""),
  2418. "parent description/plan content flows through")
  2419. check(len(parent_obj.get("plan") or "") <= 4000,
  2420. "parent plan clamped to ~4000 chars (%d)"
  2421. % len(parent_obj.get("plan") or ""))
  2422. root_pushes = [p for p in fake.start_payloads
  2423. if int(p.get("task", {}).get("id") or 0) == offline_task]
  2424. check(all("parent" not in p for p in root_pushes),
  2425. "root task /start carries no parent object")
  2426. print("== R5 B2: task-reading API ==")
  2427. status, _ = saddle_api("GET", "/api/saddle/tasks", None)
  2428. check(status == 401, "tasks endpoint rejects a missing token")
  2429. status, _ = saddle_api("GET", "/api/saddle/task/%d" % auto_child, None)
  2430. check(status == 401, "task detail endpoint rejects a missing token")
  2431. status, body = saddle_api("GET", "/api/saddle/tasks", r4_token)
  2432. check(status == 200 and len(body.get("tasks", [])) > 5,
  2433. "tasks endpoint lists tasks without filters")
  2434. row = [t for t in body["tasks"] if int(t["id"]) == auto_child][0]
  2435. check(row["title"] == "Auto child" and int(row["parent_task_id"]) == auto_parent
  2436. and row["status"] in ("done", "queued", "working"),
  2437. "compact rows carry id/title/status/parent_task_id")
  2438. status, body = saddle_api("GET", "/api/saddle/tasks?project_id=1", r4_token)
  2439. other_project = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  2440. if p["name"] == "diff-fabrica"][0])
  2441. check(all(True for _ in [1]) # project 1 dominates the data set
  2442. and not any(int(t["id"]) == 0 for t in body["tasks"]),
  2443. "project_id filter accepted")
  2444. status, body = saddle_api("GET",
  2445. "/api/saddle/tasks?project_id=%d" % other_project, r4_token)
  2446. check(all(t["title"].startswith("Diff") for t in body["tasks"]),
  2447. "other project lists only its own tasks")
  2448. status, body = saddle_api("GET", "/api/saddle/tasks?q=FLANGE", r4_token)
  2449. titles = [t["title"] for t in body["tasks"]]
  2450. check("Wire the flange" in titles,
  2451. "q matches titles case-insensitively")
  2452. status, body = saddle_api("GET", "/api/saddle/tasks?q=torque%20to%20spec", r4_token)
  2453. check(any(t["title"] == "Lineage subtask" for t in body["tasks"]),
  2454. "q matches description text")
  2455. status, body = saddle_api("GET", "/api/saddle/tasks?q=parent%20plan", r4_token)
  2456. check(any(t["title"] == "Auto parent" for t in body["tasks"]),
  2457. "q matches plan text")
  2458. status, body = saddle_api("GET", "/api/saddle/task/%d" % auto_child, r4_token)
  2459. task_view = body.get("task", {})
  2460. check(status == 200 and int(task_view.get("id") or 0) == auto_child
  2461. and task_view.get("parent_title") == "Auto parent"
  2462. and int(task_view.get("parent_task_id") or 0) == auto_parent,
  2463. "single-task view joins the parent title")
  2464. check("status" in task_view and "description" in task_view
  2465. and "plan" in task_view and "summary" in task_view,
  2466. "single-task view carries the full detail fields")
  2467. status, body = saddle_api("GET", "/api/saddle/task/99999", r4_token)
  2468. check(status == 404, "unknown task id returns 404")
  2469. print("== R6 F1: a hanging request cannot freeze the tick ==")
  2470. # One wedged /task-update (never responds) blocks the comment/
  2471. # subtask-event delivery pass; the Soup timeout must fail it and
  2472. # later ticks keep dispatching.
  2473. task_state(auth, lineage_task)
  2474. conn = db()
  2475. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  2476. " values (1, 'Hang survivor', 'queued', 2, strftime('%s','now'))")
  2477. hang_task = conn.execute("select max(id) from tasks").fetchone()[0]
  2478. conn.close()
  2479. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2480. "project_id": "1",
  2481. "title": "Hang runner",
  2482. "priority": "3",
  2483. })
  2484. hang_runner = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2485. if t["title"] == "Hang runner"][0])
  2486. # A human comment on the running task gives the tick a
  2487. # /task-update delivery to make; the next one hangs.
  2488. check(wait_for(lambda: task_state(auth, hang_runner).get("status") == "working"
  2489. or False, timeout=60, what="hang runner working") is not None,
  2490. "hang runner reaches working")
  2491. act(auth, task_state(auth, hang_runner)["comment"],
  2492. {"body": "operator ping while wedged"})
  2493. fake.hang_next["/task-update"] = 1
  2494. check(wait_task_done(auth, hang_runner, timeout=90) is not None,
  2495. "dispatching task survives a hung daemon request")
  2496. check(wait_for(lambda: any(c.get("text") == "operator ping while wedged"
  2497. or c.get("body") == "operator ping while wedged"
  2498. for c in fake.comment_log) or False,
  2499. timeout=30, what="wedged comment eventually delivered") is not None,
  2500. "the comment delivery retries after the hang")
  2501. # The hung delivery itself fails after the timeout; the system
  2502. # kept moving either way.
  2503. with open(os.path.join(WORK, "app.log")) as handle:
  2504. app_log = handle.read()
  2505. check("tick exceeded" not in app_log or "Dispatch tick failed" in app_log,
  2506. "a hung request never freezes the tick latch")
  2507. print("== R6 F2: refresh must not corrupt parked bookkeeping ==")
  2508. fake.suspend_on_title = "Parked refresh parent"
  2509. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2510. "project_id": "1",
  2511. "title": "Parked refresh parent",
  2512. "priority": "2",
  2513. })
  2514. parked = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2515. if t["title"] == "Parked refresh parent"][0])
  2516. check(wait_for(lambda: task_state(auth, parked).get("status") == "suspended"
  2517. or False, timeout=60, what="parked parent suspends") is not None,
  2518. "parent parks before the refresh")
  2519. fake_card = saddle_card("fake-saddle")
  2520. act(auth, fake_card["refresh"], {})
  2521. fake_card = saddle_card("fake-saddle")
  2522. check(fake_card["status"] == "idle" and int(fake_card["current_task_id"] or 0) == 0,
  2523. "refresh on a parked (suspended) daemon leaves the saddle idle")
  2524. # The parked task keeps its open session and resumes normally.
  2525. conn = db()
  2526. conn.execute("insert into tasks (project_id, title, status, priority, parent_task_id,"
  2527. " summary, completed_at, created_at) values (1, 'Parked child', 'done', 5,"
  2528. " ?, 'child finished', strftime('%s','now','+1 second'),"
  2529. " strftime('%s','now'))", (parked,))
  2530. conn.commit()
  2531. conn.close()
  2532. check(wait_task_done(auth, parked, timeout=90) is not None,
  2533. "parked parent still resumes after the refresh")
  2534. print("== R7 B1: cancel reaches the daemon ==")
  2535. # Plan 10 phase 2: cancellation is POST /task-update {kind: cancel}
  2536. # to the RUNNING daemon (the abort machinery, workspace kept).
  2537. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2538. "project_id": "1",
  2539. "title": "Cancel live",
  2540. "priority": "2",
  2541. })
  2542. cancel_live = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2543. if t["title"] == "Cancel live"][0])
  2544. check(wait_for(lambda: task_state(auth, cancel_live).get("status") == "working"
  2545. or False, timeout=60, what="cancel-live working") is not None,
  2546. "task reaches working before the cancel")
  2547. act(auth, task_state(auth, cancel_live)["cancel"], {})
  2548. check(wait_for(lambda: cancel_live in fake.abort_log or False,
  2549. timeout=30, what="daemon abort recorded") is not None,
  2550. "cancelling POSTs task-update cancel to the daemon")
  2551. check(any(c["body"] == "cancelled; daemon aborted"
  2552. for c in task_state(auth, cancel_live).get("comments", [])),
  2553. "the abort outcome is narrated")
  2554. check(task_state(auth, cancel_live)["status"] == "failed",
  2555. "cancelled task lands failed as before")
  2556. # A 500 on the cancel marks the saddle offline (no fence layer
  2557. # anymore); nothing dispatches to it while offline, and the
  2558. # daemon's own ask flips the row back to idle (proof of life).
  2559. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2560. "project_id": "1",
  2561. "title": "Fence runner",
  2562. "priority": "2",
  2563. })
  2564. fence_runner = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2565. if t["title"] == "Fence runner"][0])
  2566. check(wait_for(lambda: task_state(auth, fence_runner).get("status") == "working"
  2567. or False, timeout=60, what="fence runner working") is not None,
  2568. "second task reaches working")
  2569. fake.abort_failures = 1
  2570. act(auth, task_state(auth, fence_runner)["cancel"], {})
  2571. check(any(c["body"] == "cancelled; daemon unreachable — saddle marked offline"
  2572. for c in task_state(auth, fence_runner).get("comments", [])),
  2573. "failed cancel narrates the offline marking")
  2574. check(saddle_card("fake-saddle")["status"] == "offline",
  2575. "saddle marked offline after the failed cancel")
  2576. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2577. "project_id": "1",
  2578. "title": "During fence",
  2579. "priority": "3",
  2580. })
  2581. during_fence = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2582. if t["title"] == "During fence"][0])
  2583. time.sleep(7)
  2584. check(task_state(auth, during_fence)["status"] == "queued",
  2585. "offline saddle is not dispatchable")
  2586. # The (unaborted) daemon finishes its round, goes idle-awake and
  2587. # asks — the ask is the proof of life that flips the row back.
  2588. check(wait_for(lambda: saddle_card("fake-saddle")["status"] == "idle" or False,
  2589. timeout=30, what="ask flips offline to idle") is not None,
  2590. "the daemon's ask flips the offline row back to idle")
  2591. check(wait_task_done(auth, during_fence, timeout=60) is not None,
  2592. "queued work dispatches once the saddle proves it is alive")
  2593. print("== R7 B3: health panel + pushed raw log from the first round ==")
  2594. # A normally dispatched task pushes its chunks immediately: raw
  2595. # rows exist from the first round (the session-4 gap stays
  2596. # fixed without any probe machinery).
  2597. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2598. "project_id": "1",
  2599. "title": "Raw from first push",
  2600. "priority": "2",
  2601. })
  2602. raw_first = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2603. if t["title"] == "Raw from first push"][0])
  2604. def raw_count(task_id):
  2605. conn = db()
  2606. try:
  2607. return conn.execute(
  2608. "select count(*) from session_raw_log where session_id in"
  2609. " (select id from sessions where task_id = ?)", (task_id,)).fetchone()[0]
  2610. finally:
  2611. conn.close()
  2612. check(wait_for(lambda: raw_count(raw_first) > 0 or False,
  2613. timeout=60, what="raw rows from first push") is not None,
  2614. "pushed chunks land from the first round (session-4 gap)")
  2615. check(wait_task_done(auth, raw_first, timeout=60) is not None,
  2616. "raw-first task completes")
  2617. # Health panel: a manual refresh populates the snapshot.
  2618. fake_card = saddle_card("fake-saddle")
  2619. act(auth, fake_card["refresh"], {})
  2620. card = saddle_card("fake-saddle")
  2621. check(card.get("health") in ("healthy", "stale")
  2622. and card.get("daemon_state") in ("working", "idle", "done")
  2623. and card.get("uptime_display", "") != ""
  2624. and card.get("last_contact_display", "") not in ("", "never"),
  2625. "saddles page shows daemon state, uptime and last contact")
  2626. print("== R8: pushed chunk ingestion is lossless ==")
  2627. # The daemon's opening flush: a coloured prompt run, plain text,
  2628. # a bare CRLF between prompts and the tail — every non-empty
  2629. # chunk must land, exactly once, in seq order. A mid-flight
  2630. # redelivery of the whole batch (the outbox's at-least-once
  2631. # retry) consumes the duplicates.
  2632. corpus = [
  2633. {"seq": 1, "text": "\x1b[01;32muser@host\x1b[00m:\x1b[01;34m~/task-1\x1b[00m$ "},
  2634. {"seq": 2, "text": "echo hello\r\n"},
  2635. {"seq": 3, "text": "\r\n"},
  2636. {"seq": 4, "text": "hello\r\n"},
  2637. {"seq": 5, "text": "\x1b[01;32muser@host\x1b[00m:\x1b[01;34m~/task-1\x1b[00m$ "},
  2638. {"seq": 6, "text": "done\r\n"},
  2639. ]
  2640. fake.scripted_corpus = corpus
  2641. fake.hold_state = True
  2642. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2643. "project_id": "1",
  2644. "title": "Lossless log task",
  2645. "priority": "2",
  2646. })
  2647. lossless = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2648. if t["title"] == "Lossless log task"][0])
  2649. def stored_seqs(task_id):
  2650. conn = db()
  2651. try:
  2652. return [r[0] for r in conn.execute(
  2653. "select seq from session_raw_log where session_id in"
  2654. " (select id from sessions where task_id = ?)"
  2655. " order by seq", (task_id,))]
  2656. finally:
  2657. conn.close()
  2658. check(wait_for(lambda: task_state(auth, lossless).get("status") == "working"
  2659. or False, timeout=60, what="lossless task working") is not None,
  2660. "lossless task dispatches and pushes its opening flush")
  2661. check(wait_for(lambda: stored_seqs(lossless) == [1, 2, 3, 4, 5, 6] or False,
  2662. timeout=30, what="all six chunks stored") is not None,
  2663. "every pushed chunk lands in session_raw_log, CRLF-only included (%s)"
  2664. % stored_seqs(lossless))
  2665. status, _ = saddle_api("POST", "/api/saddle/chunks", fake.token,
  2666. {"session_id": fake.session_id,
  2667. "chunks": [dict(chunk) for chunk in corpus]})
  2668. check(status == 200 and stored_seqs(lossless) == [1, 2, 3, 4, 5, 6],
  2669. "a full-batch redelivery stores nothing new (exactly-once)")
  2670. request = urllib.request.Request(
  2671. WEB + "/terminal-stream/%d" % [r[0] for r in db().execute(
  2672. "select id from sessions where task_id = ?", (lossless,))][0])
  2673. with urllib.request.urlopen(request, timeout=15) as stream:
  2674. texts = []
  2675. deadline = time.monotonic() + 8
  2676. while time.monotonic() < deadline and len(texts) < 6:
  2677. line = stream.readline().decode().strip()
  2678. if not line.startswith("data: ") or line == "data: ping":
  2679. continue
  2680. event = json.loads(line[6:])
  2681. if event.get("type") == "raw":
  2682. texts.append(event.get("text") or "")
  2683. check("\r\n" in texts and len(texts) == 6,
  2684. "SSE serves the whitespace chunk unfiltered")
  2685. fake.hold_state = False
  2686. fake.scripted_corpus = None
  2687. check(wait_task_done(auth, lossless, timeout=60) is not None,
  2688. "lossless task completes")
  2689. print("== R9 B1/B2: git identity + ssh key ==")
  2690. # The key travels on /status into the saddle row and the page view
  2691. # (the manual refresh's exceptional probe).
  2692. fake.ssh_public_key = "ssh-ed25519 AAAAC3NzaC1lZDI1teStKey saddle-1@fedora"
  2693. fake_card = saddle_card("fake-saddle")
  2694. check(fake_card.get("ssh_public_key", "") == "",
  2695. "no key shown before the daemon reports one")
  2696. act(auth, fake_card["refresh"], {})
  2697. check(wait_for(lambda: "AAAAC3NzaC1lZDI1teStKey" in
  2698. saddle_card("fake-saddle").get("ssh_public_key", "") or False,
  2699. timeout=30, what="key lands on the row") is not None,
  2700. "reported ssh_public_key persists onto the saddle row")
  2701. conn = db()
  2702. row_key = conn.execute("select ssh_public_key from saddles where name = 'fake-saddle'"
  2703. ).fetchone()[0]
  2704. conn.close()
  2705. check(row_key == fake.ssh_public_key,
  2706. "the key is stored verbatim in the database")
  2707. # Identity edit flows through the UI into the assignment payload.
  2708. fake_card = saddle_card("fake-saddle")
  2709. act(auth, fake_card["update_identity"],
  2710. {"git_name": "clanker-bot", "git_email": "bot@unitatem.net"})
  2711. fake_card = saddle_card("fake-saddle")
  2712. check(fake_card.get("git_name") == "clanker-bot"
  2713. and fake_card.get("git_email") == "bot@unitatem.net",
  2714. "inline edit saves the git identity")
  2715. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2716. "project_id": "1",
  2717. "title": "Identity task",
  2718. "priority": "2",
  2719. })
  2720. identity_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2721. if t["title"] == "Identity task"][0])
  2722. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == identity_task
  2723. for p in fake.start_payloads) or False,
  2724. timeout=60, what="identity task dispatched") is not None,
  2725. "identity task dispatches")
  2726. payload = [p for p in fake.start_payloads
  2727. if int(p.get("task", {}).get("id") or 0) == identity_task][-1]
  2728. identity = payload.get("git_identity") or {}
  2729. check(identity.get("name") == "clanker-bot"
  2730. and identity.get("email") == "bot@unitatem.net",
  2731. "the assignment carries the saddle's git_identity")
  2732. # Earlier assignments (identity unset) carry no git_identity member.
  2733. check(all("git_identity" not in p for p in fake.start_payloads[:-1]),
  2734. "unset identity omits the member (daemon fallback applies)")
  2735. # Clearing the identity omits it from later assignments.
  2736. fake_card = saddle_card("fake-saddle")
  2737. act(auth, fake_card["update_identity"], {"git_name": "", "git_email": ""})
  2738. check(saddle_card("fake-saddle").get("git_name", "") == "",
  2739. "clearing the identity empties the row")
  2740. check(wait_task_done(auth, identity_task, timeout=60) is not None,
  2741. "identity task completes")
  2742. print("== R10: branch_advanced on the /poll verdict channel ==")
  2743. conn = db()
  2744. conn.execute("insert into tasks (project_id, title, status, priority,"
  2745. " created_at) values (1, 'Poll grandparent', 'working', 5,"
  2746. " strftime('%s','now','-300 seconds'))")
  2747. poll_grand = conn.execute("select max(id) from tasks").fetchone()[0]
  2748. conn.execute("insert into tasks (project_id, title, status, priority,"
  2749. " parent_task_id, created_at) values (1, 'Poll answer parent',"
  2750. " 'blocked', 5, ?, strftime('%s','now','-120 seconds'))",
  2751. (poll_grand,))
  2752. poll_parent = conn.execute("select max(id) from tasks").fetchone()[0]
  2753. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  2754. " values (?, ?, strftime('%s','now','-120 seconds'))",
  2755. (poll_parent, fake_id))
  2756. conn.execute("insert into task_blocks (task_id, question, type, answer,"
  2757. " answered_at, created_at) values (?, 'Which DB?', 'question',"
  2758. " 'SQLite', strftime('%s','now','-60 seconds'),"
  2759. " strftime('%s','now','-100 seconds'))", (poll_parent,))
  2760. conn.execute("update saddles set status = 'busy', current_task_id = ?,"
  2761. " allocated_at = strftime('%s','now') where name = 'fake-saddle'",
  2762. (poll_parent,))
  2763. conn.commit()
  2764. conn.close()
  2765. status, body = saddle_api("GET", "/api/saddle/%d/poll" % fake_id, fake_token)
  2766. check(status == 200 and len(body.get("answers", [])) == 1
  2767. and body["answers"][0].get("branch_advanced") is False,
  2768. "/poll verdicts carry branch_advanced=false with no siblings")
  2769. # A sibling under the same parent completed after the park marker.
  2770. conn = db()
  2771. conn.execute("insert into tasks (project_id, title, status, priority,"
  2772. " parent_task_id, summary, completed_at, created_at)"
  2773. " values (1, 'Poll sibling', 'done', 5, ?, 'sibling finished',"
  2774. " strftime('%s','now'), strftime('%s','now','-200 seconds'))",
  2775. (poll_grand,))
  2776. conn.execute("insert into task_blocks (task_id, question, type, answer,"
  2777. " answered_at, created_at) values (?, 'Second question?',"
  2778. " 'question', 'Yes', strftime('%s','now'),"
  2779. " strftime('%s','now','-90 seconds'))", (poll_parent,))
  2780. conn.commit()
  2781. conn.close()
  2782. status, body = saddle_api("GET", "/api/saddle/%d/poll" % fake_id, fake_token)
  2783. check(status == 200 and len(body.get("answers", [])) == 1
  2784. and body["answers"][0].get("branch_advanced") is True,
  2785. "sibling completion after park flips branch_advanced to true")
  2786. # Release the staged fixture: cancel it so its busy@task row does
  2787. # not linger into the sections below.
  2788. act(auth, task_state(auth, poll_parent)["cancel"], {})
  2789. print("== phase 2: blocked push -> block row + pulse ==")
  2790. # The browser flow on each pulse: statum.act(task.refresh) — the
  2791. # sealed GET action must rehydrate the task slot with the new
  2792. # block the daemon just PUSHED (state blocked + block payload).
  2793. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2794. "project_id": "1",
  2795. "title": "Live block task",
  2796. "priority": "2",
  2797. })
  2798. live_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2799. if t["title"] == "Live block task"][0])
  2800. check(wait_for(lambda: task_state(auth, live_task).get("status") == "working"
  2801. or False, timeout=60, what="live task working") is not None,
  2802. "live-block task reaches working")
  2803. fake.hold_state = True
  2804. fake.state = "blocked" # the daemon parks on its question
  2805. status = fake.push_results("blocked", block={
  2806. "question": "Pick one", "type": "question", "options": ["A", "B"]})
  2807. check(status == 200, "blocked state push accepted")
  2808. # The parked daemon is idle-awake: it asks (and sleeps on 204).
  2809. fake.maybe_trigger_ask("parked")
  2810. check(wait_for(lambda: any(b.get("question") == "Pick one"
  2811. for b in task_state(auth, live_task).get("blocks", []))
  2812. or False, timeout=30, what="block lands in state") is not None,
  2813. "the pushed block reaches the sealed refresh without a reload")
  2814. detail = task_state(auth, live_task)
  2815. check(detail.get("status") == "blocked",
  2816. "the blocked push flips the task to blocked")
  2817. pushed_block = [b for b in detail["blocks"] if b.get("question") == "Pick one"][0]
  2818. conn = db()
  2819. options_json = conn.execute(
  2820. "select options from task_blocks where id = ?", (int(pushed_block["id"]),)
  2821. ).fetchone()[0]
  2822. conn.close()
  2823. check(json.loads(options_json) == ["A", "B"],
  2824. "the block row carries its options payload")
  2825. check(any(s["status"] == "idle"
  2826. for s in slot_public(auth, "/saddles", "saddles")["saddles"]),
  2827. "the blocked push parks the saddle")
  2828. detail = task_state(auth, live_task)
  2829. check(detail.get("refresh") is not None,
  2830. "the sealed GET refresh action is still authored")
  2831. status, _ = http("GET", detail["refresh"]["uri"], timeout=15)
  2832. check(status in (200, 401),
  2833. "the refresh URI resolves as a GET (client roundtrip shape)")
  2834. act(auth, pushed_block["answer_action"], {"answer": "A"})
  2835. # The answer makes the parked task resume-offerable: the affine
  2836. # saddle is woken, asks, and its assignment carries the answer.
  2837. pushes_before = len([p for p in fake.start_payloads
  2838. if int(p.get("task", {}).get("id") or 0) == live_task])
  2839. check(wait_for(lambda: len([p for p in fake.start_payloads
  2840. if int(p.get("task", {}).get("id") or 0) == live_task])
  2841. > pushes_before or False, timeout=60,
  2842. what="blocked task resumes") is not None,
  2843. "answering the pushed block resumes the parked workspace")
  2844. fake.hold_state = False # the resumed round runs to completion
  2845. resume_payload = [p for p in fake.start_payloads
  2846. if int(p.get("task", {}).get("id") or 0) == live_task][-1]
  2847. answers = resume_payload.get("task", {}).get("answers", [])
  2848. check(any(a.get("answer") == "A" for a in answers),
  2849. "the resume assignment carries the human's answer")
  2850. check(wait_task_done(auth, live_task, timeout=60) is not None,
  2851. "live-block task completes after answering")
  2852. print("== phase 2: staleness — one probe decides ==")
  2853. # A silent-but-alive runner (long think, nothing to flush): after
  2854. # SADDLE_STALE_S (3s here) of silence it owes ONE exceptional
  2855. # GET /status; the answer keeps it running and the silence
  2856. # episode gets no second probe.
  2857. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2858. "project_id": "1",
  2859. "title": "Silent thinker",
  2860. "priority": "2",
  2861. })
  2862. thinker = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2863. if t["title"] == "Silent thinker"][0])
  2864. check(wait_for(lambda: task_state(auth, thinker).get("status") == "working"
  2865. or False, timeout=60, what="thinker working") is not None,
  2866. "silent thinker reaches working")
  2867. fake.silent = True # the daemon goes quiet mid-round (alive)
  2868. probes_at_start = fake.status_hits
  2869. check(wait_for(lambda: fake.status_hits > probes_at_start or False,
  2870. timeout=30, what="exceptional probe arrives") is not None,
  2871. "a silent runner gets its exceptional GET /status probe")
  2872. time.sleep(8)
  2873. second_window = fake.status_hits
  2874. time.sleep(6)
  2875. check(fake.status_hits == second_window,
  2876. "the silence episode is probed exactly once (no poll drumbeat)")
  2877. check(task_state(auth, thinker).get("status") == "working"
  2878. and saddle_card("fake-saddle")["status"] == "busy",
  2879. "the answered probe keeps the task running (no requeue)")
  2880. # Output flows again: the episode ends, the clock resets.
  2881. fake.silent = False
  2882. fake.push_chunks(["resumed output\r\n"])
  2883. check(wait_task_done(auth, thinker, timeout=60) is not None,
  2884. "the silent thinker completes once output flows again")
  2885. # The daemon vanishing mid-task: silence for the window, the
  2886. # probe fails, the task requeues with a bot comment and the
  2887. # saddle goes offline.
  2888. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2889. "project_id": "1",
  2890. "title": "Vanish victim",
  2891. "priority": "2",
  2892. })
  2893. vanish = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2894. if t["title"] == "Vanish victim"][0])
  2895. check(wait_for(lambda: task_state(auth, vanish).get("status") == "working"
  2896. or False, timeout=60, what="vanish victim working") is not None,
  2897. "vanish victim reaches working")
  2898. fake.kill()
  2899. check(wait_for(lambda: saddle_card("fake-saddle")["status"] == "offline" or False,
  2900. timeout=60, what="daemon death -> offline") is not None,
  2901. "vanishing daemon drives the saddle offline (failed staleness probe)")
  2902. check(wait_for(lambda: any("unreachable" in c["body"]
  2903. for c in task_state(auth, vanish).get("comments", []))
  2904. or False, timeout=30, what="unreachable comment") is not None,
  2905. "the affected task gets an unreachable bot comment")
  2906. check(task_state(auth, vanish)["status"] == "queued",
  2907. "the task requeues after the daemon death")
  2908. card = saddle_card("fake-saddle")
  2909. check(card.get("health") == "offline",
  2910. "health badge reports offline")
  2911. # The unreachable row flag marks the detection window: a task the
  2912. # web still sees working while its saddle is offline/fenced, before
  2913. # the requeue pass moves it. Controlled window (the real
  2914. # transitions above are atomic with their requeues).
  2915. conn = db()
  2916. conn.execute("insert into tasks (project_id, title, status, priority,"
  2917. " created_at) values (1, 'Unreachable row', 'working', 5,"
  2918. " strftime('%s','now'))")
  2919. unreachable_row = conn.execute("select max(id) from tasks").fetchone()[0]
  2920. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  2921. " values (?, ?, strftime('%s','now'))", (unreachable_row, fake_id))
  2922. conn.commit()
  2923. conn.close()
  2924. row = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2925. if int(t["id"]) == unreachable_row][0]
  2926. check(row.get("unreachable") is True,
  2927. "queue row shows the unreachable state in the window")
  2928. print("== phase 1: startup migrates the per-saddle token ==")
  2929. # Saddles registered before the flip hold legacy api_tokens rows.
  2930. # On startup every saddle row gets its canonical token: the
  2931. # legacy value it already holds (daemons keep their credential)
  2932. # or a freshly minted one.
  2933. conn = db()
  2934. conn.execute("insert into api_tokens (saddle_id, token, created_at)"
  2935. " values (?, 'saddle-legacy-copied-token', strftime('%s','now'))",
  2936. (int(racer_cards[fake2]["id"]),))
  2937. conn.execute("update saddles set token = null where name = 'racer-two'")
  2938. conn.execute("insert into saddles (name, host, status, current_task_id)"
  2939. " values ('tokenless-orphan', '127.0.0.1:1', 'offline', 0)")
  2940. conn.commit()
  2941. conn.close()
  2942. app.terminate()
  2943. app.wait(timeout=10)
  2944. app = start_app()
  2945. auth = login("admin", "adminpass123")
  2946. def saddle_row(name):
  2947. conn = db()
  2948. try:
  2949. return conn.execute("select id, token from saddles where name = ?",
  2950. (name,)).fetchone()
  2951. finally:
  2952. conn.close()
  2953. check(wait_for(lambda: saddle_row("tokenless-orphan") is not None
  2954. and (saddle_row("tokenless-orphan")[1] or "").startswith("saddle-")
  2955. or False, timeout=20, what="tokenless row minted") is not None,
  2956. "startup mints a token for a saddle row without one")
  2957. check(wait_for(lambda: saddle_row("racer-two") is not None
  2958. and saddle_row("racer-two")[1] == "saddle-legacy-copied-token"
  2959. or False, timeout=20, what="legacy token copied") is not None,
  2960. "startup copies the legacy api_tokens value onto the row")
  2961. fake2.token = "saddle-legacy-copied-token" # the daemon asks with it
  2962. status, _ = saddle_api("POST", "/api/saddle/next-task", "saddle-legacy-copied-token")
  2963. check(status in (200, 204),
  2964. "the legacy token still authenticates (copied, not replaced)")
  2965. conn = db()
  2966. conn.execute("delete from saddles where name = 'tokenless-orphan'")
  2967. conn.commit()
  2968. conn.close()
  2969. # The restart wiped the in-memory ask bookkeeping; the fleet's
  2970. # daemons re-establish sleeping with a fresh ask each (the real
  2971. # daemons' idle-awake ask / 15-minute safety self-ask).
  2972. for daemon in (fake2, fake3):
  2973. daemon.ask_now()
  2974. check(True, "fleet re-asks after the restart (sleeping re-established)")
  2975. finally:
  2976. # Exit-code diagnostic: distinguishes a crashed app (negative
  2977. # returncode, e.g. -11 SIGSEGV) from a clean shutdown. When
  2978. # tearing down mid-exception, also capture the still-alive
  2979. # app's stacks before killing it (a wedged-but-alive server
  2980. # otherwise leaves no evidence).
  2981. print("(app returncode at teardown: %s)" % app.poll())
  2982. if app.poll() is None and sys.exc_info()[0] is not None:
  2983. dump_app_stacks(app.pid)
  2984. app.terminate()
  2985. try:
  2986. app.wait(timeout=5)
  2987. except subprocess.TimeoutExpired:
  2988. app.kill()
  2989. print("%d passed, %d failed" % (passes, failures))
  2990. return 1 if failures else 0
  2991. if __name__ == "__main__":
  2992. sys.exit(main())