web_stack_test.py 221 KB

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