web_stack_test.py 202 KB

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