Coverage for packages/workshop/src/livery/workshop/_e2e.py: 65%
Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_sync_install.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_runs.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_extension_mount.py, packages/workshop/tests/test_workshop_e2e.py, packages/workshop/tests/test_workshop_credential_traces.py, packages/extensions/python/tests/test_extensions_python.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/cpp/tests/test_extensions_cpp.py, packages/extensions/conan/tests/test_extensions_conan.py ran.
1415 statements
924 run
491 missing
4 excluded
34 partial
?
Keys r m x p show or hide the lines of a kindj k the next or previous highlighted chunk0 the top of the page1 the first highlighted chunk[ ] the previous or next fileu the index? show or hide this help
1 """``fm ci.e2e``: the CI and release story against a local forge.
3 The workshop's own development substrate: provision a scratch
4 repository on the seeded local forge, and drive the emitted
5 workflows through a real runner against the forge's own package
6 registry, so the whole second world runs consequence-free before
7 anything reaches a public forge. The loop's workspace splits its one
8 runner's check leg into two shards, so every pass proves the slice,
9 the gate job's fold and the durations row beside the gate itself.
11 The verb registers only where the workshop develops itself, the way
12 ``fm forge.fixtures.record`` does: a consumer checkout does not
16 from __future__ import annotations 8 ctx
23 from collections . abc import ( 8 ctx
32 from dataclasses import dataclass , field , replace 8 ctx
33 from datetime import UTC , datetime 8 ctx
34 from pathlib import Path 8 ctx
35 from typing import TYPE_CHECKING , TypeVar 8 ctx
37 import livery . footman as footman 8 ctx
38 from livery import git 8 ctx
39 from livery . footman import fail 8 ctx
40 from livery . forge import ForgeError 8 ctx
41 from livery . workshop . _ci_context import state_store 8 ctx
42 from livery . workshop . _ci_tasks import ci 8 ctx
43 from livery . workshop . _e2e_rows import ( 8 ctx
52 from livery . workshop . _series import LOOP 8 ctx
53 from livery . workshop . _verdict import FollowTimedOut , ForgeUnreachable , Pending , follow 8 ctx
56 from livery . forge import Forge , Job , Registry , Repository , Run
57 from livery . workshop . _devenv import Environment
58 from livery . workshop . _packages import Package
60 #: What a runs reader answers.
61 _A = TypeVar ( " _A " ) 8 ctx
63 #: The seeded organisation and the loop's one scratch repository.
64 E2E_OWNER = " livery " 8 ctx
65 E2E_REPO = " ci-e2e-loop " 8 ctx
67 #: The workshop's own test suite, present only in a source checkout:
68 #: this file is src/livery/workshop/_e2e.py, so the package directory
69 #: holding tests/ is three parents up.
70 _WORKSHOP_TESTS = Path ( __file__ ) . resolve ( ) . parents [ 3 ] / " tests " 8 ctx
72 #: The member the loop eats the dev wheels of; its dependency closure
73 #: rides along, read from the contracts by `dev_members`.
74 DEV_MEMBER = " packages/workshop " 8 ctx
76 #: What a reset of the loop's tree keeps: the directories `fm sync`
77 #: materialises, gitignored and read by the gate on the desk.
78 KEPT_BY_SYNC = ( " .venv " , " typings " , " .workshop " ) 8 ctx
80 #: How many shards the loop's workspace splits its one runner's check
81 #: leg into: every check leg of a pass runs as this many jobs, which
82 #: the gate job folds into one leg before anything reads the run.
88 """How many runner runs the pass has followed so far; the timing table reads it."""
93 #: The pass-wide count every wait on a run adds to, so a scenario's
94 #: row says how many runs it cost, not only how long it took.
100 """The environment a pass runs on, as the loop reads its forge from it.
103 name: The environment's name; empty outside a pass.
104 mode: `host` or `docker`.
105 url: The forge's URL in host mode; empty in docker mode, where
106 the cascade's shared file names it.
107 token: The seeded API token in host mode.
108 label: The runner label the loop's workspace names as its
109 runner and its wheel platform; the hosted name in docker
110 mode, the environment's own label in host mode.
117 label : str = " ubuntu-latest " 8 ctx
120 #: The environment of the running pass. `ci.e2e` sets it from
121 #: `--env` before anything reads the forge; the tests set it by hand.
122 CURRENT = Current ( ) 8 ctx
125 #: The variables that make the workshop read a process as a CI run: a
126 #: fix is refused inside CI, a tool the store cannot supply refuses, and
127 #: a run is stamped as the runner's. The pass drives its project as a
128 #: desk does, so its children run without them, on a hosted runner too.
129 CI_MARKERS : tuple [ str , . . . ] = ( " CI " , " GITHUB_ACTIONS " , " GITEA_ACTIONS " , " GITLAB_CI " ) 8 ctx
132 def scrub_ci_markers ( environ : MutableMapping [ str , str ] ) - > tuple [ str , . . . ] : 8 ctx
133 """Remove CI's markers from *environ*; the names removed, in declared order."""
134 removed = tuple ( name for name in CI_MARKERS if name in environ ) 1 ctx
135 for name in removed : 1 ctx
136 del environ [ name ] 1 ctx
140 def child_environment ( * * extra : str ) - > dict [ str , str ] : 8 ctx
141 """The environment a child the pass starts by hand begins with, *extra* over it.
143 The process environment over the task's. The pass is a serial task,
144 so the process environment is the real one, where the pass writes
145 its forge's own token after the task started; the task's carries
146 what the git plugin wrote at the task's start, the tools' identity
147 and the unsigned setting, which the process environment lacks. A
148 spawn given an explicit environment takes neither by itself.
150 return { * * footman . current ( ) . env , * * os . environ , * * extra } 7 ctx
153 def edit_environments ( 8 ctx
154 values : Mapping [ str , str ] , * , remove : Sequence [ str ] = ( )
156 """Write *values* and drop *remove* where this task and every child read them.
158 The pass is a serial task, so ``os.environ`` in it is the real
159 environment, which a child given an explicit environment built from
160 it inherits; footman's own ``run`` and the store's tool handles
161 spawn from the task's ``ctx.env``, the environment the task started
162 with, so the same edit lands there too. Without the second write a
163 git the pass runs through the store commits without the identity
164 and the unsigned setting, which a hosted runner showed. Returns the
165 names removed from the process environment, in *remove*'s order.
167 from livery . footman import current 5 ctx
169 environments : list [ MutableMapping [ str , str ] ] = [ os . environ , current ( ) . env ] 5 ctx
170 removed = tuple ( name for name in remove if name in os . environ ) 5 ctx
171 for environ in environments : 5 ctx
172 environ . update ( values ) 5 ctx
173 for name in remove : 5 ctx
174 environ . pop ( name , None ) 1 ctx
178 def dev_members ( root : Path , extensions : Sequence [ str ] | None = None ) - > tuple [ str , . . . ] : 8 ctx
179 """The members whose dev wheels the loop eats: the workshop and what a birth lists.
181 Directory names, the workshop first, then each member that ships
182 an extension a birth lists, and each dependency after the first
183 member that names it, once. An edge of every kind counts: the
184 wheel the runner installs resolves all of them from the loop's
185 registry, and a member the closure does not reach publishes
186 nothing there. An extension depends on the workshop, never the
187 other way round, so the workshop's closure alone leaves the
188 newborn's listed extensions nothing to install. *extensions* is
189 the stack a birth lists, the stock list when None.
192 Failed: when *root* has no workshop member to eat.
194 from livery . workshop . _extensions import SELF , distribution_of , listing 10 ctx
195 from livery . workshop . _new_project import birth_extensions 10 ctx
196 from livery . workshop . _packages import discover_packages 10 ctx
198 by_path = { package . path : package for package in discover_packages ( root ) } 10 ctx
199 workshop = by_path . get ( DEV_MEMBER ) 10 ctx
200 if workshop is None : 10 ctx
201 fail ( f " { root } : no { DEV_MEMBER } member; the loop eats the workshop ' s dev wheels " ) 1 ctx
202 listed = birth_extensions ( [ SELF ] ) if extensions is None else extensions 9 ctx
203 stock = { distribution_of ( listing ( entry ) . name ) for entry in listed } 9 ctx
204 shipping = sorted ( 9 ctx
205 ( p for p in by_path . values ( ) if p . name in stock and p is not workshop ) ,
206 key = lambda package : package . path ,
208 ordered : list [ str ] = [ ] 9 ctx
209 pending = [ workshop , * shipping ] 9 ctx
211 package = pending . pop ( 0 ) 9 ctx
212 if package . member in ordered : 9 ctx
214 ordered . append ( package . member ) 9 ctx
216 by_path [ edge . path ] for edge in package . depends if edge . path in by_path
218 return tuple ( ordered ) 9 ctx
221 @dataclass ( frozen = True ) 8 ctx
223 """One local forge the loop runs against, as the host and the runner reach it.
226 kind: The forge kind, ``gitea`` or ``gitlab``.
227 alias: The forge as CI sees it, the compose service name and
228 port, true on the host too through its hosts entry.
229 url_var: The shared env key the seed writes the host-side URL
231 token_var: The shared env key the seed writes the lane token to.
232 version_path: The API path the hosts-entry probe reads.
233 runner: The compose service of the lane's runner.
240 version_path : str 8 ctx
244 def host ( self ) - > str : 8 ctx
245 """The compose hostname alone, for the hosts entry."""
246 return self . alias . removeprefix ( " http:// " ) . rsplit ( " : " , 1 ) [ 0 ] 2 ctx
248 def publish ( self , base : str = " " ) - > str : 8 ctx
249 """The PyPI upload base for the loop's packages at *base*, the alias by default.
251 Gitea keeps an owner's registry; GitLab a project's, addressed
252 by its URL-encoded path.
254 base = base or self . alias 3 ctx
255 if self . kind == " gitlab " : 3 ctx
256 from urllib . parse import quote 1 ctx
258 project = quote ( f " { E2E_OWNER } / { E2E_REPO } " , safe = " " ) 1 ctx
259 return f " { base } /api/v4/projects/ { project } /packages/pypi " 1 ctx
260 return f " { base } /api/packages/ { E2E_OWNER } /pypi " 3 ctx
262 def index ( self , base : str = " " ) - > str : 8 ctx
263 """The simple index the loop's packages are read from."""
264 return f " { self . publish ( base ) } /simple " 1 ctx
267 #: The lanes, by forge kind.
268 LANES : dict [ str , Lane ] = { 8 ctx
279 " http://gitlab:8929 " ,
287 #: The compose project the dev containers belong to; a container is
288 #: named ``<project>-<service>-1``.
289 _DEV_PROJECT = " livery-forge-dev " 8 ctx
292 def _require_runner_docker ( kind : str ) - > None : 8 ctx
293 """Refuse until the lane's runner has the host's docker socket.
295 The loop's native member builds its wheel through cibuildwheel on
296 the runner, which needs a daemon, and the runners get the socket
297 only from ``fm forge.dev.up --with-docker``. A runner that is not
298 up at all is named the same way, so the refusal comes before the
299 minutes a pass spends reaching the release act.
303 import livery . toolroom . tools as tools 1 ctx
305 if CURRENT . mode == " host " : 305 ↛ 309line 305 didn't jump to line 309 because the condition on line 305 was never true 1 ctx
306 # The runner is a process of this machine, and cibuildwheel
307 # reaches the machine's own daemon: the one question is
308 # whether it answers.
309 info = tools . docker . opts ( nofail = True , recorded = False ) ( " info " )
312 " the machine ' s docker daemon does not answer, and the loop ' s "
313 " native member builds its wheel through cibuildwheel on it: "
314 " start Docker Desktop, or the daemon "
317 lane = _lane ( kind ) 1 ctx
318 container = f " { _DEV_PROJECT } - { lane . runner } -1 " 1 ctx
319 result = tools . docker . opts ( nofail = True , recorded = False ) ( 1 ctx
320 " inspect " , " --format " , " {{ json .Mounts}} " , container
322 if result . code != 0 : 1 ctx
324 f " the { kind } runner ( { container } ) is not up: "
325 f " ` { footman . prog ( ) } forge.dev.up --profile= { kind } --with-docker` "
328 mounts = json . loads ( result . stdout or " [] " ) 1 ctx
329 except ValueError : 1 ctx
331 destinations = { 1 ctx
332 str ( mount . get ( " Destination " , " " ) ) for mount in mounts if isinstance ( mount , dict )
334 if " /var/run/docker.sock " not in destinations : 1 ctx
336 f " the { kind } runner has no docker socket, and the loop ' s native "
337 " member builds its wheel through cibuildwheel on it: "
338 f " ` { footman . prog ( ) } forge.dev.up --profile= { kind } --with-docker` "
342 def _lane ( kind : str ) - > Lane : 8 ctx
343 """The lane for *kind*; refuses a kind with no local containers.
345 On a host-mode environment the lane's alias is the environment's
346 own URL: the forge and the runner are processes of this machine,
347 so one localhost URL is true on both sides of the loop.
349 from dataclasses import replace 17 ctx
351 lane = LANES . get ( kind ) 17 ctx
352 if lane is None : 17 ctx
354 f " --forge= { kind } is not a local lane: the loop runs against "
355 f " { ' , ' . join ( LANES ) } "
357 if CURRENT . mode == " host " and CURRENT . url : 16 ctx
358 return replace ( lane , alias = CURRENT . url ) 3 ctx
362 def _enter_host ( values : Mapping [ str , str ] , env : str ) - > None : 8 ctx
363 """Run the pass on the host-mode environment *env*, whose *values* these are.
365 The forge's URL and token go into the pass's own environment as
366 well as `CURRENT`. The cascade filled them when the pass started,
367 before the bring-up seeded the environment, and every child the
368 pass starts (the birth, the loop's own fm) copies that
369 environment, so each would otherwise reach the forge with a token
370 the environment no longer holds. The generic forge variables go
371 too: the workshop reads ``FORGE_TOKEN`` and ``FORGE_ADMIN_TOKEN``
372 before a forge's own, and a hosted job carries the real forge's in
373 them, so the newborn would otherwise hand GitHub's token to the
374 local Gitea and meet a 401.
376 CURRENT . name , CURRENT . mode = env , " host " 4 ctx
377 CURRENT . url , CURRENT . token = values [ " GITEA_URL " ] , values [ " GITEA_TOKEN " ] 4 ctx
378 CURRENT . label = values [ " LABELS " ] . split ( " , " ) [ 0 ] 4 ctx
379 lane = LANES [ " gitea " ] 4 ctx
380 os . environ [ lane . url_var ] , os . environ [ lane . token_var ] = CURRENT . url , CURRENT . token 4 ctx
381 os . environ [ " FORGE_TOKEN " ] = os . environ [ " FORGE_ADMIN_TOKEN " ] = CURRENT . token 4 ctx
384 def enter_environment ( 8 ctx
385 name : str , extensions : Sequence [ str ] , * , fresh : bool = False
387 """Run the pass on environment *name*, brought up first; the environment.
389 A host-mode environment is brought up; with *fresh* it is removed
390 first, so the pass gets a new forge, and so is a directory that a
391 refused removal left. A removal that cannot take the whole
392 directory refuses, and the pass stops there
393 ([livery.workshop._devenv.remove][]). The forge's URL and token then
394 go into the pass's environment (`_enter_host`). A docker-mode
395 environment is the compose rig, used as it is, fresh or not.
397 In both modes the pass and every process it starts then run with
398 the variables the set of *extensions*, the list the loop's
399 workspace is born with, declares, each one naming ``{place}``
400 placed in the environment's directory. A tool's home placed there
401 goes with the environment: a release writes a remote into it that
402 names the environment's forge, and a home shared with an earlier
403 pass would keep that remote after the forge is gone, so a later
404 install that asks the remotes tries it and fails. A fresh pass
405 starts with nothing an earlier one wrote there.
407 from livery . workshop import _devenv 4 ctx
409 place = _devenv . environment ( name ) 4 ctx
410 if fresh and place . mode != " docker " and place . directory . is_dir ( ) : 4 ctx
411 for line in _devenv . remove ( place ) : 3 ctx
413 place = _devenv . environment ( name ) 3 ctx
414 if place . mode == " docker " : 4 ctx
415 CURRENT . name , CURRENT . mode = name , " docker " 1 ctx
417 _devenv . up_host ( place , ( " host " , ) ) 3 ctx
418 place = _devenv . environment ( name ) 3 ctx
419 _enter_host ( place . values ( ) , name ) 3 ctx
420 from livery . workshop . _composition import closure 4 ctx
421 from livery . workshop . _extensions import installed_declaration 4 ctx
423 held = closure ( extensions , installed_declaration ) 4 ctx
424 variables = place . variables ( held , os . environ ) 4 ctx
425 edit_environments ( variables ) 4 ctx
426 for variable , value in variables . items ( ) : 4 ctx
427 print ( f " { variable } : { value } " ) 2 ctx
431 def _dev_forge ( kind : str ) - > tuple [ Forge , str ] : 8 ctx
432 """The seeded local forge and its token; refusal teaches.
434 The credentials are the ones ``fm forge.dev.up`` writes into the
435 shared env file the cascade reads, so a warm machine needs
436 nothing beyond the containers being up.
438 lane = _lane ( kind ) 5 ctx
439 url = CURRENT . url or os . environ . get ( lane . url_var , " " ) 4 ctx
440 token = CURRENT . token or os . environ . get ( lane . token_var , " " ) 4 ctx
441 if not url or not token : 4 ctx
443 f " the local { kind } ' s credentials are not in the environment. "
444 f " Run ` { footman . prog ( ) } devenv.up`: it starts and seeds the "
445 f " environment and writes { lane . url_var } and { lane . token_var } "
446 " into the shared env file the cascade reads "
448 from livery . workshop . _forge_lane import _connect 3 ctx
450 return _connect ( kind , url , token ) , token 3 ctx
453 def provision ( kind : str = " gitea " ) - > None : 8 ctx
454 """Ensure the loop's repository, idempotently, with its secrets.
456 The repository is created on the seeded organisation when absent
457 and reused when present. ``UV_PUBLISH_TOKEN`` is written as an
458 Actions secret with the forge token's value, because the forge's
459 own package registry authenticates with the same credential as
460 its API. Re-running is the recovery procedure.
462 from livery . forge import ForgeError , RepoConfig 4 ctx
464 forge , token = _dev_forge ( kind ) 4 ctx
466 existing = forge . get_repo ( E2E_OWNER , E2E_REPO ) 2 ctx
467 except ForgeError as error :
469 f " the local forge did not answer: { error } . Is the container "
470 f " up? ` { footman . prog ( ) } forge.dev.up --profile=gitea` "
472 if existing is None : 2 ctx
473 forge . create_repo ( 2 ctx
477 description = " The workshop ' s local CI loop. Scratch; recreated freely. " ,
479 print ( f " created { E2E_OWNER } / { E2E_REPO } " ) 2 ctx
481 print ( f " reusing { E2E_OWNER } / { E2E_REPO } " ) 1 ctx
482 repo = forge . repository ( E2E_OWNER , E2E_REPO ) 2 ctx
483 if kind == " gitlab " : 2 ctx
484 _make_project_public ( os . environ . get ( _lane ( kind ) . url_var , " " ) , token ) 1 ctx
485 print ( " project: public, so its registry reads without a credential " ) 1 ctx
486 # Three secrets, all the lane token: the registry credential the
487 # publish reads, the forge lane's everyday token, and the admin
488 # ladder's, because the emitted governance job asks for it and
489 # the seeded admin account holds every grant anyway. GitLab's jobs
490 # push through a fourth, a project access token, since the job
493 " UV_PUBLISH_TOKEN " : token ,
494 " FORGE_TOKEN " : token ,
495 " FORGE_ADMIN_TOKEN " : token ,
497 if kind == " gitlab " : 2 ctx
498 secrets [ " GITLAB_PUSH_TOKEN " ] = _mint_push_token ( 1 ctx
499 os . environ . get ( _lane ( kind ) . url_var , " " ) , token
501 repo . configure ( RepoConfig ( secrets = secrets ) ) 2 ctx
502 print ( f " secrets set: { ' , ' . join ( secrets ) } " ) 2 ctx
505 #: One GitLab API call for the loop's provisioning: (method, path,
506 #: token, body) to (status, parsed body or text).
507 GitlabCall = Callable [ [ str , str , str , " dict[str, object] | None " ] , " tuple[int, object] " ] 8 ctx
510 def _gitlab_call ( 8 ctx
511 method : str , url : str , token : str , body : dict [ str , object ] | None = None
512 ) - > tuple [ int , object ] :
513 """One GitLab API call for the loop's provisioning; (status, parsed body)."""
516 import urllib . request
518 request = urllib . request . Request (
520 data = json . dumps ( body ) . encode ( ) if body is not None else None ,
522 headers = { " PRIVATE-TOKEN " : token , " Content-Type " : " application/json " } ,
525 with urllib . request . urlopen ( request , timeout = 30 ) as response :
526 text = response . read ( ) . decode ( )
527 return int ( response . status ) , ( json . loads ( text ) if text else None )
528 except urllib . error . HTTPError as exc :
529 return exc . code , exc . read ( ) . decode ( errors = " replace " )
532 def _make_project_public ( url : str , token : str , api : GitlabCall | None = None ) - > None : 8 ctx
533 """Make the loop's GitLab project public, so its registry reads anonymously.
535 The runner installs the dev wheels from the project's PyPI index
536 and the loop locks against it here, both without a credential, as
537 both read Gitea's owner registry. A private project's index
538 answers 401 to both, whatever the group's visibility. *api* is the
539 call, the live one by default.
541 from urllib . parse import quote 2 ctx
543 api = api or _gitlab_call 2 ctx
544 path = f " { url } /api/v4/projects/ { quote ( f ' { E2E_OWNER } / { E2E_REPO } ' , safe = ' ' ) } " 2 ctx
545 status , body = api ( " PUT " , path , token , { " visibility " : " public " } ) 2 ctx
546 if status != 200 : 2 ctx
547 fail ( f " making { E2E_OWNER } / { E2E_REPO } public answered HTTP { status } : { body } " ) 1 ctx
550 def _mint_push_token ( url : str , token : str , api : GitlabCall | None = None ) - > str : 8 ctx
551 """A project access token that may push to the loop's project; its value.
553 GitLab's job token cannot push, so the state store, the receipt
554 tags and the template artifact ride a project access token with
555 ``write_repository``. A token's value is readable at minting
556 alone, so every provisioning mints one and revokes the ones it
557 minted before, by name. *api* is the call, the live one by
560 from datetime import UTC , datetime , timedelta 2 ctx
561 from urllib . parse import quote 2 ctx
563 api = api or _gitlab_call 2 ctx
564 base = f " { url } /api/v4/projects/ { quote ( f ' { E2E_OWNER } / { E2E_REPO } ' , safe = ' ' ) } " 2 ctx
565 name = " livery-loop-push " 2 ctx
568 path : str , * , method : str = " GET " , body : dict [ str , object ] | None = None
569 ) - > tuple [ int , object ] :
570 return api ( method , base + path , token , body ) 2 ctx
572 status , listed = call ( " /access_tokens " ) 2 ctx
573 if status == 200 and isinstance ( listed , list ) : 573 ↛ 581line 573 didn't jump to line 581 because the condition on line 573 was always true 2 ctx
574 for item in listed : 2 ctx
575 if ( 575 ↛ 574line 575 didn't jump to line 574 because the condition on line 575 was always true
576 isinstance ( item , dict )
577 and item . get ( " name " ) == name
578 and item . get ( " active " )
580 call ( f " /access_tokens/ { item [ ' id ' ] } " , method = " DELETE " ) 1 ctx
581 expires = ( datetime . now ( UTC ) + timedelta ( days = 30 ) ) . date ( ) . isoformat ( ) 2 ctx
582 status , made = call ( 2 ctx
587 " scopes " : [ " api " , " write_repository " ] ,
589 " expires_at " : expires ,
592 if status != 201 or not isinstance ( made , dict ) or not made . get ( " token " ) : 2 ctx
593 fail ( f " the loop ' s push token was not minted: HTTP { status } : { made } " ) 1 ctx
594 return str ( made [ " token " ] ) 1 ctx
597 @dataclass ( frozen = True ) 8 ctx
598 class LoopMember : 8 ctx
599 """One member of the loop: its directory and the template it is born from.
602 name: The member's directory under ``packages/``.
603 template: The template whose verb, ``fm new.package.<template>``,
604 births it, and whose ``extensions`` the member's contract
611 def listed ( self ) - > tuple [ str , . . . ] : 8 ctx
612 """The extensions the member's contract lists, from its template.
614 The template's ``extensions`` in their canonical form, which a
615 birth writes into the contract, so the loop and the birth name
616 one list. The template is read from every available one,
617 whatever the driving checkout's lists hold: the loop's
618 workspace, not the driver's, creates the member.
620 from livery . workshop . _composition import canonical 3 ctx
621 from livery . workshop . _extensions import installed_declaration 3 ctx
622 from livery . workshop . _seeds import available_templates 3 ctx
624 declared = available_templates ( ) [ self . template ] 3 ctx
625 return canonical ( declared . extensions , installed_declaration ) 3 ctx
627 def needs ( self ) - > tuple [ str , . . . ] : 8 ctx
628 """The extensions the loop's root lists before the member is created.
630 Those its template's chain needs: each template's
631 ``extensions`` and the extension declaring it, since a creation
634 from livery . workshop . _seeds import chain_needs , template_chain 8 ctx
636 return chain_needs ( template_chain ( self . template ) ) 8 ctx
638 def holds ( self ) - > tuple [ str , . . . ] : 8 ctx
639 """The extensions the member's set holds: its list and what it requires."""
640 from livery . workshop . _composition import closure 3 ctx
641 from livery . workshop . _extensions import installed_declaration 3 ctx
643 return closure ( self . listed ( ) , installed_declaration ) 3 ctx
646 #: The loop's members. The nanobind member forces the wheels path on
647 #: every pass: its wheel is built on the runner through cibuildwheel,
648 #: published, and installed in the isolated leg. The cpp-conan member
649 #: forces the native measurement and the conan path: its gate build
650 #: is measured by gcov beside the runner image's gcc and its lines
651 #: join the union, the release leg creates it into conan's cache, and
652 #: the wave publishes it through the forge's conan registry.
653 LOOP_MEMBERS : tuple [ LoopMember , . . . ] = ( 8 ctx
654 LoopMember ( " loop-echo " , " python-library " ) ,
655 LoopMember ( " loop-native " , " nanobind-module " ) ,
656 LoopMember ( " loop-cpp " , " cpp-package " ) ,
660 #: The member that contributes a point, and the point's name.
661 CONTRIBUTING_MEMBER = " loop-echo " 8 ctx
662 CONTRIBUTED_POINT = " echo-audit " 8 ctx
664 #: The verb the loop's contract schedules at the nightly point: it
665 #: verifies the member's released wheel against its own tests.
666 VERIFY_TASK = " release.verify " 8 ctx
669 def _contract_name ( root : Path , member : str ) - > str : 8 ctx
670 """The name the loop member *member*'s contract declares, as the verbs print it."""
673 contract = root / " packages " / member / " workshop.toml "
674 return str ( tomllib . loads ( contract . read_text ( " utf-8 " ) ) [ " name " ] )
677 def _serving_probe ( root : Path ) - > Callable [ [ str ] , tuple [ str , . . . ] ] : 8 ctx
678 """What the loop's registries serve of a member, by name: its versions.
680 Each member is probed where its extensions release it, through the
681 probe they answer for that registry, under the name its contract
682 declares, which the wave publishes it under: the python index
683 normalises a name, and a conan registry matches it exactly. Each
684 probe is built once and polled through the wave's wait.
686 from livery . workshop import _lifecycle 2 ctx
687 from livery . workshop . _packages import discover_packages 2 ctx
689 members = { package . member : package for package in discover_packages ( root ) } 2 ctx
690 probes : dict [ str , Registry ] = { } 2 ctx
692 def versions ( name : str ) - > tuple [ str , . . . ] : 2 ctx
693 package = members [ name ] 2 ctx
694 probe = probes . get ( name ) 2 ctx
695 if probe is None : 2 ctx
696 probe = probes [ name ] = _lifecycle . registry ( package ) 2 ctx
697 return probe . versions ( package . name ) 2 ctx
702 def _require_host_alias ( kind : str = " gitea " ) - > None : 8 ctx
703 """Refuse until the host resolves the lane's compose hostname.
705 One registry URL must be true on both sides of the loop: the
706 runner resolves the compose service name, the host does not, and
707 a split URL forces an unlocked workspace and a hostname fork
708 through every file. The one-line alias makes the compose name
709 true on the host too, and the lock then carries a URL both sides
712 import urllib . error 2 ctx
713 import urllib . request 2 ctx
715 if CURRENT . mode == " host " : 2 ctx
716 # A localhost URL needs no alias: the same address is true for
717 # the driver, the forge and the runner, all on this machine.
719 lane = _lane ( kind ) 1 ctx
721 with urllib . request . urlopen ( lane . alias + lane . version_path , timeout = 2 ) : 1 ctx
723 except urllib . error . HTTPError : 1 ctx
724 # The host answered: GitLab's version endpoint refuses an
725 # anonymous read with 401, and the alias resolved all the same.
727 except ( urllib . error . URLError , TimeoutError , OSError ) : 1 ctx
729 f " the host cannot reach { lane . alias } , the compose "
730 " hostname CI uses for the registry (a network resolving "
731 f " ' { lane . host } ' elsewhere fails the same way; /etc/hosts wins "
732 " over DNS). Add the alias once: "
733 f " sudo sh -c ' echo \" 127.0.0.1 { lane . host } \" >> /etc/hosts ' "
737 def _loop_home ( kind : str ) - > Path : 8 ctx
738 """Where the lane's workspace lives: durable, per machine and per forge.
740 One directory per lane: the workspaces have different remotes,
741 different registries and different histories, and one pass must
742 never adopt the other lane's checkout.
744 from livery . footman import data_dir 1 ctx
746 home = data_dir ( ) / " workshop-e2e " 1 ctx
747 if CURRENT . name : 1 ctx
748 home = home / CURRENT . name 1 ctx
749 return home / kind 1 ctx
752 def _dev_pins ( root : Path , head : str , members : tuple [ str , . . . ] ) - > dict [ str , str ] : 8 ctx
753 """The dev versions this pass built for *members*, by distribution name.
755 Read from the wheels [livery.workshop._e2e._dev_wheels][] finds.
758 name : wheel . name . split ( " - " , 2 ) [ 1 ]
759 for name , wheel in _dev_wheels ( root , head , members ) . items ( )
763 def _dev_wheels ( root : Path , head : str , members : tuple [ str , . . . ] ) - > dict [ str , Path ] : 8 ctx
764 """The wheel this pass built for each of *members*, by distribution name.
766 The newest wheel in each member's ``dist``, which the dev act just
767 filled, checked against *head*: a dev version's local segment is
768 ``<branch>.<sha>.<date>``, ``.dirty`` appended for a tree no
769 commit describes, so a wheel a previous pass left behind can never
770 pin the loop. Refuses, naming the member, when a dist holds no
771 wheel or its newest wheel is another commit's.
773 found : dict [ str , Path ] = { } 5 ctx
774 for member in members : 5 ctx
775 dist = root / " packages " / member / " dist " 5 ctx
776 wheels = sorted ( dist . glob ( " *.whl " ) , key = lambda wheel : wheel . stat ( ) . st_mtime ) 5 ctx
778 fail ( f " no dev wheel in { dist } : the dev act built nothing for { member } " ) 1 ctx
779 name , version = wheels [ - 1 ] . name . split ( " - " , 2 ) [ : 2 ] 4 ctx
780 local = version . partition ( " + " ) [ 2 ] . split ( " . " ) 4 ctx
781 if local and local [ - 1 ] == " dirty " : 4 ctx
783 # The sha as git describe spells it, ``g`` first; a hex sha
784 # never starts with a ``g`` of its own.
785 sha = local [ - 2 ] . removeprefix ( " g " ) if len ( local ) > = 2 else " " 4 ctx
786 if not sha or not head . startswith ( sha ) : 4 ctx
788 f " the newest wheel in { dist } is { wheels [ - 1 ] . name } , built from "
789 f " { sha or ' no commit ' } , not from HEAD { head [ : 12 ] } : the dev "
790 f " act did not build this pass ' s { member } "
792 found [ name . replace ( " _ " , " - " ) ] = wheels [ - 1 ] 3 ctx
797 root : Path , stack : Sequence [ str ] = ( )
798 ) - > tuple [ list [ str ] , dict [ str , str ] ] :
799 """The dev members this pass builds, and the release each other one pins, by member.
801 A member nothing unreleased touches cannot be built as a dev
802 wheel: that number would sort below its release and satisfy no
803 floor naming it. The loop pins the release instead, and drops the
804 member's stale rehearsal wheels from the registry, which a
805 first-index resolve would otherwise pick over the release.
807 from livery . workshop . _dev_release import unchanged_since_release 2 ctx
808 from livery . workshop . _packages import discover_packages 2 ctx
810 packages = { package . member : package for package in discover_packages ( root ) } 2 ctx
811 changed : list [ str ] = [ ] 2 ctx
812 released : dict [ str , str ] = { } 2 ctx
813 for member in dev_members ( root , tuple ( stack ) or None ) : 2 ctx
814 version = unchanged_since_release ( root , packages [ member ] ) 2 ctx
816 released [ member ] = version 2 ctx
818 changed . append ( member ) 2 ctx
819 return changed , released 2 ctx
822 def write_dev_index ( folder : Path , wheels : Collection [ Path ] ) - > Path : 8 ctx
823 """Lay *wheels* out at *folder* as a simple index uv reads; *folder*.
825 One directory per project, named as PEP 503 normalises it, holding
826 the project's wheels and a page that links them, and a root page
827 that links the projects. Whatever *folder* held before goes, so a
828 wheel an earlier pass built is never offered again.
830 if folder . exists ( ) : 7 ctx
831 shutil . rmtree ( folder ) 2 ctx
832 folder . mkdir ( parents = True ) 7 ctx
833 projects : dict [ str , list [ Path ] ] = { } 7 ctx
834 for wheel in wheels : 7 ctx
835 name = re . sub ( r " [-_.]+ " , " - " , wheel . name . split ( " - " , 1 ) [ 0 ] ) . lower ( ) 7 ctx
836 projects . setdefault ( name , [ ] ) . append ( wheel ) 7 ctx
837 for name , files in sorted ( projects . items ( ) ) : 7 ctx
838 ( folder / name ) . mkdir ( ) 7 ctx
839 for wheel in files : 7 ctx
840 shutil . copy2 ( wheel , folder / name / wheel . name ) 7 ctx
841 _index_page ( folder / name , sorted ( wheel . name for wheel in files ) ) 7 ctx
842 _index_page ( folder , [ f " { name } / " for name in sorted ( projects ) ] ) 7 ctx
846 def _index_page ( directory : Path , targets : list [ str ] ) - > None : 8 ctx
847 """Write *directory*'s ``index.html``: one link per target."""
848 links = " " . join ( f ' <a href= " { target } " > { target } </a> \n ' for target in targets ) 7 ctx
849 ( directory / " index.html " ) . write_text ( 7 ctx
850 f " <!DOCTYPE html> \n <html><body> \n { links } </body></html> \n " , " utf-8 "
854 def checkout_index ( 8 ctx
855 root : Path , folder : Path , extensions : Sequence [ str ] | None = None
857 """Build what a newborn installs from *root* as a local index at *folder*; its URL.
859 The members are [livery.workshop._e2e.dev_members][]: the workshop,
860 what it depends on, and the extensions a birth lists. Each is built
861 by `build_content_named`, at the version its manifest declares with
862 a local segment naming its content, and
863 [livery.workshop._e2e.write_dev_index][] lays the wheels out. Named
864 first in ``UV_INDEX``, the index serves every distribution it holds,
865 whatever its version, because uv takes a package from the first
866 index that has it; every other package comes from the next.
867 ``UV_FIND_LINKS`` would not do: a folder named there only adds
868 candidates, and a stable release on PyPI beats a dev wheel
869 (measured). This is how a workspace installs this checkout's code
870 before a release, never the dev act, which on a main-family branch
871 is the release train. *extensions* is the stack the birth lists,
872 the stock list when None.
876 from livery . workshop . _packages import discover_packages 1 ctx
878 members = set ( dev_members ( root , extensions ) ) 1 ctx
879 with tempfile . TemporaryDirectory ( ) as scratch : 1 ctx
880 built = Path ( scratch ) / " wheels " 1 ctx
881 for package in discover_packages ( root ) : 1 ctx
882 if package . member in members : 1 ctx
883 build_content_named ( package , root , built ) 1 ctx
884 write_dev_index ( folder , sorted ( built . glob ( " *.whl " ) ) ) 1 ctx
885 return folder . as_uri ( ) 1 ctx
888 def build_content_named ( package : Package , root : Path , out : Path ) - > Path : 8 ctx
889 """Build *package*'s wheel into *out*, at a version naming its content; the wheel.
891 The build reads a copy of the package's directory, without its build
892 outputs and environments. The copy's version gains a local segment,
893 a digest of the copy's files, so the wheel's file name changes
894 whenever its content does. uv caches an installed wheel by its file
895 name and the place it came from, and installs the cached copy again
896 without reading a newer file of that name (measured). The package's
897 own files stay as they are. *root* is the workspace *package*
898 belongs to, whose stamp phase writes the version.
901 Failed: when nothing in the package's set answers its version,
902 or adds a step to the stamp phase.
906 import livery . toolroom . tools as toolroom 2 ctx
908 skipped = shutil . ignore_patterns ( 2 ctx
909 " .venv " , " dist " , " build " , " __pycache__ " , " _docs " , " *.egg-info "
911 with tempfile . TemporaryDirectory ( ) as scratch : 2 ctx
912 copy = Path ( scratch ) / " copy " / package . member 2 ctx
913 shutil . copytree ( package . directory , copy , ignore = skipped ) 2 ctx
914 _stamp_content ( replace ( package , directory = copy ) , root ) 2 ctx
915 built = Path ( scratch ) / " built " 2 ctx
916 toolroom . uv . opts ( cwd = root , recorded = False ) ( 2 ctx
917 " build " , " --wheel " , " --out-dir " , str ( built ) , str ( copy )
919 ( wheel , ) = built . glob ( " *.whl " ) 2 ctx
920 out . mkdir ( parents = True , exist_ok = True ) 2 ctx
921 return Path ( shutil . copy2 ( wheel , out / wheel . name ) ) 2 ctx
924 def _stamp_content ( package : Package , root : Path ) - > None : 8 ctx
925 """Give *package*'s version a local segment naming its tree's content.
927 A rebuilt wheel at an unchanged version carries the last one's file
928 name, and uv installs a cached wheel by its name: a birth installed
929 the code from before a fix (measured). The segment is a digest of
930 the package's files, so a change gets a new name and an unchanged
931 tree the same one, and every floor the version met still holds, a
932 local version sorting with its public one. The stamp phase of the
933 package's set writes it, into the files the package keeps its
937 Failed: when nothing in the package's set answers its version,
938 or adds a step to the stamp phase.
942 from livery . workshop import _lifecycle 3 ctx
944 tree = package . directory 3 ctx
945 digest = hashlib . sha256 ( ) 3 ctx
946 for path in sorted ( path for path in tree . rglob ( " * " ) if path . is_file ( ) ) : 3 ctx
947 digest . update ( path . relative_to ( tree ) . as_posix ( ) . encode ( " utf-8 " ) ) 3 ctx
948 digest . update ( b " \0 " ) 3 ctx
949 digest . update ( path . read_bytes ( ) ) 3 ctx
950 digest . update ( b " \0 " ) 3 ctx
951 version = _lifecycle . current_version ( package ) 3 ctx
952 _lifecycle . stamp ( package , root , f " { version } +checkout. { digest . hexdigest ( ) [ : 12 ] } " ) 3 ctx
955 def _dev_index ( kind : str , stack : Sequence [ str ] = ( ) ) - > str : 8 ctx
956 """This checkout's index under the lane's home, for the birth to read; its URL.
958 The birth locks the newborn before the pass publishes anything, and
959 every extension the birth lists is in that first lock, released or
960 not: [livery.workshop._e2e.checkout_index][] builds them.
962 from livery . workshop . _extensions import workspace_root
964 root = workspace_root ( )
966 fail ( " no workspace: no workshop.toml above the working directory " )
967 folder = _loop_home ( kind ) . parent / f " { kind } -dev-index "
968 url = checkout_index ( root , folder , tuple ( stack ) or None )
969 held = sum ( 1 for entry in folder . iterdir ( ) if entry . is_dir ( ) )
971 f " checkout index: { held } distributions at { folder } , read first by the birth "
976 def require_dev_branch ( root : Path ) - > None : 8 ctx
977 """Refuse unless *root* stands on a branch whose release verb is the dev act.
979 The loop builds the dev wheels it installs with `workflow.release`
980 in this checkout, and the branch decides that verb's act. On
981 ``main`` or a reserved ``workflow/`` branch it is the release train,
982 which opens a real release on this repository's forge, and a merged
983 one publishes to the real index; a detached HEAD names no act at all.
985 from livery . workshop . _release_driver import runs_the_train 4 ctx
987 branch = git . current_branch ( root ) 4 ctx
988 if branch and not runs_the_train ( branch ) : 4 ctx
990 where = f " ' { branch } ' " if branch else " a detached HEAD " 1 ctx
991 prog = footman . prog ( ) 1 ctx
993 f " the loop builds its dev wheels with ` { prog } workflow.release`, and on "
994 f " { where } that is the release train, which opens a real release: start a "
995 f " branch at this commit (` { prog } start chore/<slug>`) and run the loop there "
999 @contextlib . contextmanager 8 ctx
1000 def scratch_branch ( root : Path | None , * , enabled : bool ) - > Generator [ None , None , None ] : 8 ctx
1001 """Run a pass from a scratch branch where a build would be the release train.
1003 ``--from-main``: a nightly's checkout stands on ``main``, where the
1004 loop's first build is the release train, so the pass moves to
1005 ``chore/loop-<stamp>`` at the same commit before anything builds
1006 and returns afterwards, deleting the branch when it gained no
1007 commit. A checkout already on a dev branch, or none, is left
1008 alone. A dirty tree refuses naming the paths, so the scratch branch
1009 holds exactly the commit it started from.
1012 root: The driver checkout, None when the pass runs outside one.
1013 enabled: Whether ``--from-main`` was asked.
1016 Nothing; the pass runs inside.
1018 from livery . workshop . _release_driver import runs_the_train 4 ctx
1020 if root is None or not enabled : 4 ctx
1023 branch = git . current_branch ( root ) 4 ctx
1024 if branch and not runs_the_train ( branch ) : 4 ctx
1027 dirty = git . dirty_paths ( root ) 3 ctx
1030 " --from-main starts a scratch branch at this commit, and the working "
1031 f " tree has changes: { ' , ' . join ( dirty ) } ; commit or discard them first "
1033 origin = branch or git . head_sha ( root ) 2 ctx
1034 scratch = f " chore/loop- { datetime . now ( UTC ) : %Y%m%dT%H%M%SZ } " 2 ctx
1035 git . create_branch ( root , scratch ) 2 ctx
1036 where = f " ' { branch } ' " if branch else " a detached HEAD " 2 ctx
1037 print ( f " from main: left { where } for { scratch } at { git . head_sha ( root ) [ : 12 ] } " ) 2 ctx
1041 _leave_scratch ( root , origin , scratch , branch ) 2 ctx
1044 def _leave_scratch ( root : Path , origin : str , scratch : str , branch : str ) - > None : 8 ctx
1045 """Return *root* to *origin*; *scratch* goes when it gained nothing."""
1046 if git . current_branch ( root ) != scratch : 1046 ↛ 1047line 1046 didn't jump to line 1047 because the condition on line 1046 was never true 2 ctx
1048 f " from main: the checkout left { scratch } during the pass; "
1052 if not git . is_clean ( root ) : 1052 ↛ 1053line 1052 didn't jump to line 1053 because the condition on line 1052 was never true 2 ctx
1053 print ( f " from main: the tree has changes, so { scratch } stays checked out " )
1055 gained = git . commits_since ( root , origin ) 2 ctx
1056 if branch : 1056 ↛ 1059line 1056 didn't jump to line 1059 because the condition on line 1056 was always true 2 ctx
1057 git . switch ( root , branch ) 2 ctx
1059 git . detach ( root , origin )
1060 back = branch or origin [ : 12 ] 2 ctx
1063 f " from main: back on { back } ; { scratch } holds { gained } commit(s) and stays "
1066 git . delete_branch ( root , scratch ) 1 ctx
1067 print ( f " from main: back on { back } ; { scratch } deleted " ) 1 ctx
1070 def _publish_dev_wheels ( kind : str , stack : Sequence [ str ] = ( ) ) - > dict [ str , str ] : 8 ctx
1071 """Publish the workspace's dev wheels to the loop's registry; the pins.
1073 The loop installs the workshop being edited, so every pass
1074 publishes fresh dev wheels first: a lock pinned to an older dev
1075 version would test yesterday's code with today's templates. The
1076 dev act is idempotent at a given commit, and a re-publish of the
1077 same version walks past. A dirty tree is the exception: its dev
1078 version is the same for every edit, so the wheels it published
1079 before are dropped first, and the pass installs the tree as it is
1080 now. Returns the published versions by distribution name, for the
1081 loop's lock to pin exactly.
1083 from livery . footman import run 2 ctx
1084 from livery . workshop . _extensions import workspace_root 2 ctx
1085 from livery . workshop . _packages import discover_packages 2 ctx
1087 root = workspace_root ( ) 2 ctx
1088 if root is None : 1088 ↛ 1089line 1088 didn't jump to line 1089 because the condition on line 1088 was never true 2 ctx
1089 fail ( " no workspace: no workshop.toml above the working directory " )
1090 require_dev_branch ( root ) 2 ctx
1091 _ , token = _dev_forge ( kind ) 2 ctx
1092 packages = { package . member : package for package in discover_packages ( root ) } 2 ctx
1093 changed , pinned = _dev_split ( root , stack ) 2 ctx
1094 released = { packages [ member ] . name : version for member , version in pinned . items ( ) } 2 ctx
1095 for member , version in pinned . items ( ) : 2 ctx
1097 f " { member } : nothing unreleased since { version } ; the loop pins the release "
1099 if released : 1099 ↛ 1107line 1099 didn't jump to line 1107 because the condition on line 1099 was always true 2 ctx
1100 purged = _purge ( 2 ctx
1101 kind , os . environ . get ( _lane ( kind ) . url_var , " " ) , token , names = released
1104 f " registry: { len ( purged ) } stale rehearsal release(s) of the pinned "
1105 " member(s) dropped "
1107 if changed and not git . is_clean ( root ) : 2 ctx
1108 purged = _purge ( 1 ctx
1110 os . environ . get ( _lane ( kind ) . url_var , " " ) ,
1112 names = { packages [ member ] . name for member in changed } ,
1115 f " registry: { len ( purged ) } dev wheel(s) of the dirty tree dropped, "
1116 " so this pass installs the tree as it is now "
1118 if changed : 1118 ↛ 1130line 1118 didn't jump to line 1130 because the condition on line 1118 was always true 2 ctx
1120 # The runner under its own name: a branded instance is not
1121 # called `fm`, and a literal would spawn nothing there.
1122 [ footman . prog ( ) , " --yes " , " workflow.release " , * changed ] ,
1124 # The whole environment, extended: env= replaces, and a bare
1125 # pair would strip PATH from under the child fm.
1126 env = child_environment (
1127 PYTHON_PUBLISH_INDEX = _lane ( kind ) . publish ( ) , UV_PUBLISH_TOKEN = token
1130 pins = _dev_pins ( root , git . head_sha ( root ) , tuple ( changed ) ) | released 2 ctx
1131 print ( " dev wheels: published to the loop ' s registry " ) 2 ctx
1136 kind : str , url : str , token : str , * , names : Collection [ str ] | None = None
1138 """Drop the loop's packages from the registry at *url*: every one, or *names*.
1140 Gitea keeps them under the owner, GitLab under the project.
1142 from livery . forge . _registry import purge_gitlab_packages , purge_packages 5 ctx
1144 project = f " { E2E_OWNER } / { E2E_REPO } " 5 ctx
1145 if names is None : 5 ctx
1146 if kind == " gitlab " : 1146 ↛ 1147line 1146 didn't jump to line 1147 because the condition on line 1146 was never true 3 ctx
1147 return purge_gitlab_packages ( url , project , token = token )
1148 return purge_packages ( url , E2E_OWNER , token = token ) 3 ctx
1149 if kind == " gitlab " : 3 ctx
1150 return purge_gitlab_packages ( url , project , token = token , names = names ) 1 ctx
1151 return purge_packages ( url , E2E_OWNER , token = token , names = names ) 2 ctx
1160 wait : float = 120.0 ,
1161 kind : str = " gitea " ,
1163 """Delete the loop's repository, its registry releases, and *root*; the lines.
1165 Refuses while *root* holds commits its origin has not seen, since
1166 the repository they would land in is about to go. A repository or
1167 a release already gone is not an error: the next birth wants them
1168 absent, and a re-run of the reset is the recovery procedure. A
1169 delete the forge answers too slowly for the client completes on
1170 the server anyway, so the reset waits up to *wait* seconds for
1171 the repository to be gone before it refuses.
1173 if ( root / " .git " ) . is_dir ( ) : 2 ctx
1174 unpushed = _unpushed_commits ( root ) 1 ctx
1176 listed = " \n " . join ( f " { line } " for line in unpushed ) 1 ctx
1178 f " { root } holds commits its origin has not seen: \n { listed } \n "
1179 " push or discard them before starting over "
1181 lines : list [ str ] = [ ] 2 ctx
1183 lane . delete_repo ( E2E_OWNER , E2E_REPO ) 2 ctx
1184 except ForgeError as error : 1 ctx
1185 if not _gone_within ( lane , wait ) : 1 ctx
1186 raise ForgeError ( 1 ctx
1187 f " { E2E_OWNER } / { E2E_REPO } is still on the dev forge after the "
1188 f " delete ' s wait: { error } "
1191 f " deleted { E2E_OWNER } / { E2E_REPO } on the dev forge (the delete "
1192 " outran the client ' s wait and finished on the server) "
1195 lines . append ( f " deleted { E2E_OWNER } / { E2E_REPO } on the dev forge " ) 1 ctx
1196 purged = _purge ( kind , url , token ) 2 ctx
1198 f " purged { len ( purged ) } release(s) from the registry "
1199 + ( f " : { ' , ' . join ( purged ) } " if purged else " " )
1201 if root . exists ( ) : 2 ctx
1203 lines . append ( f " removed { root } " ) 1 ctx
1207 def _gone_within ( lane : Forge , wait : float ) - > bool : 8 ctx
1208 """Whether the loop's repository is gone from the forge within *wait* seconds."""
1210 def gone ( ) - > bool | Pending : 1 ctx
1211 return True if lane . get_repo ( E2E_OWNER , E2E_REPO ) is None else Pending ( ) 1 ctx
1217 subject = " the loop ' s repository " ,
1223 except FollowTimedOut : 1 ctx
1227 def _rmtree ( path : Path ) - > None : 8 ctx
1228 """Remove *path* whole; git's pack files are read-only, which Windows honours.
1230 A file that goes between the walk and its chmod is left to the
1231 removal: git's background maintenance drops its lock under
1232 ``.git/objects`` while a fresh clone is being torn down.
1236 for entry in path . rglob ( " * " ) : 2 ctx
1237 if entry . is_file ( ) and not entry . is_symlink ( ) : 2 ctx
1239 entry . chmod ( entry . stat ( ) . st_mode | stat . S_IWRITE ) 2 ctx
1240 except FileNotFoundError : 1 ctx
1242 shutil . rmtree ( path ) 2 ctx
1245 def _origin_main ( root : Path ) - > str : 8 ctx
1246 """The commit origin's main is at, asked of origin; empty when it cannot say."""
1248 return git . ls_remote ( root , " refs/heads/main " ) . get ( " refs/heads/main " , " " )
1249 except git . GitError :
1253 def _unpushed_commits ( root : Path ) - > list [ str ] : 8 ctx
1254 """The commits on any local branch of *root* that its origin does not hold."""
1256 git . fetch ( root ) 1 ctx
1257 except git . GitError :
1258 return [ ] # no reachable origin: nothing there could hold them anyway
1259 return git . unpushed ( root ) 1 ctx
1266 stack : Sequence [ str ] = ( ) ,
1267 driver : Path | None = None ,
1269 """Birth or resume the loop's workspace; the root it lives at.
1271 ``fm new.project`` owns the whole half: seeds, git, repository,
1272 protection, and the setup pull request. It runs as a child of the
1273 pass, this interpreter's own footman with the pass's environment:
1274 a task run in-process starts from the run's pinned environment,
1275 and the pass's own settings, its unsigned commits, would never
1276 reach the birth's git. A workspace already there is resumed, so
1277 this is the recovery procedure too. *index*, when given, is
1278 searched before any other index the environment names
1279 ([livery.workshop._e2e._dev_index][]); *stack*, when given, is the
1280 extensions the workspace lists instead of the stock list, which the
1281 birth takes through ``--extensions``. The verb
1282 runs from *driver*, the checkout running the pass, whose own project
1283 mounts the workshop being edited, so a bare runner needs nothing
1284 self-added and the birth runs this checkout's code; the folder is
1285 then absolute, and the verb hands the finish to the newborn's own
1286 runner. Without a driver the machine's footman answers from the
1291 home = _loop_home ( kind ) 4 ctx
1292 env = child_environment ( ) 4 ctx
1294 env [ " UV_INDEX " ] = " " . join ( filter ( None , ( index , os . environ . get ( " UV_INDEX " ) ) ) ) 1 ctx
1295 home . mkdir ( parents = True , exist_ok = True ) 4 ctx
1296 # A workspace already there is a birth to resume: the verb refuses
1297 # to start a second one in its folder.
1298 resume = [ " --resume " ] if ( home / E2E_REPO / " workshop.toml " ) . is_file ( ) else [ ] 4 ctx
1299 result = footman . run ( 4 ctx
1306 str ( home / E2E_REPO ) if driver is not None else E2E_REPO ,
1308 f " --owner= { E2E_OWNER } " ,
1309 f " --url= { _lane ( kind ) . alias } " ,
1310 " --description=The workshop ' s local CI loop. Scratch; recreated freely. " ,
1311 * ( [ f " --extensions= { ' , ' . join ( stack ) } " ] if stack else [ ] ) ,
1314 cwd = driver if driver is not None else home ,
1319 print ( result . stdout . rstrip ( " \n " ) ) 4 ctx
1320 if result . code != 0 : 1320 ↛ 1321line 1320 didn't jump to line 1321 because the condition on line 1320 was never true 4 ctx
1321 fail ( f " the loop ' s birth exited { result . code } : \n { result . stderr } " )
1322 return home / E2E_REPO 4 ctx
1325 def _enable_steps ( contract_text : str , steps : tuple [ str , . . . ] ) - > str : 8 ctx
1326 """*contract_text* with a table turning on each of *steps* it does not have yet.
1328 A step is ``<phase>.<step>``, and its table is
1329 ``[phases.<phase>.<step>] enabled = true``, the root contract's
1330 spelling for a step its extension declares off.
1332 for name in steps : 4 ctx
1333 phase , _ , step = name . partition ( " . " ) 1 ctx
1334 table = f " [phases. { phase } . { step } ] " 1 ctx
1335 if table in contract_text : 1 ctx
1337 contract_text = ( 1 ctx
1338 contract_text . rstrip ( " \n " )
1339 + f " \n \n # The { name } step, declared off, turned on for the pass. \n "
1341 + " enabled = true \n "
1343 return contract_text 4 ctx
1346 def _has_remote ( root : Path ) - > bool : 8 ctx
1347 """Whether the loop's workspace at *root* has its forge remote."""
1348 return git . has_remote ( root ) 2 ctx
1351 def _authenticate_remote ( root : Path , token : str , kind : str = " gitea " ) - > None : 8 ctx
1352 """Embed the lane token in the scratch workspace's remote.
1354 Birth writes a credential-free remote by design and a human's
1355 pushes ride their credential helper; the loop is automation on a
1356 scratch workspace, so the token rides the remote URL instead.
1357 The URL is a [livery.footman.Secret][]: a profile trace and every
1358 other place a command line is shown carry ``***`` in its place,
1359 and git alone receives the value. Gitea validates the token and
1360 ignores the username (measured), and ``oauth2`` is the
1361 conventional stand-in.
1363 bare = _lane ( kind ) . alias . removeprefix ( " http:// " ) 3 ctx
1364 url = footman . Secret ( f " http://oauth2: { token } @ { bare } / { E2E_OWNER } / { E2E_REPO } .git " ) 3 ctx
1366 git . set_remote_url ( root , " origin " , url ) 3 ctx
1367 except git . GitError as error :
1371 def _lock_pins ( root : Path , pins : dict [ str , str ] ) - > None : 8 ctx
1372 """Lock the loop onto exactly the dev wheels this pass published.
1374 The dev number counts commits since the release tag, so a longer
1375 branch publishes a higher number and a lock left to upgrade
1376 freely keeps resolving that branch's wheels (measured: the loop
1377 ran one branch's emitter under another branch's wheels). The
1378 pins name the four versions outright; everything else keeps its
1381 import livery . toolroom . tools as toolroom
1383 args = [ f " --upgrade-package= { name } == { version } " for name , version in pins . items ( ) ]
1384 result = toolroom . uv . opts ( cwd = root , nofail = True ) ( " lock " , * args )
1385 if result . code != 0 :
1387 f " uv lock in the loop workspace exited { result . code } : "
1388 f " \n { result . stdout } { result . stderr } "
1392 def _eat_dev_wheels ( 8 ctx
1394 pins : dict [ str , str ] ,
1395 kind : str = " gitea " ,
1397 enabled : tuple [ str , . . . ] = ( ) ,
1399 """Point the workspace at this pass's dev wheels; the pushed head sha.
1401 The registry joins the contract, the lock pins the wheels the
1402 pass just published, and only then does the workspace re-render
1403 through its own fm, so the files the runner executes come from
1404 the templates and the emitter under test. Measured necessity: a
1405 released workshop predating the emitted verbs fails the docs job
1406 with "no task named", and a render before the re-lock ships the
1407 previous pass's workflows. The loop's fm then writes the tool lock
1408 against the contract the wiring edited, since CI's setup refuses a
1409 lock the contract has moved past. *enabled* names the steps the
1410 contract turns on, each at its own address, the steps the extension
1411 under test declares off. Idempotent: an already-wired workspace
1414 from livery . workshop . _new_project import _SETUP_BRANCH 3 ctx
1416 # main is protected by the birth's own assertion, so the wiring
1417 # rides the setup branch and its pull request proves the gate.
1418 # The branch is pass-owned: rebuilt from current main every
1419 # time, because a reused branch atop stale bases conflicts with
1420 # the very squashes it produced (measured: green statuses,
1421 # mergeable false, the merge API answering 'try again later'
1423 _fresh_branch ( root , _SETUP_BRANCH ) 3 ctx
1424 lane = _lane ( kind ) 3 ctx
1425 host_url = os . environ . get ( lane . url_var , " " ) 3 ctx
1426 contract = root / " workshop.toml " 3 ctx
1427 if contract . is_file ( ) : 1427 ↛ 1431line 1427 didn't jump to line 1431 because the condition on line 1427 was always true 3 ctx
1428 body = contract . read_text ( " utf-8 " ) 3 ctx
1429 if host_url and host_url in body : 1429 ↛ 1430line 1429 didn't jump to line 1430 because the condition on line 1429 was never true 3 ctx
1430 contract . write_text ( body . replace ( host_url , lane . alias ) , " utf-8 " )
1431 loop_index , loop_publish = lane . index ( ) , lane . publish ( ) 3 ctx
1432 # The registry lives in the contract, and the template renders it
1433 # into pyproject from there: every re-render preserves the wiring
1434 # (a roster change re-renders pyproject too, and an unwired
1435 # render re-locks the workshop back to the released index).
1436 contract_file = root / " workshop.toml " 3 ctx
1437 original = contract_file . read_text ( " utf-8 " ) 3 ctx
1438 contract_text = original 3 ctx
1439 # No prerelease declaration: uv's default admits a prerelease
1440 # where only prereleases exist or a requirement names one, and
1441 # the first-index strategy serves the workshop from the loop
1442 # index alone, so the dev wheels resolve with nothing declared
1443 # (measured). A global "allow" is the measured trap: it resolved
1444 # mkdocs 2.0.dev3 from PyPI and the docs job lost
1445 # mkdocs.exceptions. The heal below removes any mode an earlier
1447 if " [registries.python] " not in contract_text : 3 ctx
1448 contract_text = ( 3 ctx
1449 contract_text . rstrip ( " \n " )
1450 + " \n \n # The loop eats the workshop ' s dev wheels from the local \n "
1451 + " # registry; the compose hostname is true on both sides, \n "
1452 + " # the host through its /etc/hosts alias. The publish base \n "
1453 + " # is where the release wave uploads; without it the wave \n "
1454 + " # refuses rather than default an upload endpoint. \n "
1455 + " [registries.python] \n "
1456 + f ' url = " { loop_index } " \n '
1457 + f ' publish = " { loop_publish } " \n '
1459 elif f ' publish = " { loop_publish } " ' not in contract_text : 1459 ↛ 1460line 1459 didn't jump to line 1460 because the condition on line 1459 was never true 1 ctx
1460 contract_text = contract_text . replace (
1461 f ' url = " { loop_index } " \n ' ,
1462 f ' url = " { loop_index } " \n publish = " { loop_publish } " \n ' ,
1465 contract_text = re . sub ( r ' prerelease = " [^ " ]* " \ n ' , " " , contract_text ) 3 ctx
1466 if " [docs] " not in contract_text and " docs " in _listed_extensions ( root ) : 1466 ↛ 1472line 1466 didn't jump to line 1472 because the condition on line 1466 was never true 3 ctx
1467 # The loop builds the site for real and publishes nowhere:
1468 # the runner container has no docker, and the release act
1469 # needs main green (an undeclared seam defaults to the forge
1470 # kind's, container on gitea, which dies on the missing
1473 contract_text . rstrip ( " \n " )
1474 + " \n \n # The site builds for real; nothing serves it here. \n "
1476 + ' publish = " none " \n '
1478 if " python-versions " not in contract_text : 3 ctx
1479 # The fast shape: one python per point, the loop's whole
1480 # matrix; livery's own contract keeps the derived pair.
1481 marker = " \n [ci] \n " 3 ctx
1482 if marker not in contract_text : 1482 ↛ 1483line 1482 didn't jump to line 1483 because the condition on line 1482 was never true 3 ctx
1484 " the loop ' s contract has no [ci] table to declare its "
1485 " python on; birth seeds one, so this workspace was not "
1488 contract_text = contract_text . replace ( 3 ctx
1489 marker , marker + ' python-versions = [ " 3.14 " ] \n affected-legs = true \n ' , 1
1491 if CURRENT . label != " ubuntu-latest " : 3 ctx
1492 # The environment's runner answers to its own label, so the
1493 # workspace names it: the check legs run there, and the wheels
1495 contract_text = contract_text . replace ( 1 ctx
1496 ' runners = [ " ubuntu-latest " ] ' , f ' runners = [ " { CURRENT . label } " ] ' , 1
1498 if " speed-marks " not in contract_text : 3 ctx
1499 # Seeded on its own: an adopted loop born before the key
1500 # exists keeps its contract, and the judge stays off without
1501 # it, which the scoped-leg proof pins.
1502 contract_text = contract_text . replace ( 3 ctx
1503 " \n [ci] \n " , " \n [ci] \n speed-marks = true \n " , 1
1505 if re . search ( r " ^shards *= " , contract_text , re . MULTILINE ) is None : 3 ctx
1506 # The check leg runs as shards on the environment's runner, the
1507 # one `[ci] runners` names, so every pass proves the slice, the
1508 # fold and the durations row; a contract that declares a count
1510 contract_text = contract_text . replace ( 3 ctx
1511 " \n [ci] \n " , f ' \n [ci] \n shards = {{ " { CURRENT . label } " = { SHARDS } }} \n ' , 1
1513 if " host-allowed " not in contract_text : 3 ctx
1514 # The allowance for the build tools: a runner with cmake and
1515 # ninja on PATH serves them from the host, one without takes
1516 # the store's, and the sync says which. The loop's container
1517 # runner has neither, so the pass proves the store's path.
1518 marker = " \n [toolroom] \n " 3 ctx
1519 if marker not in contract_text : 1519 ↛ 1520line 1519 didn't jump to line 1520 because the condition on line 1519 was never true 3 ctx
1521 " the loop ' s contract has no [toolroom] table to allow host "
1522 " tools in; birth seeds one, so this workspace was not "
1525 contract_text = contract_text . replace ( 3 ctx
1526 marker , marker + ' host-allowed = [ " cmake " , " ninja " ] \n ' , 1
1528 if " [[ci.schedule]] " not in contract_text : 3 ctx
1529 # The schedule seam's first entry: the nightly point verifies
1530 # the member's released wheel, so a dispatched nightly proves
1531 # a task scheduled through the contract with no YAML change.
1532 contract_text = ( 3 ctx
1533 contract_text . rstrip ( " \n " )
1534 + " \n \n # The nightly point verifies the released member. \n "
1535 + " [[ci.schedule]] \n "
1536 + ' point = " nightly " \n '
1537 + f ' task = " { VERIFY_TASK } " \n '
1538 + ' args = [ " loop-echo " , " --python= {python} " ] \n '
1540 # An adopted loop keeps the entry its birth wrote: the entry's task
1541 # is set to the verb that verifies a release, whatever it named.
1542 contract_text = re . sub ( 3 ctx
1543 r ' task = " release \ .[a-z-]+ " \ nargs = \ [ " loop-echo " ' ,
1544 f ' task = " { VERIFY_TASK } " \n args = [ " loop-echo " ' ,
1547 contract_text = _enable_steps ( contract_text , enabled ) 3 ctx
1548 if contract_text != original : 3 ctx
1549 contract_file . write_text ( contract_text , " utf-8 " ) 3 ctx
1550 # Birth's pyproject predates the registry in the contract, and the
1551 # lock below must already read the loop index to find the dev
1552 # wheels, before the loop's own fm can run them. The pass's own
1553 # workshop renders it, the code the dev wheels are built from, as
1554 # it rendered the birth. From nothing: an edit an earlier pass
1555 # committed would be a local override the render keeps and drift
1557 ( root / " pyproject.toml " ) . unlink ( missing_ok = True ) 3 ctx
1558 _render_with_the_pass ( root ) 3 ctx
1559 # Lock first, render second: the loop's fm syncs its venv from
1560 # the lock, so the render runs the workshop this pass published,
1561 # and the workflows it emits are the emitter under test. The
1562 # render may rewrite pyproject (the registry wiring, the roster),
1563 # so the lock settles on the same pins once more afterwards; an
1564 # unchanged pyproject makes that a no-op.
1565 _lock_pins ( root , pins ) 3 ctx
1566 _loop_fm ( root , " drift.check " , " --fix " ) 3 ctx
1567 # The tool lock follows the contract as the wiring left it: an
1568 # allowance above joins its tool's entry, so a lock the birth wrote
1569 # before it moves, and CI's setup (`sync --locked`) refuses a lock
1570 # that would move. The push below skips the lock check `fm submit`
1571 # makes, so the wiring writes the lock itself.
1572 _loop_fm ( root , " toolroom.lock " ) 3 ctx
1573 _lock_pins ( root , pins ) 2 ctx
1574 # Cleanliness is the truth, not this run's edits: a resumed
1575 # half-wired workspace still commits and pushes here.
1576 if git . is_clean ( root ) : 1576 ↛ 1577line 1576 didn't jump to line 1577 because the condition on line 1576 was never true 2 ctx
1577 print ( " dev wheels: already wired " )
1579 git . commit_all ( 2 ctx
1581 " chore: the loop eats the dev wheels \n \n The registry index "
1582 " joins uv ' s config on the compose hostname, true on both "
1583 " sides, and the lock pins the workshop ' s own dev wheels, "
1584 " so the installed workshop matches the emitter that "
1585 " rendered these workflows. " ,
1587 # Force: the branch is rebuilt from main each pass, so the
1588 # remote's copy is always superseded, like everything scratch.
1589 # The head this push supersedes keeps its runs moving with
1590 # nothing left to read them: they are cancelled after the push.
1593 previous = git . remote_head ( root , _SETUP_BRANCH ) 2 ctx
1594 except Exception : # no such branch on origin yet
1596 git . push_force ( root , _SETUP_BRANCH ) 2 ctx
1597 if previous and previous != git . head_sha ( root ) : 1597 ↛ 1598line 1597 didn't jump to line 1598 because the condition on line 1597 was never true 2 ctx
1598 from livery . workshop . _ci_tasks import cancel_superseded_runs
1600 forge_lane , _ = _dev_forge ( kind )
1601 for line in cancel_superseded_runs (
1602 forge_lane . repository ( E2E_OWNER , E2E_REPO ) , previous
1605 print ( " dev wheels: wired and pushed " ) 2 ctx
1606 return git . head_sha ( root ) 2 ctx
1609 def _runs_followed ( 8 ctx
1611 read : Callable [ [ tuple [ Run , . . . ] ] , _A | Pending ] ,
1617 timed_out : Callable [ [ Pending ] , str ] ,
1619 """Poll the runs (of *head_sha*, or all) until *read* answers from them.
1621 A loaded local forge answers a runs listing in minutes, and the
1622 client's timeout is shorter: an unreadable poll is retried as the
1623 ``ci`` verbs retry theirs, and only a spent budget or the deadline
1624 is the verdict, each failing with its words. *read* answers a
1625 pending whose key says what it still waits for; at the deadline
1626 *timed_out* turns the last one into the failure's words.
1631 lambda : read ( repo . checks . runs ( head_sha = head_sha ) ) ,
1637 except ForgeUnreachable as exc : 1 ctx
1638 fail ( exc . line . strip ( ) )
1639 except FollowTimedOut as exc : 1 ctx
1640 fail ( timed_out ( exc . last ) ) 1 ctx
1643 def _watch_latest ( kind : str , workflow : str , * , timeout : float = 900.0 ) - > None : 8 ctx
1644 """Follow the newest run of *workflow* to its verdict; red fails verbatim."""
1645 forge , _ = _dev_forge ( kind )
1646 repo = forge . repository ( E2E_OWNER , E2E_REPO )
1648 def newest_completed ( listed : tuple [ Run , . . . ] ) - > Run | Pending :
1649 runs = [ run for run in listed if run . workflow . endswith ( workflow ) ]
1650 latest = max ( runs , key = lambda run : run . id , default = None )
1651 if latest is not None and latest . status == " completed " :
1653 return Pending ( key = " pending " )
1655 latest = _runs_followed (
1658 subject = f " { workflow } ' s runs " ,
1661 timed_out = lambda _last : (
1662 f " { workflow } did not complete within { timeout : .0f } s: "
1663 f " { repo . web_url ( ) } /actions "
1666 if latest . conclusion != " success " :
1668 f " { workflow } run { latest . id } ended { latest . conclusion } : "
1669 f " { repo . web_url ( ) } /actions/runs/ { latest . id } "
1671 print ( f " { workflow : <14 } { latest . conclusion } " )
1676 repo : Repository , runs : tuple [ Run , . . . ] , * , branch : str = " "
1678 """One line per run; red fails with every red run named.
1680 A failed run is red. A cancelled run is red too, unless a twin
1681 for the same head took over and completed green, in which case
1682 the twin's verdict stands and the line says so; a successor for a
1683 moved head means the watched sha is no longer the branch's and is
1684 named as red, since the loop watches a sha of its own. A
1685 cancellation nobody took over stays red rather than quietly
1688 from livery . workshop . _runs import successor 5 ctx
1690 lines : list [ str ] = [ ] 5 ctx
1691 failed : list [ str ] = [ ] 5 ctx
1692 for run in runs : 5 ctx
1693 verdict : str = run . conclusion or run . status 5 ctx
1694 if run . conclusion == " cancelled " : 5 ctx
1695 found = successor ( repo , run , branch = branch ) 3 ctx
1696 if found is None : 3 ctx
1697 verdict = " cancelled; no newer run for its head is known " 1 ctx
1698 failed . append ( run . workflow ) 1 ctx
1699 elif found . same_head and found . run . conclusion == " success " : 2 ctx
1701 f " cancelled, superseded by run { found . run . id } for the same "
1704 elif found . same_head : 2 ctx
1706 f " cancelled, superseded by run { found . run . id } for the same head "
1707 f " ( { found . run . conclusion or found . run . status } ) "
1709 failed . append ( run . workflow ) 1 ctx
1712 f " cancelled, superseded by run { found . run . id } for the moved head "
1713 f " { found . run . head_sha [ : 12 ] } ; the watched sha is no longer "
1716 failed . append ( run . workflow ) 1 ctx
1717 elif run . conclusion == " failure " : 3 ctx
1718 failed . append ( run . workflow ) 3 ctx
1719 lines . append ( f " { run . workflow : 14 } { verdict } " ) 5 ctx
1721 names = " , " . join ( failed ) 5 ctx
1722 fail ( f " red runs on the loop: { names } ; logs: { repo . web_url ( ) } /actions " ) 5 ctx
1726 def _jobs_settled ( repo : Repository , run : Run , * , timeout : float = 600.0 ) - > None : 8 ctx
1727 """Wait until every job of *run* has completed.
1729 A job still moving past *timeout* seconds fails, named.
1732 def settled ( ) - > bool | Pending : 2 ctx
1734 job . name for job in repo . checks . jobs ( run . id ) if job . status != " completed "
1736 if not moving : 1736 ↛ 1738line 1736 didn't jump to line 1738 because the condition on line 1736 was always true 2 ctx
1739 f " waiting for { moving [ 0 ] } of run { run . id } before its re-run " ,
1740 key = " , " . join ( moving ) ,
1747 subject = f " the jobs of run { run . id } " ,
1752 except ForgeUnreachable as exc :
1753 fail ( exc . line . strip ( ) )
1754 except FollowTimedOut as exc :
1756 f " run { run . id } ended failure but { exc . last . key } still "
1757 f " moved { timeout : .0f } s later; the re-run would race it "
1761 def _retry_red_once ( repo : Repository , runs : tuple [ Run , . . . ] ) - > list [ str ] : 8 ctx
1762 """Re-run the failed jobs of every red run in *runs*; the runs re-queued.
1764 The loop's runner has failed a job on a build that left nothing
1765 and passed the same job on the re-run, so a red run gets one more
1766 attempt before it is judged. Returns the workflows re-run, empty
1767 when nothing was red.
1769 retried : list [ str ] = [ ] 3 ctx
1770 for run in runs : 3 ctx
1771 if run . conclusion != " failure " : 3 ctx
1773 # A job of the old attempt still running would collect the new
1774 # attempt's halves: the re-run waits until every job has
1775 # completed, naming the one it waits on.
1776 _jobs_settled ( repo , run ) 2 ctx
1777 # The re-run keeps the latest attempt's logs alone, so the first
1778 # attempt's failure is said here or nowhere.
1779 print ( red_jobs_text ( repo , run ) ) 2 ctx
1780 repo . checks . rerun ( run . id , failed_only = True ) 2 ctx
1781 print ( f " re-running { run . workflow } (run { run . id } ) once: it ended failure " ) 2 ctx
1782 retried . append ( run . workflow ) 2 ctx
1791 timeout : float = 900.0 ,
1792 require : tuple [ str , . . . ] = ( ) ,
1794 interval : float = 5.0 ,
1796 """Follow *sha*'s runs to their verdicts; red fails verbatim after one re-run.
1798 The runs judged are the ones this pass caused: every run the
1799 commit's own events started, and the dispatched runs *require*
1800 names. A run dispatched at the same commit by something else (the
1801 merge point re-dispatching a wave that already failed there) is
1802 named once and left to the scenario that owns it, so a birth is
1803 never judged by a wave it did not cause. *require* names
1804 workflows that must appear before the wait ends: a workflow
1805 triggered by the push registers its run a beat after the others,
1806 and a watch that settles on the early arrivals would call the
1807 commit green while the required one is still unstarted. A run
1808 that ended failure is re-run once and followed again; red twice
1811 forge , _ = _dev_forge ( kind ) 2 ctx
1812 repo = forge . repository ( E2E_OWNER , E2E_REPO ) 2 ctx
1813 retried = False 2 ctx
1814 foreign : set [ int ] = set ( ) 2 ctx
1816 def own ( runs : tuple [ Run , . . . ] ) - > tuple [ Run , . . . ] : 2 ctx
1817 mine : list [ Run ] = [ ] 2 ctx
1818 for run in runs : 2 ctx
1819 if run . event != " workflow_dispatch " or run . workflow in require : 2 ctx
1820 mine . append ( run ) 2 ctx
1821 elif run . id not in foreign : 1821 ↛ 1818line 1821 didn't jump to line 1818 because the condition on line 1821 was always true 1 ctx
1822 foreign . add ( run . id ) 1 ctx
1824 f " { run . workflow } run { run . id } is not this pass ' s: dispatched "
1825 f " at { sha [ : 10 ] } by something else; left to its own scenario "
1827 return tuple ( mine ) 2 ctx
1829 def all_completed ( runs : tuple [ Run , . . . ] ) - > tuple [ Run , . . . ] | Pending : 2 ctx
1831 mine = own ( runs ) 2 ctx
1832 present = { run . workflow for run in mine } 2 ctx
1833 if ( 1833 ↛ 1841line 1833 didn't jump to line 1841 because the condition on line 1833 was always true
1835 and all ( r . status == " completed " for r in mine )
1836 and all ( name in present for name in require )
1838 if retried or not _retry_red_once ( repo , mine ) : 2 ctx
1841 missing = " , " . join ( sorted ( set ( require ) - present ) ) 1 ctx
1842 return Pending ( key = missing ) 1 ctx
1844 def never_completed ( last : Pending ) - > str : 2 ctx
1845 waited = f " ; never appeared: { last . key } " if last . key else " "
1847 f " the loop ' s runs did not complete within { timeout : .0f } s "
1848 f " { waited } : { repo . web_url ( ) } /actions "
1851 runs = _runs_followed ( 2 ctx
1855 subject = f " { sha [ : 10 ] } ' s runs " ,
1858 timed_out = never_completed ,
1860 RUNS . count + = len ( runs ) 2 ctx
1861 for line in judge_runs ( repo , runs , branch = branch ) : 2 ctx
1865 def _align_main ( root : Path ) - > None : 8 ctx
1866 """Align the loop's main hard onto origin, superseded commits named.
1868 Origin is the loop's truth: every local byte is regenerable
1869 render output, and local main gathers aftercare commits the
1870 squashes supersede, so a fast-forward regularly cannot. What
1871 goes is printed, never silently vanished.
1873 git . fetch ( root ) 1 ctx
1874 with contextlib . suppress ( git . GitError ) : 1 ctx
1875 for line in git . oneline ( root , " origin/main..main " ) : 1875 ↛ 1876line 1875 didn't jump to line 1876 because the loop on line 1875 never started 1 ctx
1876 print ( f " superseded local commit: { line } " )
1877 git . switch ( root , " main " ) 1 ctx
1878 git . reset_hard ( root , " origin/main " ) 1 ctx
1879 # Residue too: a failed pass's branch leaves untracked leftovers
1880 # (a member directory without its contract refuses discovery).
1881 # What `fm sync` materialises survives: the venv, the stubs under
1882 # typings/ and the receipts and fragments under .workshop/, which
1883 # the gate reads and no verb between two syncs rewrites (a member
1884 # is wired with `uv sync` alone); everything else is regenerable
1886 residue = git . clean ( root , keep = KEPT_BY_SYNC , dry_run = True ) 1 ctx
1887 if residue : 1887 ↛ 1895line 1887 didn't jump to line 1895 because the condition on line 1887 was always true 1 ctx
1888 for line in residue : 1 ctx
1889 print ( f " cleaned: { line } " ) 1 ctx
1890 git . clean ( root , keep = KEPT_BY_SYNC ) 1 ctx
1891 # Local branches too: main is the loop's only durable ref, and
1892 # every other local branch is a past pass's residue (a prepared
1893 # release branch whose PR already merged makes the driver refuse
1894 # as stale). What goes is printed, never silently vanished.
1895 for name in git . local_branches ( root , " " ) : 1895 ↛ 1896line 1895 didn't jump to line 1896 because the loop on line 1895 never started 1 ctx
1898 with contextlib . suppress ( git . GitError ) :
1899 for line in git . oneline ( root , f " main.. { name } " ) :
1900 print ( f " superseded branch commit: { line } ( { name } ) " )
1901 with contextlib . suppress ( git . GitError ) :
1902 git . delete_branch ( root , name )
1903 print ( f " pruned pass-owned branch: { name } " )
1906 def _main_settled ( root : Path , kind : str ) - > None : 8 ctx
1907 """Wait until main's push run at the aligned tip has completed.
1909 The loop cuts its next branch right after a merge, and the one
1910 runner may run the new pull request's check job before main's push
1911 job has written main's record; a leg then reads a record that holds
1912 nothing and measures every suite afresh. The push run is waited for
1913 here, so what a branch's leg reuses is on the record before the leg
1914 reads it. A red push run fails the pass as any red run does.
1916 forge , _ = _dev_forge ( kind )
1917 repo = forge . repository ( E2E_OWNER , E2E_REPO )
1918 _completed_run ( repo , git . head_sha ( root ) , event = " push " )
1921 def _fresh_branch ( root : Path , name : str ) - > None : 8 ctx
1922 """A pass-owned branch, recreated from an aligned main.
1924 ``switch -C`` from a dirty tree drags or clobbers state, so the
1925 alignment and the switch are one operation here, never two calls
1926 a future edit can separate: the tree is reset to origin, cleaned,
1927 and swept of stale local branches before this one is recreated.
1930 git . switch_new ( root , name )
1933 def _render_with_the_pass ( root : Path ) - > None : 8 ctx
1934 """Render the loop's files at *root* with this pass's own workshop.
1936 A child of the pass's interpreter, as the birth is, with the uv
1937 handoff off: the loop's lock pins the workshop the loop last
1938 locked, and the handoff would run that one instead. The caller has
1939 deleted the loop's ``pyproject.toml`` so the render starts from
1940 nothing, and footman's project rung reads that file for the
1941 built-ins a project's dependencies offer, so here it offers none.
1942 The child mounts the workshop as a user built-in instead, through
1943 a config directory of its own: what a desk's global fm carries in
1944 its user config and a bare runner lacks. A failure also prints
1945 footman's ``--plugins`` listing from the same child: what mounted,
1946 and from which rung.
1949 import tempfile 1 ctx
1951 runner = [ sys . executable , " -m " , " livery.footman " ] 1 ctx
1952 with tempfile . TemporaryDirectory ( prefix = " loop-render- " ) as config : 1 ctx
1953 ( Path ( config ) / " config.toml " ) . write_text ( 1 ctx
1954 " # The pass ' s own workshop, mounted for the render alone. \n "
1955 ' [builtins] \n user = [ " livery.workshop " ] \n ' ,
1958 env = child_environment ( FOOTMAN_NO_UV = " 1 " , FOOTMAN_CONFIG_DIR = config ) 1 ctx
1959 result = footman . run ( 1 ctx
1960 [ * runner , " --yes " , " drift.check " , " --fix " ] ,
1966 print ( result . stdout . rstrip ( " \n " ) ) 1 ctx
1967 if result . code != 0 : 1 ctx
1968 plugins = footman . run ( 1 ctx
1969 [ * runner , " --plugins " ] , cwd = root , env = env , nofail = True , timeout = 120.0
1972 f " the pass ' s render of the loop exited { result . code } : "
1973 f " \n { result . stdout } { result . stderr } "
1974 f " \n footman ' s plugins in the loop: \n { plugins . stdout } { plugins . stderr } "
1979 root : Path , * args : str , timeout : float = 900.0 , nofail : bool = False
1981 """Run the loop's own fm, the dev wheels' one, inside the loop.
1983 The whole point of the substrate: the workspace under test runs
1984 the workshop being edited, so submit, release, and every other
1985 verb exercise the dev wheels end to end. ``--yes`` rides every
1986 call, because the loop is automation and silence never confirms.
1988 import livery . toolroom . tools as toolroom
1990 # The caller's VIRTUAL_ENV points at the worktree; the loop's uv
1991 # must resolve the loop's own venv, so the variable stays behind.
1992 env = { k : v for k , v in os . environ . items ( ) if k != " VIRTUAL_ENV " }
1993 # Named here, not only in the pass's environment: a write to
1994 # os.environ inside a task is the task's, and the environment this
1995 # child gets is built from the process's, so the loop's own fm
1996 # (whose submit can amend a commit) would ask a developer's signer.
1997 # No --no-sync: the wiring moves the lock onto each pass's fresh
1998 # dev wheels, and a frozen venv would keep running yesterday's
1999 # workshop under today's lock (measured: a fixed bug stayed red
2000 # in the loop while the fix sat published in the registry).
2001 result = toolroom . uv . opts ( cwd = root , nofail = True , timeout = timeout , env = env ) (
2002 " run " , " fm " , " --yes " , * args
2004 if result . code != 0 :
2006 # The evidence prints either way; the caller owns the
2007 # verdict for one bounded retry, never a silent swallow.
2009 f " the loop ' s ` { footman . prog ( ) } { ' ' . join ( args ) } ` exited "
2010 f " { result . code } : \n { result . stdout } { result . stderr } "
2014 f " the loop ' s ` { footman . prog ( ) } { ' ' . join ( args ) } ` exited "
2015 f " { result . code } : \n { result . stdout } { result . stderr } "
2020 def members_for ( names : Sequence [ str ] = ( ) ) - > tuple [ LoopMember , . . . ] : 8 ctx
2021 """The loop's members named *names*, in the loop's order; all when empty."""
2022 return tuple ( member for member in LOOP_MEMBERS if not names or member . name in names ) 3 ctx
2025 def landed_members ( named : Iterable [ str ] ) - > tuple [ str , . . . ] : 8 ctx
2026 """The loop's members a pass lands for steps naming *named*, by name, in order.
2028 A member lands for an extension a step names that its set holds and
2029 that no member whose set lies within its own holds too: the smaller
2030 member stands for that extension. loop-native's set holds
2031 loop-echo's, so a step naming python lands loop-echo alone, and one
2032 naming conan lands loop-native and loop-cpp. A pass carries the
2033 members its steps were written for, and no slower one besides.
2035 wanted = set ( named ) 2 ctx
2036 sets = { member . name : frozenset ( member . holds ( ) ) for member in LOOP_MEMBERS } 2 ctx
2037 landed : list [ str ] = [ ] 2 ctx
2038 for member in LOOP_MEMBERS : 2 ctx
2039 held = sets [ member . name ] 2 ctx
2040 own = set ( held ) 2 ctx
2041 for other , smaller in sets . items ( ) : 2 ctx
2042 if other != member . name and smaller < held : 2 ctx
2044 if own & wanted : 2 ctx
2045 landed . append ( member . name ) 2 ctx
2046 return tuple ( landed ) 2 ctx
2049 def steps_declared_off ( name : str ) - > tuple [ str , . . . ] : 8 ctx
2050 """The steps extension *name* declares ``enabled = false``, by ``<phase>.<step>``.
2052 An extension pass turns each on in the newborn's root contract, so
2053 every step of the extension under test registers and runs.
2055 from livery . workshop . _extensions import declaration 1 ctx
2057 found = declaration ( name ) 1 ctx
2058 if found is None : 1 ctx
2060 return tuple ( record . name for record in found . additions . steps if not record . enabled ) 1 ctx
2063 def extension_under_test ( name : str ) - > tuple [ tuple [ str , . . . ] , tuple [ str , . . . ] ] : 8 ctx
2064 """The list a pass births to test extension *name*, and the members it lands.
2066 The members are the loop's whose sets hold an extension *name*'s
2067 steps name, by name (`landed_members`), so each step has something
2068 of its own to judge. The list is *name* and what those members'
2069 templates need (`LoopMember.needs`), as their canonical list: a
2070 creation installs nothing, so the root lists them before the
2071 members are created, and the set takes in what each requires. The
2072 steps *name* declares off are turned on in the newborn's contract
2073 (`steps_declared_off`), so each of its steps registers.
2076 Failed: when no installed distribution declares *name*, naming
2077 the installed ones; when *name* registers no step.
2079 from livery . workshop . _extensions import declaration , installed_extensions 4 ctx
2080 from livery . workshop . _new_project import canonical_extensions 4 ctx
2082 found = declaration ( name ) 4 ctx
2083 if found is None : 4 ctx
2084 installed = " , " . join ( installed_extensions ( ) ) or " none " 1 ctx
2086 f " extension { name !r} : no installed distribution declares it; "
2087 f " the installed ones are { installed } "
2089 steps = found . additions . steps 3 ctx
2092 f " extension { name !r} registers no step: a pass would have "
2093 " nothing of its own to run "
2095 named = { extension for record in steps for extension in record . extensions } 2 ctx
2096 members = landed_members ( named ) 2 ctx
2097 needs = [ needed for member in members_for ( members ) for needed in member . needs ( ) ] 2 ctx
2098 return tuple ( canonical_extensions ( [ name , * needs ] ) ) , members 2 ctx
2101 def _ensure_members ( root : Path , members : Sequence [ str ] = ( ) ) - > None : 8 ctx
2102 """Give the loop its *members*, by name, all when empty, in one pull request.
2104 Its template's verb, ``new.package.<template>``, renders and wires
2105 each missing member, a `[release] baseline` seeds the first
2106 release's number, the nanobind member's
2107 ``[nanobind] wheel-platforms`` names the loop's one runner, and the
2108 loop's own ``fm submit --armed`` lands them together: one branch,
2109 one pull request, one gate on the runner over every kind at once
2110 (it compiles the native member's editable install), and one merge,
2111 all on the dev wheels. One pull request rather than one per member:
2112 every member edits the same rendered root files, so pull requests
2113 in flight together conflict, and landing them one after another
2114 costs a gate run and a merge each; what the one gate drops is each
2115 kind's narrowed gate and its own submit. Idempotent: a member
2116 already on main is skipped, and nothing is submitted when none is
2119 # Landed means on main: a failed pass leaves the working tree on
2120 # the feature branch with the member present, and judging that
2121 # tree would skip straight to the release act with nothing
2122 # merged. The alignment makes the glob read main's truth.
2123 _align_main ( root ) 1 ctx
2124 missing : list [ tuple [ str , str ] ] = [ ] 1 ctx
2125 for wanted in members_for ( members ) : 1 ctx
2126 if ( root / " packages " / wanted . name / " workshop.toml " ) . is_file ( ) : 1 ctx
2127 print ( f " member { wanted . name } : already landed " ) 1 ctx
2129 missing . append ( ( wanted . name , wanted . template ) ) 1 ctx
2130 if not missing : 1 ctx
2132 _fresh_branch ( root , " feat/members " ) 1 ctx
2133 for name , template in missing : 1 ctx
2134 _loop_fm ( root , f " new.package. { template } " , name ) 1 ctx
2135 member = root / " packages " / name / " workshop.toml " 1 ctx
2136 body = member . read_text ( " utf-8 " ) 1 ctx
2137 # The nanobind template names the hosted runners under
2138 # [nanobind] wheel-platforms; the loop's fleet is its one runner,
2139 # and the leg must be schedulable. Another template names none,
2140 # and nothing changes.
2141 body = body . replace ( 1 ctx
2142 ' wheel-platforms = [ " ubuntu-latest " , " macos-latest " , " windows-latest " ] ' ,
2143 f ' wheel-platforms = [ " { CURRENT . label } " ] ' ,
2145 if " [release] " not in body : 2145 ↛ 2151line 2145 didn't jump to line 2151 because the condition on line 2145 was always true 1 ctx
2148 + " \n \n [release] \n # The first release lands at the baseline. \n "
2149 + ' baseline = " 0.1.0 " \n '
2151 if name == CONTRIBUTING_MEMBER and " [[ci.point]] " not in body : 2151 ↛ 2155line 2151 didn't jump to line 2155 because the condition on line 2151 was never true 1 ctx
2152 # The member contributes a point: the loop dispatches it
2153 # by hand, so the point is proven against the real runner
2154 # rather than against the renderer's own output.
2157 + " \n \n # A point of this member ' s own, run by hand in the loop. \n "
2159 + f ' name = " { CONTRIBUTED_POINT } " \n '
2160 + ' task = " extensions " \n '
2161 # The environment's runner, as the root's runners name
2162 # it: the hosted label on the docker rig, the host
2163 # runner's own label in host mode.
2164 + f ' runners = [ " { CURRENT . label } " ] \n '
2166 member . write_text ( body , " utf-8 " ) 1 ctx
2167 # The baseline is a render input: cliff.toml was rendered before
2168 # the append, so it must settle again or the gate names it as
2170 _loop_fm ( root , " drift.check " , " --fix " ) 1 ctx
2171 names = " , " . join ( name for name , _template in missing ) 1 ctx
2172 git . commit_all ( 1 ctx
2174 f " feat: the loop ' s members \n \n { names } : born through their templates ' verbs on "
2175 " the dev wheels, with the release baseline seeded so the "
2176 " first release lands at 0.1.0. " ,
2178 # Force for the same reason the setup branch pushes force: the
2179 # branch is pass-owned, rebuilt from main every time, so the
2180 # remote's copy is always superseded.
2181 _loop_fm ( root , " submit " , " --force " , " --armed " ) 1 ctx
2182 _align_main ( root ) 1 ctx
2183 print ( f " members { names } : landed through the loop ' s own gate, one pull request " ) 1 ctx
2186 def red_jobs_text ( repo : Repository , run : Run , * , lines : int = 60 ) - > str : 8 ctx
2187 """The failed jobs of *run* with the last *lines* of each log, as text to print.
2189 A run that went red on the loop's forge is readable at its page on
2190 a desk; inside a hosted job the forge vanishes with the job, so the
2191 pass prints what the page would show. Every job that ended in
2192 failure is named with its log's tail; a run whose jobs all passed
2193 or never ran gives the header line alone.
2195 out = [ f " run { run . id } ended { run . conclusion } : { run . url or repo . web_url ( ) } " ] 3 ctx
2196 for job in repo . checks . jobs ( run . id ) : 3 ctx
2197 if job . conclusion != " failure " : 3 ctx
2199 tail = repo . checks . job_log ( job . id ) . rstrip ( " \n " ) . splitlines ( ) [ - lines : ] 3 ctx
2200 out . append ( f " { job . name } : failure; the last { len ( tail ) } line(s) of its log: " ) 3 ctx
2201 out . extend ( f " { line } " for line in tail ) 3 ctx
2202 return " \n " . join ( out ) 3 ctx
2205 def _completed_run ( 8 ctx
2210 timeout : float = 900.0 ,
2211 interval : float = 5.0 ,
2212 ) - > tuple [ Run , tuple [ Job , . . . ] ] :
2213 """The newest completed ``ci.yml`` run of *sha* for *event*, with its jobs.
2215 Waits for the run to register and complete; a run that ended
2216 failure is re-run once and waited for again, and a red run then
2217 fails verbatim, naming its page. The jobs carry their names, the
2218 check legs by their matrix display (``check (ubuntu-latest,
2219 3.14)``), so a reader looks for the prefix it needs; the logs are
2220 read per job on demand, since a job the run skipped has none to
2223 retried = False 3 ctx
2225 def newest_completed ( listed : tuple [ Run , . . . ] ) - > Run | Pending : 3 ctx
2230 if run . workflow . endswith ( " ci.yml " ) and run . event == event
2232 run = max ( runs , key = lambda run : run . id , default = None ) 3 ctx
2233 if run is not None and run . status == " completed " : 3 ctx
2234 if retried or not _retry_red_once ( repo , ( run , ) ) : 2 ctx
2237 return Pending ( key = " pending " ) 2 ctx
2239 run = _runs_followed ( 3 ctx
2243 subject = f " { sha [ : 10 ] } ' s { event } run " ,
2246 timed_out = lambda _last : (
2247 f " no completed { event } run for { sha [ : 10 ] } within { timeout : .0f } s: "
2248 f " { repo . web_url ( ) } /actions "
2251 RUNS . count + = 1 2 ctx
2252 if run . conclusion != " success " : 2 ctx
2253 print ( red_jobs_text ( repo , run ) ) 1 ctx
2255 f " run { run . id } ( { event } , { sha [ : 10 ] } ) ended { run . conclusion } : "
2256 f " { repo . web_url ( ) } /actions/runs/ { run . id } "
2258 return run , repo . checks . jobs ( run . id ) 2 ctx
2262 repo : Repository , run : Run , jobs : tuple [ Job , . . . ] , job : str , line : str
2264 """Fail unless the log of the job whose name starts with *job* carries *line*.
2266 The one read of a job's log the loop keeps: the publish job's word
2267 on whether it collected what the wheels job built has no row until
2268 conan's per-host artifact (phase 13 of the destination note), which
2269 the destination's temporary table names.
2271 found = next ( ( item for item in jobs if item . name . startswith ( job ) ) , None ) 3 ctx
2272 if found is None : 3 ctx
2273 fail ( f " run { run . id } has no { job } job: { repo . web_url ( ) } /actions/runs/ { run . id } " ) 1 ctx
2274 if line not in repo . checks . job_log ( found . id ) : 3 ctx
2276 f " run { run . id } ' s { job } job did not say { line !r} ; "
2277 f " { repo . web_url ( ) } /actions/runs/ { run . id } "
2281 def _require_task ( facts : RunFacts , prefix : str , task : str ) - > None : 8 ctx
2282 """Fail unless a job of *facts* named by *prefix* ran *task*, by its row.
2284 A matrix job is several forge jobs under one name (``nightly
2285 (3.14)``), so any one of them running the task is the proof.
2287 found = [ job for name , job in facts . jobs . items ( ) if name . startswith ( prefix ) ]
2290 f " run { facts . run } : the row names no job starting with { prefix !r} ; "
2291 f " its jobs are { ' , ' . join ( sorted ( facts . jobs ) ) or ' none ' } "
2293 if not any ( task in job . tasks for job in found ) :
2294 ran = sorted ( { t for job in found for t in job . tasks } )
2296 f " run { facts . run } : no { prefix } job ran { task } ; the row names "
2297 f " { ' , ' . join ( ran ) or ' no task ' } "
2301 def _require_scope ( 8 ctx
2306 packages : Collection [ str ] = ( ) ,
2307 composed : bool | None = None ,
2309 """Fail unless *run*'s check leg recorded *scope* over *packages*.
2311 *composed* says whether the leg must name the tree it measured from
2312 (a narrowed gate) or must not; None leaves it unjudged.
2314 leg = facts . job ( " check " )
2315 if leg . scope != scope or set ( leg . packages ) != set ( packages ) :
2317 f " run { run . id } : the check leg ' s row says { leg . scope } over "
2318 f " { sorted ( leg . packages ) or ' no package ' } , expected { scope } over "
2319 f " { sorted ( packages ) or ' no package ' } ; { run . url } "
2321 if composed is not None and bool ( leg . base_tree ) != composed :
2323 f " names base tree { leg . base_tree [ : 12 ] } "
2325 else " names no base tree "
2328 f " run { run . id } : the check leg ' s row { named } , expected "
2329 f " { ' one ' if composed else ' none ' } ; { run . url } "
2333 def _require_judged ( run : Run , facts : RunFacts , percents : Mapping [ str , float ] ) - > None : 8 ctx
2334 """Fail unless the gate job's coverage section judged exactly *percents*."""
2335 if facts . coverage != dict ( percents ) :
2337 f " run { run . id } : the gate job judged { facts . coverage } , expected "
2338 f " { dict ( percents ) } ; { run . url } "
2342 def _require_record ( 8 ctx
2348 fresh : Collection [ str ] ,
2349 carried : Collection [ str ] ,
2351 """Fail unless *base*'s record on *leg* holds the units as measured.
2353 *fresh* were measured by *run*; *carried* by another run.
2355 units = record_units ( root , base , leg )
2356 expected = set ( fresh ) | set ( carried )
2357 if set ( units ) != expected :
2359 f " run { run . id } : { base } ' s record on { leg } holds { sorted ( units ) } , "
2360 f " expected { sorted ( expected ) } "
2362 stale = [ unit for unit in fresh if units [ unit ] . run != str ( run . id ) ]
2363 remeasured = [ unit for unit in carried if units [ unit ] . run == str ( run . id ) ]
2364 if stale or remeasured :
2366 f " run { run . id } : { base } ' s record on { leg } was to measure { sorted ( fresh ) } "
2367 f " afresh and carry { sorted ( carried ) } ; measured by another run: "
2368 f " { stale } ; measured again: { remeasured } "
2372 def _require_proved ( root : Path , run : Run , * , branch : str = " " ) - > None : 8 ctx
2373 """Fail unless *run* recorded proved rows, naming *branch* when given."""
2374 rows = proved_by ( root , run . id )
2376 branches = { entry . branch for _base , _leg , _row , entry in rows if entry . branch }
2377 if branch not in branches :
2379 f " run { run . id } : proved rows name branches { sorted ( branches ) } , "
2380 f " expected { branch !r} "
2384 def _require_mark ( 8 ctx
2385 root : Path , package : str , * , value : float , kind : str , by : str = " "
2387 """Fail unless *package*'s mark is *value* of *kind*, and set by *by* when given."""
2388 current = marks ( root ) . get ( package )
2390 fail ( f " no mark on the store for { package } " )
2391 if current . value != value or current . kind != kind or ( by and current . by != by ) :
2393 f " { package } ' s mark is { current . value } ( { current . kind } by { current . by } ), "
2394 f " expected { value } ( { kind } { ' by ' + by if by else ' ' } ) "
2398 def _require_shards ( run : Run , facts : RunFacts , * , count : int , ran : bool ) - > None : 8 ctx
2399 """Fail unless *run*'s check leg is the fold of *count* shards, each with its row.
2401 The fold's row lists each shard with its job, and the forge's row of
2402 that job stands beside it. *ran* says whether the leg ran its gate:
2403 then the shards partitioned a set and ran its items; otherwise
2404 every shard skipped, so the fold names no item ran and no
2407 leg = facts . job ( " check " ) 2 ctx
2408 fold = leg . fold 2 ctx
2409 if fold is None : 2 ctx
2411 f " run { run . id } : the check leg ' s row ( { leg . leg } ) is not a fold; the "
2412 f " loop ' s contract splits the leg into { count } shards; { run . url } "
2414 labels = " , " . join ( shard . leg for shard in fold . shards ) 2 ctx
2415 if fold . count != count or len ( fold . shards ) != count : 2 ctx
2417 f " run { run . id } : the check leg ' s row folds { fold . count } shard(s) and "
2418 f " lists { len ( fold . shards ) } ( { labels or ' none ' } ), expected { count } ; "
2421 missing = [ shard . job for shard in fold . shards if shard . job not in facts . shard_jobs ] 2 ctx
2424 f " run { run . id } : the forge ' s rows of { ' , ' . join ( missing ) } are not beside "
2425 " the folded row; the collect keeps each shard ' s job with its times; "
2428 items = sum ( shard . items for shard in fold . shards ) 2 ctx
2429 if ran and ( not fold . digest or not items ) : 2 ctx
2431 f " run { run . id } : the check leg ran and its shards ( { labels } ) ran no "
2432 f " item; the fold recorded no partition; { run . url } "
2434 if not ran and ( items or fold . rows ) : 2 ctx
2436 f " run { run . id } : every shard skipped, and the fold records { items } "
2437 f " item(s) ran and { len ( fold . rows ) } durations row(s) read ( { labels } ); "
2442 def _require_durations ( root : Path , run : Run , leg : str , * , written : bool ) - > None : 8 ctx
2443 """Fail unless *run*'s durations row on *leg*'s platform is there, or is not.
2445 *written* says the gate job's collect wrote the row, naming at
2446 least one item; otherwise the leg ran no item and the series holds
2449 row = durations_row ( root , run . id , leg ) 1 ctx
2450 if written and not row . items : 1 ctx
2452 f " run { run . id } : no row { row . name } naming an item on { row . ref } ; the "
2453 " gate job ' s collect wrote no seconds per item for the leg; "
2456 if not written and row . items is not None : 1 ctx
2458 f " run { run . id } : { row . ref } holds { row . name } with { len ( row . items ) } "
2459 " item(s), and every shard skipped; a leg that ran no item leaves no "
2460 f " durations; { run . url } "
2464 def _prove_shards ( root : Path , run : Run , facts : RunFacts , * , ran : bool ) - > None : 8 ctx
2465 """Prove *run*'s check leg ran as the loop's shards and folded into one leg.
2467 The loop's contract splits its one runner's check leg into `SHARDS`
2468 shards, so every run's metrics row has the fold's row for the
2469 platform leg, with the forge's rows of the shards beside it. Where
2470 the leg ran its gate (*ran*), the shards partitioned the test files
2471 and the gate job's collect wrote the run's durations row on the
2472 platform leg's series; where every shard skipped, the fold names no
2473 item and no row is written.
2475 _require_shards ( run , facts , count = SHARDS , ran = ran ) 1 ctx
2476 leg = facts . job ( " check " ) . leg 1 ctx
2477 _require_durations ( root , run , leg , written = ran ) 1 ctx
2480 f " shards: run { run . id } ' s check leg ran as { SHARDS } shards folded into "
2481 f " { leg } ; its durations row is on the store "
2485 f " shards: run { run . id } ' s check leg skipped on every shard, folded into "
2486 f " { leg } ; no durations row written "
2490 def _units ( root : Path ) - > tuple [ list [ str ] , bool ] : 8 ctx
2491 """The newborn's units: its members' paths, and whether its own tests are one."""
2492 from livery . workshop . _packages import discover_packages , workspace_suite
2494 members = [ package . path for package in discover_packages ( root ) ]
2495 return members , workspace_suite ( root ) is not None
2498 def _require_prebuilt ( repo : Repository , run : Run , distribution : str ) - > None : 8 ctx
2499 """Fail unless the wave *run* published *distribution* from the wheels job's wheels.
2501 The wave publishes a platform-wheel member either way: from the
2502 wheels the wheels job built and handed over, or from a build of its
2503 own on the publish job's runner. The served version is the same
2504 after both. The publish job's ``prebuilt:`` line tells them apart:
2505 the wave prints it for each member a job builds before the wave
2506 whose collected ``dist/`` held what the job built, naming the job.
2507 A publish job that did not end green proves nothing, so it fails
2508 here too, naming how it ended.
2510 jobs = repo . checks . jobs ( run . id ) 3 ctx
2511 publish = next ( ( job for job in jobs if job . name . startswith ( " publish " ) ) , None ) 3 ctx
2512 if publish is not None and publish . conclusion != " success " : 3 ctx
2514 f " run { run . id } ' s publish job ended { publish . conclusion or publish . status } ; "
2515 f " { repo . web_url ( ) } /actions/runs/ { run . id } "
2522 f " prebuilt: { distribution } : the run collected what the wheels job built " ,
2525 f " release: the wave published the wheels the wheels job built for "
2526 f " { distribution } (run { run . id } ) "
2530 def _prove_verified_skip ( root : Path , kind : str ) - > None : 8 ctx
2531 """Prove main's run after the setup squash skips the gate and copies the record.
2533 The setup pull request's check leg ran the full gate, its gate
2534 job wrote the setup branch's coverage record, and its stamp put
2535 the tree on the verified record naming the branch; the squash
2536 lands the same tree on main, so main's push run finds it on the
2537 record, skips the gate, measures nothing, and its union takes
2538 every unit from the setup branch's record and copies it into
2539 main's. The rows say so: the check leg's scope is ``verified``,
2540 the tree's verified row names the setup branch, main's record
2541 holds every unit measured by another run, and the gate job judged
2542 each member; the leg's shards both skipped, folded into one leg,
2543 and no durations row was written. A skipped leg reddening the
2544 union, passing it with nothing counted, or measuring what the
2545 branch already measured is the failure this proof exists for.
2548 head = git . head_sha ( root )
2549 forge , _ = _dev_forge ( kind )
2550 repo = forge . repository ( E2E_OWNER , E2E_REPO )
2551 from livery . workshop . _new_project import _SETUP_BRANCH
2553 run , _jobs = _completed_run ( repo , head , event = " push " )
2554 facts = run_facts ( root , run . id )
2555 _require_scope ( run , facts , scope = " verified " )
2556 branch = proved_branch ( root )
2557 if branch != _SETUP_BRANCH :
2559 f " run { run . id } : main ' s tree is proved by rows naming { branch !r} , "
2560 f " expected { _SETUP_BRANCH !r} , the branch whose record main copies "
2562 # The units main's union reuses are the ones the workspace has at
2563 # this point: its members and its own tests. A fresh birth has
2564 # neither yet (the members and the tests land through their own
2565 # pull requests afterwards), and then the union has no unit and
2567 members , tests = _units ( root )
2568 units = [ * members , * ( [ " tests " ] if tests else [ ] ) ]
2569 leg = facts . job ( " check " ) . leg
2570 _require_record ( root , run , " main " , leg , fresh = ( ) , carried = units )
2571 _require_judged ( run , facts , dict . fromkeys ( members , 100.0 ) )
2572 _prove_shards ( root , run , facts , ran = False )
2574 f " verified skip: proven on main ' s run { run . id } ; the gate skipped, "
2575 f " nothing was measured, and main copied { _SETUP_BRANCH } ' s record "
2579 #: The member the loop keeps under auto-ratchet, so every pass proves
2580 #: the mark's first record, an accepted lowering, and the ratchet up.
2581 RATCHET_MEMBER = " loop-native " 8 ctx
2584 def _prepare_ratchet ( root : Path , kind : str ) - > None : 8 ctx
2585 """Put the ratchet member under auto-ratchet, then lower its mark for the proof.
2587 The member's template names no floor, so it is judged at the default
2588 floor until its contract gains ``[coverage] floor = "auto-ratchet"``,
2589 which lands through the loop's own gate: that pull request's run
2590 records the first mark, and main's run after the squash judges it;
2591 the pass waits for that run, or the accept below would be consumed
2592 there instead of by the member-only pull request. Then
2593 `fm coverage.accept` lowers the mark to 90 with a reason, so the
2594 pull request that follows judges from the accepted row and
2595 ratchets the mark back up. A refusal (a mark a pass that did not
2596 finish already lowered) is printed and the mark stands; the proof
2597 reads the same lines either way.
2599 contract = root / " packages " / RATCHET_MEMBER / " workshop.toml "
2600 body = contract . read_text ( " utf-8 " )
2601 if ' floor = " auto-ratchet " ' not in body :
2602 if " [coverage] " in body :
2604 f " { contract } : a [coverage] table the template does not write; the "
2605 " loop adds the member ' s own, with its floor the mark "
2607 _fresh_branch ( root , " chore/ratchet-member " )
2608 contract . write_text (
2610 + " \n \n [coverage] \n # The floor is the mark on the store. \n "
2611 + ' floor = " auto-ratchet " \n ' ,
2616 f " chore( { RATCHET_MEMBER } ): the member ' s floor is the mark on the "
2617 " store \n \n Under auto-ratchet the first gated run records the "
2618 " mark, and the loop proves the record, an accepted lowering, "
2619 " and the ratchet up on every pass. " ,
2621 with contextlib . suppress ( git . GitError ) :
2622 git . fetch ( root , prune = True )
2623 _loop_fm ( root , " submit " , " --force " , " --armed " )
2625 forge , _ = _dev_forge ( kind )
2626 repo = forge . repository ( E2E_OWNER , E2E_REPO )
2627 run , _jobs = _completed_run ( repo , git . head_sha ( root ) , event = " push " )
2629 f " ratchet member: { RATCHET_MEMBER } landed under auto-ratchet; "
2630 f " main ' s run { run . id } judged the first mark "
2635 f " packages/ { RATCHET_MEMBER } " ,
2637 " --reason=the loop proves an accepted lowering " ,
2641 print ( f " ratchet member: { RATCHET_MEMBER } ' s mark accepted down to 90 " )
2644 f " ratchet member: the accept was refused (exit { code } ); the mark stands "
2648 def _prove_scoped_leg ( root : Path , kind : str ) - > None : 8 ctx
2649 """Prove the scoped check leg on a member-only pull request.
2651 The loop's other pull requests all touch the root (a template's verb
2652 wires the workspace, the release stamps the manifest), so their
2653 legs pay the full gate by the affected rule. This one rewrites a
2654 test file inside ``loop-echo`` and nothing else, lands it through
2655 the loop's gate, and reads the rows: the check leg narrowed to
2656 that one member against main; the branch's record holds that
2657 member measured by this run and the others carried from main's;
2658 the gate job judged every member; the ratchet member's mark, which
2659 the pass accepted down to 90, is back at 100 by this run; the stamp
2660 composed with main's verified tree; and the leg's shards
2661 partitioned the member's test files, folded into one leg, and the
2662 run's durations row is on the store. Main's push run after the
2663 squash then skips the gate on that composed row, measures nothing,
2664 and copies the branch's record into main's. Re-run on a pass-owned
2665 branch with main's tip as the stamp, so the diff is never empty.
2667 _fresh_branch ( root , " chore/scoped-leg " )
2668 _main_settled ( root , kind )
2669 stamp = git . head_sha ( root )
2670 probe = root / " packages " / " loop-echo " / " tests " / " test_scoped_leg.py "
2672 ' " " " A member-only change: the loop proves the scoped check leg on it. " " " \n '
2674 f ' STAMP = " { stamp } " \n '
2676 " def test_the_stamp_is_a_commit(): \n "
2677 " assert len(STAMP) == 40 \n " ,
2682 " chore(loop-echo): a member-only change for the scoped leg \n \n One file "
2683 " under one member, so the check leg narrows to that member and "
2686 head = git . head_sha ( root )
2687 # The last pass's merge deleted the branch on origin, and the clone's
2688 # tracking ref still names its final commit; the forced submit pushes
2689 # with a lease on that ref, which git refuses as stale against a
2690 # branch that is gone. A pruning fetch drops the stale ref (or
2691 # refreshes it when a failed pass left the branch behind).
2692 with contextlib . suppress ( git . GitError ) :
2693 git . fetch ( root , prune = True )
2694 _loop_fm ( root , " submit " , " --force " , " --armed " )
2696 # The workspace's own tests are a unit once the tests leg landed
2697 # them, and the member's change moves their closure, so the leg
2698 # runs them too; a fresh birth has none.
2699 members , tests = _units ( root )
2700 others = [ path for path in members if path != " packages/loop-echo " ]
2701 fresh = [ " packages/loop-echo " , * ( [ " tests " ] if tests else [ ] ) ]
2702 judged = dict . fromkeys ( members , 100.0 )
2703 forge , _ = _dev_forge ( kind )
2704 repo = forge . repository ( E2E_OWNER , E2E_REPO )
2705 run , _jobs = _completed_run ( repo , head , event = " pull_request " )
2706 facts = run_facts ( root , run . id )
2707 _require_scope ( run , facts , scope = " affected " , packages = fresh , composed = True )
2708 leg = facts . job ( " check " ) . leg
2709 _require_record ( root , run , " chore/scoped-leg " , leg , fresh = fresh , carried = others )
2710 _require_judged ( run , facts , judged )
2713 f " packages/ { RATCHET_MEMBER } " ,
2718 _require_proved ( root , run , branch = " chore/scoped-leg " )
2719 _prove_shards ( root , run , facts , ran = True )
2721 " scoped leg: proven on a member-only pull request (affected: "
2722 " packages/loop-echo; the union reused the other members from main ' s "
2723 " record and wrote the branch ' s; the mark ratcheted; the proved rows "
2726 # Main's push after the squash skips the gate, measures nothing, and
2727 # copies the branch's rows and coverage record.
2728 landed = git . head_sha ( root )
2729 run , _jobs = _completed_run ( repo , landed , event = " push " )
2730 facts = run_facts ( root , run . id )
2731 _require_scope ( run , facts , scope = " verified " )
2732 branch = proved_branch ( root )
2733 if branch != " chore/scoped-leg " :
2735 f " run { run . id } : main ' s tree is proved by rows naming { branch !r} , "
2736 " expected ' chore/scoped-leg ' , the branch whose record main copies "
2744 carried = [ * members , * ( [ " tests " ] if tests else [ ] ) ] ,
2746 _require_judged ( run , facts , judged )
2747 _prove_shards ( root , run , facts , ran = False )
2749 f " composed skip: proven on main ' s run { run . id } after the member-only "
2750 " squash; nothing was measured, and main copied the branch ' s record "
2754 def _prove_unproven_push ( root : Path , kind : str ) - > None : 8 ctx
2755 """Prove main's run narrows from its own record when a squash lands a new tree.
2757 Every other squash the loop lands is a tree a pull request's run
2758 proved, so main's run skips. This branch is cut from the commit
2759 the scoped-leg branch stood on and touches one other member, so
2760 its squash onto main, which carries the scoped-leg squash already,
2761 is a tree no run proved: main's push run cannot skip, measures
2762 from the previous push's tree, narrows to the member the branch
2763 touched, reuses the other suites from main's record, and composes
2764 its stamp on that tree. A push that paid the whole gate here, or
2765 skipped, is the failure this proof exists for.
2768 _main_settled ( root , kind )
2769 before = git . head_sha ( root )
2770 git . switch_new ( root , " chore/unproven-push " , f " { before } ~1 " )
2771 probe = root / " packages " / " loop-native " / " tests " / " test_unproven_push.py "
2773 ' " " " A member-only change behind main: the loop proves a push narrows. " " " \n '
2775 f ' STAMP = " { before } " \n '
2777 " def test_the_stamp_is_a_commit(): \n "
2778 " assert len(STAMP) == 40 \n " ,
2783 " chore(loop-native): a member-only change behind main \n \n Cut from the "
2784 " commit before main ' s tip, so its squash lands a tree no run proved. " ,
2786 with contextlib . suppress ( git . GitError ) :
2787 git . fetch ( root , prune = True )
2788 _loop_fm ( root , " submit " , " --force " , " --armed " )
2790 landed = git . head_sha ( root )
2791 forge , _ = _dev_forge ( kind )
2792 repo = forge . repository ( E2E_OWNER , E2E_REPO )
2793 run , _jobs = _completed_run ( repo , landed , event = " push " )
2794 facts = run_facts ( root , run . id )
2796 run , facts , scope = " affected " , packages = [ " packages/loop-native " ] , composed = True
2798 members , tests = _units ( root )
2799 carried = [ path for path in members if path != " packages/loop-native " ]
2801 carried . append ( " tests " )
2806 facts . job ( " check " ) . leg ,
2807 fresh = [ " packages/loop-native " ] ,
2810 _require_judged ( run , facts , dict . fromkeys ( members , 100.0 ) )
2811 _require_proved ( root , run )
2812 _prove_shards ( root , run , facts , ran = True )
2814 f " unproven push: proven on main ' s run { run . id } ; the leg measured from the "
2815 " previous push ' s tree, ran loop-native alone, and the stamp composed "
2819 def _prove_prose_leg ( root : Path , kind : str ) - > None : 8 ctx
2820 """Prove a note-only pull request pays no package gate.
2822 The change is one markdown file under ``notes/`` and nothing
2823 else, landed through the loop's gate on a pass-owned branch with
2824 main's tip as the stamp so the diff is never empty. The check
2825 leg's row says nothing was affected; the branch's record holds
2826 every unit carried from main's; the gate job judged every member;
2827 the stamp composed with main's verified tree, so main's push run
2828 after the squash skips too.
2830 _fresh_branch ( root , " chore/prose-leg " )
2831 _main_settled ( root , kind )
2832 stamp = git . head_sha ( root )
2833 note = root / " notes " / " loop-prose.md "
2834 note . parent . mkdir ( exist_ok = True )
2836 " # The loop ' s prose probe \n \n A note-only change, so the check legs "
2837 f " skip their gate. \n \n Stamp: { stamp } \n " ,
2842 " docs(notes): a note-only change for the prose leg \n \n One markdown "
2843 " file under notes/, so the check leg finds nothing affected and "
2846 head = git . head_sha ( root )
2847 with contextlib . suppress ( git . GitError ) :
2848 git . fetch ( root , prune = True )
2849 _loop_fm ( root , " submit " , " --force " , " --armed " )
2851 forge , _ = _dev_forge ( kind )
2852 repo = forge . repository ( E2E_OWNER , E2E_REPO )
2853 run , _jobs = _completed_run ( repo , head , event = " pull_request " )
2854 facts = run_facts ( root , run . id )
2855 _require_scope ( run , facts , scope = " nothing " , composed = True )
2856 members , tests = _units ( root )
2857 units = [ * members , * ( [ " tests " ] if tests else [ ] ) ]
2859 root , run , " chore/prose-leg " , facts . job ( " check " ) . leg , fresh = ( ) , carried = units
2861 _require_judged ( run , facts , dict . fromkeys ( members , 100.0 ) )
2862 _prove_shards ( root , run , facts , ran = False )
2864 f " prose leg: proven on a note-only pull request (run { run . id } : the "
2865 " check leg skipped, the union reused every unit from main ' s record "
2866 " and wrote the branch ' s, the stamp composed) "
2868 landed = git . head_sha ( root )
2869 run , _jobs = _completed_run ( repo , landed , event = " push " )
2870 _require_scope ( run , run_facts ( root , run . id ) , scope = " verified " )
2871 print ( f " composed skip: proven on main ' s run { run . id } after the note-only squash " )
2874 def _prove_tests_leg ( root : Path , kind : str ) - > None : 8 ctx
2875 """Prove a change under the workspace's own tests runs that unit alone.
2877 A new test file under the root ``tests/`` and nothing else: the
2878 check leg's row says it narrowed to the workspace tests; the
2879 branch's record holds that unit measured by this run and every
2880 member carried from main's; the gate job judged every member; the
2881 stamp composed with main's tree. Re-run on a pass-owned branch
2882 with main's tip as the stamp.
2884 _fresh_branch ( root , " chore/tests-leg " )
2885 _main_settled ( root , kind )
2886 stamp = git . head_sha ( root )
2887 probe = root / " tests " / " test_tests_leg.py "
2888 # A fresh newborn has no workspace tests yet: this file is the first.
2889 probe . parent . mkdir ( exist_ok = True )
2891 ' " " " A workspace-tests change: the loop proves the tests leg on it. " " " \n '
2893 f ' STAMP = " { stamp } " \n '
2895 " def test_the_stamp_is_a_commit(): \n "
2896 " assert len(STAMP) == 40 \n " ,
2901 " chore(tests): a workspace-tests change for the tests leg \n \n One file "
2902 " under the root tests directory, so the check leg narrows to the "
2903 " workspace tests and says so. " ,
2905 head = git . head_sha ( root )
2906 with contextlib . suppress ( git . GitError ) :
2907 git . fetch ( root , prune = True )
2908 _loop_fm ( root , " submit " , " --force " , " --armed " )
2910 forge , _ = _dev_forge ( kind )
2911 repo = forge . repository ( E2E_OWNER , E2E_REPO )
2912 run , _jobs = _completed_run ( repo , head , event = " pull_request " )
2913 facts = run_facts ( root , run . id )
2914 _require_scope ( run , facts , scope = " affected " , packages = [ " tests " ] , composed = True )
2915 members , _tests = _units ( root )
2920 facts . job ( " check " ) . leg ,
2924 _require_judged ( run , facts , dict . fromkeys ( members , 100.0 ) )
2925 _require_proved ( root , run , branch = " chore/tests-leg " )
2926 _prove_shards ( root , run , facts , ran = True )
2928 f " tests leg: proven on a workspace-tests pull request (run { run . id } : the "
2929 " check leg ran the workspace tests alone, the union reused every member "
2930 " from main ' s record, the stamp composed) "
2932 landed = git . head_sha ( root )
2933 run , _jobs = _completed_run ( repo , landed , event = " push " )
2934 _require_scope ( run , run_facts ( root , run . id ) , scope = " verified " )
2935 print ( f " composed skip: proven on main ' s run { run . id } after the tests-leg squash " )
2938 def _prove_nightly ( root : Path , kind : str ) - > None : 8 ctx
2939 """Prove the nightly point by hand: dispatched, followed to green, read back.
2941 The loop's contract schedules the released member's verification
2942 at the nightly point, so the dispatched run proves a task attached
2943 through the contract with no YAML change, and the verbs that
2944 start and read a point run against the real runner. After the
2945 release act, so the verification has a wheel to install.
2947 code = _loop_fm ( root , " ci.dispatch " , " --point=nightly " , " --interval=5 " , nofail = True )
2949 fail ( f " the loop ' s ` { footman . prog ( ) } ci.dispatch --point=nightly` exited { code } " )
2950 if _loop_fm ( root , " ci.status " , " --point=nightly " , nofail = True ) :
2952 f " the loop ' s ` { footman . prog ( ) } ci.status --point=nightly` did not "
2953 " read the dispatched run green "
2955 from livery . workshop . _ci_tasks import point_runs
2957 forge , _ = _dev_forge ( kind )
2958 repo = forge . repository ( E2E_OWNER , E2E_REPO )
2959 run = point_runs ( repo , " nightly " , limit = 1 ) [ 0 ]
2960 # The nightly's jobs record the run's row themselves; the row names
2961 # the scheduled verification among the tasks a job ran.
2962 _require_task ( run_facts ( root , run . id ) , " nightly " , VERIFY_TASK )
2964 f " nightly: proven by hand (run { run . id } : dispatched, followed to green, "
2965 " the scheduled verification ran, and the point read back green) "
2969 def _prove_dispatched_gate ( root : Path , kind : str ) - > None : 8 ctx
2970 """Prove the gate on command: dispatched on main, full, followed to green.
2972 A dispatched gate pays the full gate whatever the contract's
2973 affected-legs key says: the check verb reads the event and
2974 narrows on a pull request alone, and sets the verified record
2975 aside the way the nightly does, so a tree main already proved is
2976 proved again rather than skipped. The check leg says so, and the
2977 run is read back green through the point's own reader.
2979 code = _loop_fm ( root , " ci.dispatch " , " --point=gate " , " --interval=5 " , nofail = True )
2981 fail ( f " the loop ' s ` { footman . prog ( ) } ci.dispatch --point=gate` exited { code } " )
2982 if _loop_fm ( root , " ci.status " , " --point=gate " , nofail = True ) :
2984 f " the loop ' s ` { footman . prog ( ) } ci.status --point=gate` did not "
2985 " read the dispatched run green "
2987 from livery . workshop . _ci_tasks import point_runs
2989 forge , _ = _dev_forge ( kind )
2990 repo = forge . repository ( E2E_OWNER , E2E_REPO )
2991 run = point_runs ( repo , " gate " , limit = 1 ) [ 0 ]
2992 if run . event != " workflow_dispatch " :
2994 f " the newest gate run { run . id } is a { run . event } run, not the "
2995 f " dispatched one: { run . url } "
2997 facts = run_facts ( root , run . id )
2998 _require_scope ( run , facts , scope = " full " )
2999 _prove_shards ( root , run , facts , ran = True )
3001 f " gate: proven by hand (run { run . id } : dispatched, followed to green, "
3002 " the full gate ran, and the point read back green) "
3006 def _prove_contributed_point ( root : Path , kind : str ) - > None : 8 ctx
3007 """Prove the member's point: dispatched, followed to green, its task run.
3009 The member's contract declares the point; the rendered shell is
3010 the loop's own output, so the proof is the real runner running
3011 the declared task through ``ci.run`` and the point reading back
3012 green through the point's own reader.
3015 root , " ci.dispatch " , f " --point= { CONTRIBUTED_POINT } " , " --interval=5 " , nofail = True
3019 f " the loop ' s ` { footman . prog ( ) } ci.dispatch --point= { CONTRIBUTED_POINT } ` "
3022 if _loop_fm ( root , " ci.status " , f " --point= { CONTRIBUTED_POINT } " , nofail = True ) :
3024 f " the loop ' s ` { footman . prog ( ) } ci.status --point= { CONTRIBUTED_POINT } ` "
3025 " did not read the dispatched run green "
3027 from livery . workshop . _ci_tasks import point_runs
3029 forge , _ = _dev_forge ( kind )
3030 repo = forge . repository ( E2E_OWNER , E2E_REPO )
3031 run = point_runs ( repo , CONTRIBUTED_POINT , root ) [ 0 ]
3032 # The point's job records the run's row itself; the row names the
3033 # member's declared task among the tasks the job ran.
3034 _require_task ( run_facts ( root , run . id ) , CONTRIBUTED_POINT , " extensions " )
3036 f " { CONTRIBUTED_POINT } : proven by hand (run { run . id } : the contributed "
3037 " point dispatched, its task run, and the point read back green) "
3041 def _release_act ( root : Path , kind : str ) - > None : 8 ctx
3042 """Release the member through the loop; verify wheel and receipt.
3044 The armed release drives prepare, the isolated legs, the release
3045 pull request through the gate, and the merge; the emitted
3046 release workflow's wave then publishes to the forge's own
3047 registry and cuts the receipt tag. Done means measured: the
3048 served version and the annotated tag, never the exit code alone,
3049 and for the native member the publish job's line that the wave
3050 published the wheels the wheels job built.
3052 from livery . workshop . _release_driver import release_name
3054 # Only the members without a receipt release: the driver refuses a
3055 # set with a member nothing unreleased touches, and a cut receipt
3056 # is exactly that. A fresh loop releases both in one set.
3058 member . name : f " packages/ { member . name } /v0.1.0 " for member in LOOP_MEMBERS
3061 on_origin = git . ls_remote ( root , * all_tags . values ( ) , tags = True )
3062 except git . GitError :
3064 cut = { name for name , tag in all_tags . items ( ) if f " refs/tags/ { tag } " in on_origin }
3065 for name in sorted ( cut ) :
3066 _require_receipt_protected ( root , all_tags [ name ] , kind )
3067 print ( f " release: receipt { all_tags [ name ] } already on the loop " )
3068 names = tuple ( member . name for member in LOOP_MEMBERS if member . name not in cut )
3071 tags = { name : all_tags [ name ] for name in names }
3073 # A prepared release PR may survive an earlier pass. Fresh (its
3074 # branch still contains main) it is the driver's own recovery:
3075 # left alone, the re-run arms and merges it, which is also how
3076 # the forge's long post-open conflict-check window is ridden out
3077 # (measured outlasting the merge retry budget). Stale (main has
3078 # moved past it) the driver refuses and teaches `abandon`; the
3079 # loop follows the teach through the verb before releasing.
3080 release_branch = f " workflow/ { release_name ( names ) } "
3081 forge , _ = _dev_forge ( kind )
3082 survivor = forge . repository ( E2E_OWNER , E2E_REPO ) . pr . find_by_head ( release_branch )
3083 if survivor is not None and survivor . state == " open " :
3084 git . fetch ( root , release_branch )
3085 if git . is_ancestor ( root , " origin/main " , f " origin/ { release_branch } " ) :
3086 print ( f " prepared release PR # { survivor . number } is fresh; recovering it " )
3088 print ( f " abandoning stale prepared release PR # { survivor . number } " )
3089 git . switch_new ( root , release_branch , f " origin/ { release_branch } " )
3090 _loop_fm ( root , " abandon " )
3092 # Bounded self-heal for the forge's post-open window: right after
3093 # a release PR opens, the arm can answer 405 for minutes while
3094 # the forge computes mergeability (measured: still refusing at
3095 # fifty seconds, mergeable when probed later). The verb's own
3096 # recovery arms the surviving fresh PR, so re-running it is the
3097 # ride-out; a failure with no fresh survivor is real and final.
3100 repo = forge . repository ( E2E_OWNER , E2E_REPO )
3101 before_sha = _origin_main ( root )
3102 for round_ in range ( 4 ) :
3104 print ( " waiting out the forge ' s post-open window (45s) " )
3116 # The wave's red run, readable here and nowhere else once a
3117 # hosted job's forge is gone.
3118 from livery . workshop . _ci_tasks import point_runs
3120 for run in point_runs ( repo , " release " , root , limit = 3 ) :
3121 if run . conclusion == " failure " :
3122 print ( red_jobs_text ( repo , run ) )
3124 survivor = repo . pr . find_by_head ( release_branch )
3125 if survivor is None or survivor . state != " open " :
3126 fail ( " the armed release failed with no fresh PR to recover; see above " )
3128 if not git . is_ancestor ( root , " origin/main " , f " origin/ { release_branch } " ) :
3129 fail ( " the armed release failed and its PR went stale; see above " )
3131 fail ( " the forge ' s post-open window never closed across 4 rounds " )
3132 # The armed release returns at the merge, and the forge moves
3133 # the ref a beat later (measured: an immediate rev-parse watched
3134 # the pre-squash commit and called the wave skipped). Poll for
3135 # the movement; a main that never moves means the recovery arm
3136 # ran, which cuts receipts itself, and the probes below judge.
3138 deadline = time . monotonic ( ) + 90
3139 while time . monotonic ( ) < deadline :
3140 moved = _origin_main ( root )
3141 if moved and moved != before_sha :
3146 # The wave runs on the squash asynchronously; its red must
3147 # surface verbatim, because a registry poll alone cannot say
3148 # whether the wave failed or is merely slow.
3149 _watch ( kind , _lane ( kind ) . alias , squash , require = ( " release.yml " , ) )
3151 # The recovery arm dispatched the wave at the stamping commit,
3152 # which is not main's tip, so the newest release run is the
3153 # one to follow: its red surfaces verbatim instead of a blind
3154 # registry wait that expires on a slow wheels leg.
3155 print ( " main unmoved: the recovery arm dispatched; following its wave " )
3156 _watch_latest ( kind , " release.yml " )
3157 # The served version is the same whether the wheels job built the
3158 # native member's wheels or the publish job built its own runner's;
3159 # the publish job's log says which. The wave just followed is the
3160 # release point's newest run.
3161 from livery . workshop . _ci_tasks import point_runs
3163 wave = point_runs ( repo , " release " , root , limit = 1 ) [ 0 ]
3164 for member in members_for ( names ) :
3165 if " nanobind " in member . holds ( ) :
3166 _require_prebuilt ( repo , wave , _contract_name ( root , member . name ) )
3167 served_versions = _serving_probe ( root )
3170 functools . partial ( _serves , served_versions , name ) ,
3173 " the wave is green but the registry never served "
3174 f " { _contract_name ( root , name ) } 0.1.0 "
3177 # The receipt push follows the publish inside the wave, so the
3178 # tag gets the same patience as the serving probe.
3179 for tag in tags . values ( ) :
3181 functools . partial ( _tag_on_remote , root , tag ) ,
3183 failing = f " served, but the receipt tag { tag } is not on the loop " ,
3184 retried = ( git . GitError , ) ,
3186 _require_receipt_protected ( root , tag , kind )
3187 served = " , " . join ( f " { _contract_name ( root , name ) } 0.1.0 " for name in names )
3188 print ( f " release: { served } served, receipts { ' , ' . join ( tags . values ( ) ) } cut " )
3191 def _serves ( probe : Callable [ [ str ] , Collection [ str ] ] , name : str ) - > bool : 8 ctx
3192 """Whether the registry *probe* serves *name* at the loop's release version."""
3193 return " 0.1.0 " in probe ( name )
3196 def _tag_on_remote ( root : Path , tag : str ) - > bool : 8 ctx
3197 """Whether *tag* is on the loop's remote."""
3198 return f " refs/tags/ { tag } " in git . ls_remote ( root , tag , tags = True )
3202 condition : Callable [ [ ] , bool ] ,
3206 retried : tuple [ type [ Exception ] , . . . ] = ( ) ,
3208 """Poll *condition* every five seconds until it holds.
3210 Past *timeout* seconds, fail with *failing*.
3213 def holds ( ) - > bool | Pending :
3214 return True if condition ( ) else Pending ( )
3226 except ( FollowTimedOut , ForgeUnreachable ) :
3230 def _require_receipt_protected ( root : Path , tag : str , kind : str = " gitea " ) - > None : 8 ctx
3231 """Prove the receipt's protection by attempting the crime.
3233 A refused delete is the strongest proof and ends it; GitLab
3234 refuses a protected tag's deletion over git to everyone, so there
3235 it is the only proof. Gitea ties creation, deletion, and movement
3236 to one whitelist, so the loop's own lane (the whitelisted admin)
3237 can delete; there the tag is pushed straight back and the proof is
3238 the protection's presence with the lane on its whitelist, read
3239 from the API, which is what binds everyone else.
3243 import urllib . request 1 ctx
3245 # Forced: a receipt recut by a later wave is a new tag object, and
3246 # the workspace may still hold the one an earlier pass fetched.
3247 with contextlib . suppress ( git . GitError ) : 1 ctx
3248 git . fetch_tag ( root , tag ) 1 ctx
3250 git . push_refspec ( root , f " :refs/tags/ { tag } " ) 1 ctx
3251 except git . GitError : 1 ctx
3252 print ( f " receipt { tag } : delete refused; protection holds " ) 1 ctx
3254 with contextlib . suppress ( git . GitError ) : 1 ctx
3255 git . push_refspec ( root , f " refs/tags/ { tag } " ) 1 ctx
3256 if kind != " gitea " : 3256 ↛ 3262line 3256 didn't jump to line 3262 because the condition on line 3256 was always true 1 ctx
3258 f " the receipt tag { tag } was deletable on { kind } , whose protection "
3259 " refuses every deletion over git: the contract ' s assertion did "
3260 " not hold (the receipt was pushed back) "
3262 url = os . environ . get ( " GITEA_URL " , " " )
3263 token = os . environ . get ( " GITEA_TOKEN " , " " )
3264 request = urllib . request . Request (
3265 f " { url } /api/v1/repos/ { E2E_OWNER } / { E2E_REPO } /tag_protections " ,
3266 headers = { " Authorization " : f " token { token } " } ,
3268 with urllib . request . urlopen ( request , timeout = 10 ) as answer :
3269 entries = json . load ( answer )
3272 for entry in entries
3273 if fnmatch . fnmatch ( tag , str ( entry . get ( " name_pattern " , " " ) ) )
3277 f " the receipt tag { tag } was deletable and no tag protection "
3278 " covers it: the contract ' s assertion did not hold (the "
3279 " receipt was pushed back) "
3282 f " receipt { tag } : protected; the configuring lane stays on the "
3283 " whitelist (gitea ' s one-whitelist model), everyone else is bound "
3287 def _merge_setup ( kind : str , sha : str ) - > None : 8 ctx
3288 """Merge the setup pull request when its green head is *sha*.
3290 Birth's own done-line prescribes it: merging the setup PR proves
3291 the gate and the protection wiring end to end. Patient through
3292 the forge's whole 405 family: the mergeability recompute's "try
3293 again later" and the beat where a finished run's required
3294 context has not propagated yet ("not all required status checks
3295 successful", measured seconds after the watch saw the run
3296 green). Already merged, or a head that moved on, is a quiet
3299 from livery . workshop . _new_project import _SETUP_BRANCH
3300 from livery . workshop . _submit import _follow_merge_state
3302 forge , _ = _dev_forge ( kind )
3303 repo = forge . repository ( E2E_OWNER , E2E_REPO )
3304 pr = repo . pr . find_by_head ( _SETUP_BRANCH )
3305 if pr is None or pr . state != " open " :
3306 print ( " setup PR: already merged or gone " )
3308 head = getattr ( pr , " head_sha " , " " )
3309 if head and head != sha :
3310 print ( " setup PR: head moved on; leaving it to the next run " )
3312 _follow_merge_state (
3313 repo , kind , pr . number , repo . pr . merge_now , pr . number , title = pr . title
3315 print ( f " setup PR # { pr . number } : merged; the gate is proven " )
3318 # --- the scenarios ---------------------------------------------------------------
3323 """What one pass carries between its scenarios.
3326 forge: The lane's kind, ``gitea`` or ``gitlab``.
3327 url: The forge's host-side URL from the shared environment.
3328 fresh: Whether the pass starts over from nothing.
3329 root: The loop's workspace once ``birth`` has run; None before.
3330 timings: One entry per scenario run, in order.
3331 extension: The extension under test; empty for a plain pass.
3332 stack: The extensions the birth lists: the loop's own
3333 ([livery.workshop._e2e.loop_stack][]) or the extension
3334 under test's; empty for the stock list.
3335 members: The members the members scenario lands, by name; empty
3341 fresh : bool = False 8 ctx
3342 root : Path | None = None 8 ctx
3343 timings : list [ Timing ] = field ( default_factory = list ) 8 ctx
3344 extension : str = " " 8 ctx
3345 stack : tuple [ str , . . . ] = ( ) 8 ctx
3346 members : tuple [ str , . . . ] = ( ) 8 ctx
3349 @dataclass ( frozen = True ) 8 ctx
3351 """What one scenario cost.
3355 seconds: Its wall time.
3356 runs: The runner runs it followed.
3357 failed: Whether it ended in a refusal or an error.
3363 failed : bool = False 8 ctx
3366 @dataclass ( frozen = True ) 8 ctx
3368 """One thing the loop proves, by name, with what must have run before it.
3371 name: The name ``--scenario`` takes.
3372 needs: The scenarios this one builds on; a pass runs them
3373 first, once, whether or not they were named.
3374 run: The proof, given the pass.
3375 daemon: Whether it needs the runner's docker socket: the
3376 release builds the native member's wheel through
3377 cibuildwheel on the runner, and nothing else does.
3381 needs : tuple [ str , . . . ] 8 ctx
3382 run : Callable [ [ Pass ] , None ] 8 ctx
3383 daemon : bool = False 8 ctx
3386 def _born ( pass_ : Pass ) - > None : 8 ctx
3387 """Birth or resume the loop's workspace and merge its setup pull request.
3389 The repository, its protection and the setup pull request through
3390 ``fm new.project``, the secrets, the wiring to the workshop's own
3391 dev wheels, the pushed head's runs followed to their verdicts on
3392 the real runner, and the setup squash merged.
3394 forge = pass_ . forge 2 ctx
3395 lane , lane_token = _dev_forge ( forge ) 2 ctx
3396 root = _loop_home ( forge ) / E2E_REPO 2 ctx
3397 if ( root / " .git " ) . is_dir ( ) and _has_remote ( root ) : 2 ctx
3398 # The origin names the forge of the pass that last wrote it,
3399 # which a fresh pass removed with its environment, so it is
3400 # pointed at this pass's forge before the start-over below asks
3401 # it for commits it has not seen.
3402 _authenticate_remote ( root , lane_token , forge ) 2 ctx
3403 listed = _listed_extensions ( root ) 2 ctx
3404 if listed and listed != _set_of ( _stack_of ( pass_ ) ) : 2 ctx
3405 # A workspace born for another list is not this pass's: an
3406 # extension pass and a plain one take turns in one environment.
3407 for line in start_over ( lane , lane_token , root , url = pass_ . url , kind = forge ) : 3407 ↛ anywhereline 3407 didn't jump anywhere: it always raised an exception. 1 ctx
3409 elif pass_ . fresh and CURRENT . mode != " host " : 3409 ↛ 3413line 3409 didn't jump to line 3413 because the condition on line 3409 was never true 1 ctx
3410 # A fresh host-mode pass took a new environment: its forge
3411 # holds nothing yet. The docker rig is long-lived, so its
3412 # repository, releases and workspace go here.
3413 for line in start_over ( lane , lane_token , root , url = pass_ . url , kind = forge ) :
3415 elif pass_ . fresh and root . exists ( ) : 3415 ↛ 3416line 3415 didn't jump to line 3416 because the condition on line 3415 was never true 1 ctx
3416 shutil . rmtree ( root , ignore_errors = True )
3417 if ( root / " .git " ) . is_dir ( ) and _has_remote ( root ) : 1 ctx
3418 # A resumed birth pushes before it returns, so an existing
3419 # workspace authenticated above; birth resets the remote, so
3420 # it authenticates again after. Main then fast-forwards onto
3421 # the merges the loop itself made: without the reconcile,
3422 # birth's foreign-repo guard reads our own squash as a
3423 # stranger's history and refuses. A birth that failed before
3424 # the forge held the repository left no remote, and resumes
3425 # as a first birth does.
3426 _align_main ( root ) 1 ctx
3427 from livery . workshop . _extensions import workspace_root 1 ctx
3432 index = _dev_index ( forge , pass_ . stack ) ,
3434 driver = workspace_root ( ) ,
3436 _authenticate_remote ( root , lane_token , forge ) 1 ctx
3437 provision ( forge ) 1 ctx
3438 # After the project exists: GitLab's registry belongs to the
3439 # project, and a fresh start's delete is asynchronous, so a
3440 # publish before the birth lands in the project being deleted.
3441 pins = _publish_dev_wheels ( forge , pass_ . stack )
3442 enabled = steps_declared_off ( pass_ . extension ) if pass_ . extension else ( )
3443 sha = _eat_dev_wheels ( root , pins , forge , enabled = enabled )
3444 print ( f " watching { sha [ : 12 ] } on the runner " )
3445 from livery . workshop . _new_project import _SETUP_BRANCH
3447 _watch ( forge , pass_ . url , sha , branch = _SETUP_BRANCH )
3448 print ( " green: the loop ' s gate ran on the real runner " )
3449 _merge_setup ( forge , sha )
3453 def _stack_of ( pass_ : Pass ) - > tuple [ str , . . . ] : 8 ctx
3454 """The extensions *pass_*'s birth lists: its own stack, else the stock list."""
3455 from livery . workshop . _extensions import SELF 1 ctx
3456 from livery . workshop . _new_project import birth_extensions 1 ctx
3458 return pass_ . stack or tuple ( birth_extensions ( [ SELF ] ) ) 1 ctx
3461 def _set_of ( names : tuple [ str , . . . ] ) - > frozenset [ str ] : 8 ctx
3462 """*names* and every extension they require: the set a list of them names."""
3463 from livery . workshop . _composition import closure 1 ctx
3464 from livery . workshop . _extensions import installed_declaration 1 ctx
3466 return frozenset ( closure ( names , installed_declaration ) ) 1 ctx
3469 #: The extension that builds the site, which a plain pass's birth leaves out.
3473 def loop_stack ( ) - > tuple [ str , . . . ] : 8 ctx
3474 """The extensions a plain pass's birth lists, as their canonical list.
3476 The stock list without the site, and what the loop's members'
3477 templates need (`LoopMember.needs`): a creation installs nothing,
3478 so the root lists them before the members are created. The site is
3479 the docs extension and every stock entry whose declaration requires
3480 it, directly or through another: the docs extension puts a docs job
3481 on every run of the loop's project, for a site nothing in a pass
3482 reads, and an extension that requires it brings it into the root's
3483 set. The pass proves the gate, the release train and the points,
3484 and ``fm ci.e2e --extension=docs`` proves the docs extension on its
3485 own. A stock entry no installed distribution declares requires
3488 from livery . workshop . _extensions import SELF , installed_declaration 6 ctx
3489 from livery . workshop . _new_project import birth_extensions , canonical_extensions 6 ctx
3491 def builds_the_site ( name : str , seen : frozenset [ str ] ) - > bool : 6 ctx
3492 if name == SITE : 6 ctx
3494 found = installed_declaration ( name ) 6 ctx
3495 needed = found . requires if found is not None else ( ) 6 ctx
3497 builds_the_site ( other , seen | { name } )
3499 if other not in seen
3504 for entry in birth_extensions ( [ SELF ] )
3505 if not builds_the_site ( entry , frozenset ( ) )
3507 needs = [ needed for member in LOOP_MEMBERS for needed in member . needs ( ) ] 6 ctx
3508 return tuple ( canonical_extensions ( [ * stock , * needs ] ) ) 6 ctx
3511 def _listed_extensions ( root : Path ) - > frozenset [ str ] : 8 ctx
3512 """The root's set of *root*'s contract: its list and what that requires.
3514 Empty with no contract. The set, not the list, so an extension
3515 another one requires counts whether the list writes it or not.
3517 from livery . workshop . _extensions import root_set 2 ctx
3519 if not ( root / " workshop.toml " ) . is_file ( ) : 2 ctx
3520 return frozenset ( ) 2 ctx
3521 return frozenset ( root_set ( root ) ) 1 ctx
3524 def _at ( pass_ : Pass ) - > Path : 8 ctx
3525 """The loop's workspace; a refusal when birth has not run in this pass."""
3526 if pass_ . root is None :
3527 fail ( " the loop ' s workspace is not born yet; `birth` runs before every scenario " )
3531 #: Every scenario, in dependency order: a scenario's needs come
3532 #: before it, so a chosen subset runs in this order too.
3533 SCENARIOS : tuple [ Scenario , . . . ] = ( 8 ctx
3534 Scenario ( " birth " , ( ) , _born ) ,
3536 " verified-skip " , ( " birth " , ) , lambda p : _prove_verified_skip ( _at ( p ) , p . forge )
3538 Scenario ( " members " , ( " birth " , ) , lambda p : _ensure_members ( _at ( p ) , p . members ) ) ,
3539 Scenario ( " ratchet " , ( " members " , ) , lambda p : _prepare_ratchet ( _at ( p ) , p . forge ) ) ,
3540 Scenario ( " scoped-leg " , ( " ratchet " , ) , lambda p : _prove_scoped_leg ( _at ( p ) , p . forge ) ) ,
3544 lambda p : _prove_unproven_push ( _at ( p ) , p . forge ) ,
3546 Scenario ( " prose-leg " , ( " members " , ) , lambda p : _prove_prose_leg ( _at ( p ) , p . forge ) ) ,
3547 Scenario ( " tests-leg " , ( " members " , ) , lambda p : _prove_tests_leg ( _at ( p ) , p . forge ) ) ,
3549 " release " , ( " members " , ) , lambda p : _release_act ( _at ( p ) , p . forge ) , daemon = True
3551 Scenario ( " nightly " , ( " release " , ) , lambda p : _prove_nightly ( _at ( p ) , p . forge ) ) ,
3555 lambda p : _prove_dispatched_gate ( _at ( p ) , p . forge ) ,
3558 " contributed-point " ,
3560 lambda p : _prove_contributed_point ( _at ( p ) , p . forge ) ,
3564 #: The named sets ``--scenario`` takes beside the scenarios' own names.
3565 SETS : dict [ str , tuple [ str , . . . ] ] = { 8 ctx
3566 " develop " : ( " birth " , " verified-skip " , " members " , " scoped-leg " , " unproven-push " ) ,
3575 " points " : ( " nightly " , " dispatched-gate " , " contributed-point " ) ,
3576 " extension " : ( " birth " , " members " ) ,
3577 " all " : tuple ( scenario . name for scenario in SCENARIOS ) ,
3581 def scenarios_for ( spec : str ) - > tuple [ Scenario , . . . ] : 8 ctx
3582 """The scenarios *spec* names, their needs added, in the registry's order.
3584 *spec* is comma-separated set names and scenario names. A name
3585 that is neither refuses naming both lists; an empty *spec*
3586 refuses too. A need is run once however many names reach it.
3588 by_name = { scenario . name : scenario for scenario in SCENARIOS } 2 ctx
3589 wanted : set [ str ] = set ( ) 2 ctx
3590 for token in ( part . strip ( ) for part in spec . split ( " , " ) ) : 2 ctx
3593 if token in SETS : 2 ctx
3594 wanted . update ( SETS [ token ] ) 2 ctx
3595 elif token in by_name : 2 ctx
3596 wanted . add ( token ) 1 ctx
3599 f " { token !r} is not a scenario or a set; the sets are "
3600 f " { ' , ' . join ( SETS ) } and the scenarios { ' , ' . join ( by_name ) } "
3603 fail ( f " --scenario names nothing; the sets are { ' , ' . join ( SETS ) } " ) 1 ctx
3604 pending = list ( wanted ) 1 ctx
3606 for need in by_name [ pending . pop ( ) ] . needs : 1 ctx
3607 if need not in wanted : 1 ctx
3608 wanted . add ( need ) 1 ctx
3609 pending . append ( need ) 1 ctx
3610 return tuple ( scenario for scenario in SCENARIOS if scenario . name in wanted ) 1 ctx
3613 def daemon_needed ( scenarios : Sequence [ Scenario ] ) - > bool : 8 ctx
3614 """Whether any of *scenarios* needs the runner's docker socket."""
3615 return any ( scenario . daemon for scenario in scenarios ) 1 ctx
3618 def run_scenario ( pass_ : Pass , scenario : Scenario ) - > None : 8 ctx
3619 """Run *scenario* for *pass_*, timed; a failure is timed and marked, then raised."""
3622 started = time . monotonic ( ) 1 ctx
3623 runs_before = RUNS . count 1 ctx
3624 print ( f " scenario { scenario . name } " ) 1 ctx
3627 scenario . run ( pass_ ) 1 ctx
3630 pass_ . timings . append ( 1 ctx
3633 time . monotonic ( ) - started ,
3634 RUNS . count - runs_before ,
3640 def timing_table ( timings : Sequence [ Timing ] ) - > list [ str ] : 8 ctx
3641 """The lines a pass ends with: each scenario's time and runs, then the total."""
3642 if not timings : 1 ctx
3643 return [ " timing: nothing ran " ] 1 ctx
3644 width = max ( len ( timing . name ) for timing in timings ) 1 ctx
3646 f " { timing . name : < { width } } { timing . seconds : 7.1f } s { timing . runs } run(s) "
3647 + ( " failed " if timing . failed else " " )
3648 for timing in timings
3650 total = sum ( timing . seconds for timing in timings ) 1 ctx
3651 runs = sum ( timing . runs for timing in timings ) 1 ctx
3652 lines . append ( f " { ' total ' : < { width } } { total : 7.1f } s { runs } run(s) " ) 1 ctx
3656 #: The local series a pass writes its rows to, declared with the
3657 #: others so `fm store.show loop` reads it and the janitor bounds it.
3658 LOOP_SERIES = LOOP 8 ctx
3661 def record_pass ( root : Path , pass_ : Pass , asked : str ) - > str : 8 ctx
3662 """Put the pass's timings on the local loop series; the line to print."""
3663 from datetime import UTC , datetime 1 ctx
3665 when = datetime . now ( UTC ) . strftime ( " % Y % m %d T % H % M % SZ " ) 1 ctx
3666 row : dict [ str , object ] = { 1 ctx
3667 " forge " : pass_ . forge ,
3669 * * ( { " extension " : pass_ . extension } if pass_ . extension else { } ) ,
3672 " name " : timing . name ,
3673 " seconds " : round ( timing . seconds , 1 ) ,
3674 " runs " : timing . runs ,
3675 " failed " : timing . failed ,
3677 for timing in pass_ . timings
3680 why = LOOP_SERIES . put ( 1 ctx
3682 { f " pass- { when } .json " : row } ,
3683 message = f " loop: pass { when } ( { asked } ) " ,
3685 if why : 3685 ↛ 3686line 3685 didn't jump to line 3686 because the condition on line 3685 was never true 1 ctx
3686 return f " loop series: { why } ; the pass is not recorded "
3687 return f " loop series: pass { when } recorded ( { len ( pass_ . timings ) } scenario(s)) " 1 ctx
3690 if _WORKSHOP_TESTS . is_dir ( ) : 3690 ↛ exitline 3690 didn't exit the module because the condition on line 3690 was always true 8 ctx
3691 # serial: the driver births into and pushes from its own
3692 # directories, so it owns the process globals for the run.
3693 @ci . task ( name = " e2e " , serial = True ) 8 ctx
3696 forge : str = " gitea " ,
3697 fresh : bool = False ,
3700 purge_cache : bool = False ,
3701 extension : str = " " ,
3702 from_main : bool = False ,
3704 """Exercise the CI and release story on a local environment, by scenario.
3706 ``--env`` names the environment the pass runs on, `e2e` by
3707 default: one that does not exist is brought up in host mode
3708 with one runner, ``--fresh`` removes it and brings it up
3709 again, so a fresh pass is a new forge, and ``--purge-cache``
3710 removes the rig's shared caches first. The docker-mode
3711 environment ``dev`` is the compose rig, addressed as before.
3712 Each variable an extension of the loop's set declares with a
3713 directory of its own is placed inside the environment, so what a
3714 release writes there goes with the environment's forge.
3715 ``--scenario`` names what the pass proves: scenario names, set
3716 names, or both, comma-separated. The sets are ``develop``
3717 (birth, the verified skip, the members, the scoped leg), the
3718 default, ``release`` (develop and the release act), ``points``
3719 (the nightly, the dispatched gate, the contributed point),
3720 ``extension`` (birth and the members) and ``all``; a scenario's
3721 needs run first, once. ``--extension`` tests one extension in
3722 isolation, ``extension`` the default set: the birth lists that
3723 extension and what it requires instead of the loop's stack, and
3724 the members are the loop's whose sets hold an extension its steps
3725 name. ``birth`` builds
3726 this checkout's workshop, its dependencies and the extensions a
3727 birth lists into a local index, births or resumes the loop's
3728 workspace through ``fm new.project`` from that index (so an
3729 extension the birth lists needs no release), with its
3730 repository, protection and setup pull request, provisions the
3731 secrets, wires the workspace to the dev wheels in the forge's
3732 registry, and follows the pushed head's runs to their verdicts
3733 on the real runner. Re-running is the recovery procedure at every
3734 step. The pass ends with a table, each scenario's time and
3735 runs, and records the same rows on the local ``loop`` series.
3736 ``--fresh`` starts over from nothing: the loop's repository on
3737 the dev forge, its releases in the forge's registry, and the
3738 local workspace go, then the pass births everything anew. It
3739 refuses while the workspace holds commits the forge has not
3740 seen. ``--from-main`` moves a checkout standing on ``main`` or a
3741 reserved ``workflow/`` branch, where a build would be the release
3742 train, to a scratch branch at the same commit for the pass and
3743 back afterwards; the nightly's checkout is one.
3747 from livery . workshop import _devenv
3748 from livery . workshop . _extensions import workspace_root
3750 driver = workspace_root ( )
3751 with scratch_branch ( driver , enabled = from_main ) :
3752 if driver is not None :
3753 # Before anything is brought up: on a branch whose release
3754 # verb is the train, the first build would open a release.
3755 require_dev_branch ( driver )
3756 asked = scenario or ( " extension " if extension else " develop " )
3757 chosen = scenarios_for ( asked )
3759 extension_under_test ( extension ) if extension else ( loop_stack ( ) , ( ) )
3761 if forge != " gitea " :
3763 f " --env addresses a Gitea environment; --forge= { forge } has none yet "
3766 for line in _devenv . purge_cache ( ) :
3768 enter_environment ( env , stack , fresh = fresh )
3769 # Every commit the pass makes, the driver's, the birth's and
3770 # the loop's own fm's, is unsigned and carries the tools'
3771 # identity: the task's marks and the git plugin put both in
3772 # the task's environment, which rides into each child. On a
3773 # hosted runner the job's CI markers would reach every child,
3774 # which would then refuse a fix and stamp its runs as the
3775 # runner's; the pass drives its project as a desk.
3776 scrubbed = edit_environments ( { } , remove = CI_MARKERS )
3778 names = " , " . join ( scrubbed )
3779 print ( f " ci markers removed for the pass ' s children: { names } " )
3780 _require_host_alias ( forge )
3781 if daemon_needed ( chosen ) :
3782 _require_runner_docker ( forge )
3785 CURRENT . url or os . environ . get ( _lane ( forge ) . url_var , " " ) ,
3787 extension = extension ,
3794 run_scenario ( pass_ , item )
3796 for line in timing_table ( pass_ . timings ) :
3798 driver = workspace_root ( )
3799 if driver is not None :
3800 print ( record_pass ( driver , pass_ , asked ) )
3801 names = " , " . join ( item . name for item in chosen )
3802 print ( f " the loop proved { names } " )