web_stack_test.py 225 KB

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