gunk-dev/the-valley

worker-e2e.nix

sourcebc00697b19b5main's published tip history
52.0 KiB
1# The check worker on a host: one NixOS machine running the module with the
2# build slice and the worker on, beside the controllers and the registry
3# compiler, and a project with ready changes. The worker makes its key the
4# first time it starts, readable by it alone, and says its public halves.
5# An earlier start that was interrupted leaves nothing that stands in the
6# way. Until the registry holds the key, the worker cannot reach the
7# host's repositories. Once it does, a pass builds the nix checks a ready
8# change requires side by side, as many at once as the host gives it
9# slots, through the machine's nix daemon, and the evidence is on origin
10# before anyone approves the change. The timer runs the next pass.
11#
12# Then the wake directory. A move the worker reads starts a pass with the
13# timer stopped, and a move during a pass gets the next one. A landing by
14# the integrator's own service marks the worker while the project's mirror
15# and the bus hang, and so does a ready push. The worker's push, refused
16# while valley-init converges, is tried again once it has. A floor landed in the
17# instance, which the worker does not build, marks it, and the next pass
18# reads the new floor. A pass killed during a build, and a pass that
19# cannot reach the repositories, leave their claim, and the timer's next
20# pass builds the change with no new mark. A failed batch is not built
21# again before its wait, however many marks and timer passes come. Last,
22# the key is the same after many starts.
23#
24# Then the scheduler. One pass starts a short change's batch and a long
25# one's at once. Their evaluations are estimated at more than half the
26# evaluation budget, so they take turns. It builds the short change beside
27# the long one, takes on changes readied while the long batch runs, builds
28# two changes with one tree once, and goes on past a failed batch,
29# claiming the marks made meanwhile itself. A second pass starts two
30# batches whose estimates fit the budget together, and their evaluations
31# overlap. The changes of both are then withdrawn, since every scan after
32# them would read them.
33#
34# The worker's interval here is 15 seconds rather than the module's
35# minute, so a scenario that waits for a timer pass or a hold-off waits
36# seconds. module-eval holds what the module renders: the minute, the
37# slice's caps, and the nix daemon's OOM policy.
38{
39 pkgs,
40 lib,
41 self,
42 machineValley,
43 ...
44}:
45let
46 # Throwaway keys, made once at build time. They hold no authority
47 # anywhere: the machine that trusts them exists for one test run. The
48 # worker's key is not among them: the worker makes its own on the host.
49 keys = pkgs.runCommand "valley-worker-e2e-keys" { nativeBuildInputs = [ pkgs.openssh ]; } ''
50 mkdir $out
51 for who in integrator contributor; do
52 ssh-keygen -q -t ed25519 -N "" -C "$who" -f "$out/$who"
53 done
54 '';
55 pub = who: lib.fileContents "${keys}/${who}.pub";
56
57 declaration = pkgs.writeText "valley-worker-e2e.cue" ''
58 package valley
59
60 projects: {
61 // The instance repository, which carries the floor and the registry.
62 "instance": protection: refs: ["refs/heads/main"]
63 // The project's mirror is a local repository, which a scenario
64 // below makes hang.
65 "project": {
66 protection: {}
67 mirrors: ["/srv/hung.git"]
68 }
69 }
70 '';
71
72 # A floor that requires two nix checks of every change but one to the
73 # policy alone, so the instance's own floor lands by integration with no
74 # evidence. floorThird, which a scenario lands in the instance, requires a
75 # third check of the same attribute as the second.
76 floorWith = third: pkgs.writeText "floor.cue" ''
77 package verification
78
79 floor: {
80 checks: {
81 first: {runner: "nix", attribute: "first"}
82 second: {runner: "nix", attribute: "second"}
83 ${lib.optionalString third ''third: {runner: "nix", attribute: "second"}''}
84 }
85 classes: policy: {paths: {"policy/**": true}, requires: {}}
86 unclassified: {first: true, second: true${lib.optionalString third ", third: true"}}
87 }
88 '';
89 floor = floorWith false;
90 followsLayer = pkgs.writeText "follows.cue" ''
91 package verification
92
93 project: {
94 checks: later: {runner: "nix", attribute: "second"}
95 classes: docs: {paths: {"docs/**": true}, requires: {}, follows: {later: true}}
96 }
97 '';
98 floorThird = floorWith true;
99
100 # The project's flake, with no inputs, so the machine builds it offline.
101 # Each check runs a script from the project's tree in the sandbox's
102 # shell, and the script is the derivation's one input. The project's own
103 # scripts spin for about half a second, several of the sampler's ticks,
104 # so the two builds a pass runs at once are seen at once, and write the
105 # cores the daemon gave them. The slow flake's evaluation first hashes
106 # one MiB three thousand times, which takes over a second and little
107 # memory, so two evaluations started a moment apart are seen running at
108 # once.
109 slowEvaluation = ''builtins.seq (let s = builtins.concatStringsSep "" (builtins.genList (_: "0123456789abcdef") 65536); in builtins.foldl' (a: _: a + builtins.stringLength (builtins.hashString "sha256" s)) 0 (builtins.genList (i: i) 3000)) '';
110 flakeWith = slow: pkgs.writeText "flake.nix" ''
111 {
112 outputs =
113 { self }:
114 let
115 check = name: script: derivation {
116 inherit name;
117 system = "x86_64-linux";
118 builder = "/bin/sh";
119 args = [ script ];
120 };
121 in
122 {
123 checks.x86_64-linux = ${lib.optionalString slow slowEvaluation}{
124 first = check "worker-first" ./first.sh;
125 second = check "worker-second" ./second.sh;
126 };
127 };
128 }
129 '';
130 flake = flakeWith false;
131 slowFlake = flakeWith true;
132 flakeLock = pkgs.writeText "flake.lock" ''{"nodes":{"root":{}},"root":"root","version":7}'';
133 spin = pkgs.writeText "spin.sh" ''
134 i=0
135 while [ $i -lt 250000 ]; do i=$((i+1)); done
136 echo $NIX_BUILD_CORES > $out
137 '';
138 # A build long enough to be killed in: about twenty seconds of spinning.
139 slow = pkgs.writeText "slow.sh" ''
140 i=0
141 while [ $i -lt 10000000 ]; do i=$((i+1)); done
142 echo $NIX_BUILD_CORES > $out
143 '';
144 # The long batch beside which a pass builds others. Its build reads the
145 # gate, a fifo the scheduler scenario writes to when the build may end.
146 long = pkgs.writeText "long.sh" ''
147 read gate < /run/valley-worker-e2e-gate/long
148 echo $NIX_BUILD_CORES > $out
149 '';
150 # A batch the pass stops: a build that never ends unless it is killed,
151 # in a builder that names itself, so the test sees its build end.
152 stopped = pkgs.writeText "stopped.sh" ''
153 exec /bin/sh -c 'while :; do :; done' valley-stopped-build
154 '';
155 broken = pkgs.writeText "broken.sh" "exit 1";
156
157 # What the daemon's builds look like while the worker runs: the number
158 # of build users with a process, and the cgroup of each such process,
159 # sampled ten times a second.
160 sampler = pkgs.writeShellScript "valley-worker-e2e-sampler" ''
161 PATH=${
162 lib.makeBinPath [
163 pkgs.coreutils
164 pkgs.gawk
165 pkgs.procps
166 ]
167 }
168 while :; do
169 ps -eo user:32=,cgroup:512= | awk '$1 ~ /^nixbld/' > /tmp/sample
170 awk '{print $1}' /tmp/sample | sort -u | wc -l >> /tmp/builders
171 awk '{print $2}' /tmp/sample >> /tmp/build-cgroups
172 sleep 0.1
173 done
174 '';
175in
176{
177 worker-e2e = pkgs.testers.runNixOSTest {
178 name = "valley-worker-e2e";
179 nodes.host = {
180 imports = [ self.nixosModules.default ];
181 # Six CPUs: more than the worker's slots, so the slots and not the
182 # CPU count decide how many checks build at once.
183 virtualisation.cores = 6;
184 virtualisation.memorySize = 2048;
185 environment.systemPackages = [
186 pkgs.git
187 machineValley
188 ];
189 services.valley = {
190 enable = true;
191 config = declaration;
192 buildSlice.enable = true;
193 authorizedKeys = [
194 {
195 principal = "contributor";
196 key = pub "contributor";
197 }
198 ];
199 identity.enable = true;
200 bus.enable = true;
201 integrator = {
202 enable = true;
203 signingKeyFile = "${keys}/integrator";
204 instanceProject = "instance";
205 signerProjects."worker/attestations" = [ "project" ];
206 };
207 # Two checks at once, each told it may use two cores, rather
208 # than the defaults of one check at a time on four.
209 worker = {
210 enable = true;
211 projects = [ "project" ];
212 signerName = "worker/attestations";
213 buildSlots = 2;
214 maxJobs = 2;
215 cores = 2;
216 # A timer pass, and the hold-off after a pass that could not
217 # claim due, come 15 seconds after the last pass ends. The
218 # window below in which the hold-off starts nothing is 5 seconds.
219 interval = "15s";
220 # The scheduler scenarios seed each project's evaluation peaks
221 # against this budget, so two evaluations fit it or do not.
222 evalMemoryBudget = "1G";
223 };
224 };
225 # The test starts each pass itself until it checks the timer, so no
226 # pass runs before the test is ready for it. A timer pass starts
227 # within a second of its interval, rather than up to a minute of
228 # systemd's accuracy later.
229 systemd.timers.valley-worker.timerConfig.OnActiveSec = lib.mkForce "1h";
230 systemd.timers.valley-worker.timerConfig.AccuracySec = "1s";
231 # The worker and every attest it starts record their progress in a
232 # stream in the worker's own directory, where the scheduler scenario
233 # reads when each batch's evaluation began and ended.
234 systemd.services.valley-worker.environment.VALLEY_TELEMETRY_DIR = "/var/lib/valley-worker/telemetry";
235 # The long check's gate, in a directory every build's sandbox holds.
236 nix.settings.extra-sandbox-paths = [ "/run/valley-worker-e2e-gate" ];
237 systemd.tmpfiles.rules = [
238 "d /var/lib/valley-worker/telemetry 0700 valley-worker valley-worker - -"
239 "d /run/valley-worker-e2e-gate 0755 root root - -"
240 "p /run/valley-worker-e2e-gate/long 0644 root root - -"
241 ];
242 # The machine has no network. Without these, every new build waits
243 # for the daemon's lookups in cache.nixos.org to fail, and every boot
244 # waits for a DHCP lease on an interface nothing here uses.
245 nix.settings.substituters = lib.mkForce [ ];
246 networking.useDHCP = false;
247 };
248
249 testScript = ''
250 import shlex
251
252 host.wait_for_unit("multi-user.target")
253 host.succeed("systemctl is-active valley-worker.timer valley-worker.path")
254 host.succeed("systemctl stop valley-worker.timer valley-worker.path")
255
256 git = "sudo -u git git"
257 wake = "/var/lib/valley-worker-wake"
258 state = "/var/lib/valley-worker"
259 ssh = shlex.quote(
260 "ssh -i /root/keys/contributor -o IdentitiesOnly=yes -o BatchMode=yes"
261 " -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
262 )
263 contributor = f"cd /root/project && GIT_SSH_COMMAND={ssh}"
264 commit = "git -c user.name=contributor -c user.email=contributor@localhost commit --quiet"
265
266 def journal():
267 return host.succeed("journalctl -u valley-worker -o cat")
268
269 def unit_property(name, prop):
270 return host.succeed(f"systemctl show -p {prop} --value {name}").strip()
271
272 def attestations():
273 return host.succeed(
274 f"{git} -C /srv/git/project.git for-each-ref --format='%(refname)' refs/the-valley/attestations/"
275 ).split()
276
277 def registry(worker):
278 principals = [
279 '"contributor": {',
280 ' kind: "human"',
281 ' keys: [{class: "ssh-ed25519", bound: "host", public: "${
282 lib.concatStringsSep " " (lib.take 2 (lib.splitString " " (pub "contributor")))
283 }"}]',
284 ' grants: {push: boundary: "push", govern: boundary: "registry"}',
285 "}",
286 ]
287 if worker:
288 principals += [
289 '"worker": {',
290 ' kind: "machine"',
291 f' keys: [{{class: "ssh-ed25519", bound: "host", public: "{worker}", signs: "worker/attestations"}}]',
292 ' grants: push: boundary: "push"',
293 ' expires: "2099-01-01"',
294 "}",
295 ]
296 return "\n".join(
297 [
298 "package identity",
299 'boundaries: {"push": kind: "git-push", "registry": kind: "registry"}',
300 'genesis: "contributor"',
301 "principals: {",
302 ]
303 + principals
304 + ["}"]
305 )
306
307 # The instance's main carries the floor and the registry. It is
308 # landed by a local write, which runs no hook, as an operator seeds
309 # a protected repository.
310 def land_instance(worker):
311 host.succeed(
312 "rm -rf /tmp/instance && mkdir -p /tmp/instance/policy/instance /tmp/instance/identity",
313 "cp ${floor} /tmp/instance/policy/instance/floor.cue",
314 f"cat > /tmp/instance/identity/registry.cue <<'EOF'\n{registry(worker)}\nEOF",
315 f"cd /tmp/instance && git init --quiet --initial-branch=main && git add -A && {commit} -m instance",
316 "chown -R git:git /tmp/instance",
317 f"{git} -C /srv/git/instance.git fetch --quiet --force /tmp/instance main:refs/heads/main",
318 "systemctl start valley-identity.service",
319 )
320
321 # The contributor's push of a branch, and its ready. A unit that
322 # requires valley-init can start it again at any time, and the host
323 # refuses pushes, writing nothing, until it converges; so each is
324 # tried until the host takes it.
325 def push_ready(branch):
326 host.wait_until_succeeds(f"{contributor} git push --quiet origin {branch}", timeout=60)
327 host.wait_until_succeeds(f"{contributor} valley ready {branch}", timeout=60)
328
329 # A branch of the project with the first check's script given, and
330 # the flake given, pushed by the contributor and readied.
331 def ready(branch, first, flake="${flake}"):
332 host.succeed(
333 f"cd /root/project && git checkout --quiet -b {branch} origin/main",
334 f"cp {first} /root/project/first.sh && echo {branch} >> /root/project/README.md",
335 f"cp {flake} /root/project/flake.nix",
336 f"cd /root/project && git add -A && {commit} -m {branch}",
337 )
338 push_ready(branch)
339
340 with subtest("the instance and the project are seeded, and a change is ready"):
341 host.succeed("mkdir /srv/hung.git && chown git:git /srv/hung.git", f"{git} init --quiet --bare /srv/hung.git")
342 land_instance(None)
343 host.succeed(
344 "mkdir -p /tmp/project/policy",
345 "cp ${flake} /tmp/project/flake.nix",
346 "cp ${flakeLock} /tmp/project/flake.lock",
347 "cp ${spin} /tmp/project/first.sh",
348 "cp ${spin} /tmp/project/second.sh",
349 "echo 'git@host:instance.git' > /tmp/project/policy/valley",
350 "echo project > /tmp/project/README.md",
351 f"cd /tmp/project && git init --quiet --initial-branch=main && git add -A && {commit} -m project",
352 "chown -R git:git /tmp/project",
353 f"{git} -C /srv/git/project.git fetch --quiet /tmp/project main:refs/heads/main",
354 "mkdir -p /root/keys && install -m 600 ${keys}/contributor /root/keys/contributor",
355 f"GIT_SSH_COMMAND={ssh} git clone --quiet git@localhost:project.git /root/project",
356 "git -C /root/project config valley.principal contributor",
357 "git -C /root/project config user.name contributor",
358 "git -C /root/project config user.email contributor@localhost",
359 )
360 ready("good", "${spin}")
361
362 with subtest("the first start makes the key, readable by the worker alone, and says its public halves"):
363 host.fail(f"test -e {state}/key")
364 # What an earlier start killed half way leaves: a partial key and
365 # public half under the temporary names, and a public half with
366 # no key.
367 host.succeed(
368 f"sudo -u valley-worker sh -c 'echo partial > {state}/key.new;"
369 f" echo partial > {state}/key.new.pub; echo stale > {state}/key.pub'"
370 )
371 # Not enrolled yet, so the host's sshd turns the worker away and
372 # the pass stops before it builds anything.
373 host.fail("systemctl start valley-worker.service")
374 assert host.succeed(f"stat -c '%a %U %G' {state}").strip() == "700 valley-worker valley-worker"
375 assert host.succeed(f"stat -c '%a %U %G' {state}/key").strip() == "400 valley-worker valley-worker"
376 host.succeed(f"test -f {state}/key && test ! -L {state}/key")
377 for other in ["git", "valley-integrator", "nobody"]:
378 host.fail(f"sudo -u {other} cat {state}/key")
379 public = host.succeed(f"cat {state}/key.pub").strip()
380 verifier = host.succeed(f"cat {state}/verifier").strip()
381 assert verifier.startswith("worker/attestations+"), verifier
382 keyhash = verifier.split("+")[1]
383 said = journal()
384 assert f"the worker's ssh public key is {public}" in said, said
385 assert f"the worker's verifier line is {verifier}" in said, said
386 assert "PRIVATE KEY" not in said, said
387 assert host.succeed(f"ssh-keygen -y -f {state}/key").split()[1] == public.split()[1]
388 host.fail(f"ls {state} | grep -q '^key.new'")
389 fingerprint = host.succeed(f"ssh-keygen -lf {state}/key").strip()
390 assert attestations() == []
391
392 with subtest("enrolled in the registry, the worker builds the ready change's checks side by side and publishes them"):
393 # The runs of the compiler and the signers publisher that follow
394 # the landing on the instance's main, and the compiler's start by
395 # hand in land_instance, run no valley-init, whose run would
396 # pause every push.
397 init_run = "systemctl show -P InvocationID valley-init"
398 before = host.succeed(init_run)
399 land_instance(" ".join(public.split()[:2]))
400 host.succeed(f"grep -q '^worker/attestations+{keyhash}+' /var/lib/valley-identity/known-signers")
401 host.wait_until_succeeds(
402 f"{git} -C /srv/git/instance.git cat-file blob refs/the-valley/signers:known-signers"
403 f" | grep -q '^worker/attestations+{keyhash}+'",
404 timeout=60,
405 )
406 assert host.succeed(init_run) == before, "a landing on the instance ran valley-init again"
407 host.succeed("systemd-run --unit=valley-worker-e2e-sampler ${sampler}")
408 host.succeed("systemctl start valley-worker.service")
409 host.succeed("systemctl stop valley-worker-e2e-sampler")
410 said = journal()
411 assert "building first, second" in said, said
412 refs = attestations()
413 assert len(refs) == 1 and refs[0].endswith(f"/{keyhash}"), refs
414 assert f"published {refs[0]}" in said, said
415 for check in ["first", "second"]:
416 host.succeed(f"{git} -C /srv/git/project.git cat-file -e {refs[0]}:{check}/statement.note")
417 # Each check's result records the capacity the pass built on: the
418 # slots, the default two batches, nix's max-jobs and cores, and
419 # the machine's CPUs.
420 import json
421 results = [
422 r for r in map(json.loads, host.succeed(f"cat {state}/telemetry/stream/seg-*.jsonl").splitlines())
423 if r["type"] == "check.result"
424 ]
425 assert sorted(r["check"] for r in results) == ["first", "second"], results
426 assert all(r["data"]["capacity"] == "slots=2 batches=2 max_jobs=2 cores=2 cpus=6" for r in results), results
427 # Both checks at once, each in the daemon's cgroup, inside the
428 # slice, each told it may use the 2 cores the host configures.
429 builders = [int(n) for n in host.succeed("cat /tmp/builders").split()]
430 assert max(builders) >= 2, builders
431 cgroups = set(host.succeed("cat /tmp/build-cgroups").split())
432 assert cgroups and all(c.startswith("0::/valley.slice/valley-builds.slice/nix-daemon.service") for c in cgroups), cgroups
433 for check in ["first", "second"]:
434 assert host.succeed(f"cat /nix/store/*-worker-{check}").strip() == "2", check
435 for unit in ["valley-worker.service", "nix-daemon.service"]:
436 assert host.succeed(f"systemctl show -p Slice --value {unit}").strip() == "valley-builds.slice", unit
437
438 with subtest("the timer runs the next pass, which finds the evidence on origin and builds nothing"):
439 # The pass above read the change again after publishing, and said
440 # this line once already.
441 covered = journal().count("origin holds evidence for every nix check it requires")
442 host.succeed("systemctl start valley-worker.timer")
443 host.wait_until_succeeds(
444 "test $(journalctl -u valley-worker -o cat | grep -c 'origin holds evidence for every nix check it requires')"
445 f" -gt {covered}",
446 timeout=150,
447 )
448 host.succeed("systemctl stop valley-worker.timer")
449 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating")
450 assert len(attestations()) == 1
451
452 def idle():
453 host.wait_until_succeeds(
454 "test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating"
455 f" && test ! -e {wake}/due",
456 timeout=300,
457 )
458
459 def started():
460 return unit_property("valley-worker.service", "ExecMainStartTimestampMonotonic")
461
462 with subtest("the wake directory is the worker's and its writers', and the worker's access is unchanged"):
463 assert host.succeed(f"stat -c '%U %G %a' {wake}").strip() == "valley-worker valley-worker-wake 770"
464 assert "valley-worker-wake" in host.succeed("id -nG git").split()
465 assert "valley-worker-wake" in host.succeed(f"id -nG {unit_property('valley-integrator@project.service', 'User')}").split()
466 assert host.succeed("id -nG valley-worker").split() == ["valley-worker"]
467 host.fail("sudo -u valley-worker ls /srv/git/project.git/refs")
468 host.succeed("systemctl cat valley-worker.path | grep -qx 'PathExists=/var/lib/valley-worker-wake/due'")
469 assert unit_property("valley-worker.service", "StartLimitIntervalUSec") == "0"
470 assert unit_property("valley-worker.service", "RestartForceExitStatus") == "75"
471 host.fail("systemctl show -p WantedBy --value valley-worker.service | grep -q multi-user")
472 # The marks the seeding pushes and the signer publication left
473 # are read by one pass, which builds nothing.
474 host.succeed("systemctl start valley-worker.path")
475 idle()
476 host.succeed(f"test ! -e {wake}/claimed")
477 assert len(attestations()) == 1
478
479 def head(branch):
480 return host.succeed(f"git -C /root/project rev-parse --short=7 {branch}").strip()
481
482 def told(commit, what):
483 return journal().count(f" at {commit}: {what}")
484
485 def wait_said(commit, what, timeout):
486 host.wait_until_succeeds(f"journalctl -u valley-worker -o cat | grep -qF ' at {commit}: {what}'", timeout=timeout)
487
488 with subtest("a ready push starts a pass at once with no timer"):
489 import time
490 host.fail("systemctl is-active valley-worker.timer")
491 ready("wake-first", "${spin}")
492 readied = time.monotonic()
493 wait_said(head("wake-first"), "building", 120)
494 print(f"ready to building: {time.monotonic() - readied:.1f}s")
495 wait_said(head("wake-first"), "published", 120)
496 idle()
497 host.succeed(f"test ! -e {wake}/claimed")
498
499 with subtest("a worker push refused while valley-init converges is tried again once it has"):
500 # valley-init deletes the converged record while it runs, and the
501 # host refuses every push until the record is back. The change is
502 # pushed and readied first, and the pass starts with pushes
503 # paused.
504 host.succeed("systemctl stop valley-worker.path")
505 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-init)\" != activating", timeout=60)
506 ready("paused", "${spin}")
507 host.succeed("mv /srv/git/.valley-converged /tmp/valley-converged", "systemctl start valley-worker.path")
508 wait_said(head("paused"), "origin paused pushes while it converges", 120)
509 host.succeed("mv /tmp/valley-converged /srv/git/.valley-converged")
510 wait_said(head("paused"), "published", 120)
511 assert told(head("paused"), "could not publish") == 0
512 idle()
513 host.succeed(f"{contributor} valley withdraw paused")
514 idle()
515
516 def eval_spans():
517 # When each attest run's evaluation began and ended, how long it
518 # waited to be admitted, and its peak memory, from its eval.start
519 # and eval.end records, in the order they began.
520 import datetime
521 import json
522 spans = {}
523 for line in host.succeed(f"cat {state}/telemetry/stream/seg-*.jsonl 2>/dev/null || true").splitlines():
524 r = json.loads(line)
525 if r["type"] in ("eval.start", "eval.end"):
526 spans.setdefault(r["run"], {})[r["type"]] = r
527 return sorted(
528 (datetime.datetime.fromisoformat(s["eval.start"]["time"].replace("Z", "+00:00")),
529 datetime.datetime.fromisoformat(s["eval.end"]["time"].replace("Z", "+00:00")),
530 s["eval.end"]["data"]["eval_wait_ms"],
531 s["eval.end"]["data"]["eval_max_rss_bytes"])
532 for s in spans.values() if len(s) == 2
533 )
534
535 def seed_peaks(mib):
536 # The project's record of evaluation peaks, as if its last
537 # evaluation had peaked at mib MiB, so the next evaluations are
538 # estimated at that.
539 import json
540 record = json.dumps({"projects": {"project": [mib << 20]}})
541 host.succeed(
542 f"echo {shlex.quote(record)} > {state}/evaluations.json",
543 f"chown valley-worker:valley-worker {state}/evaluations.json",
544 )
545
546 def peaks():
547 import json
548 return json.loads(host.succeed(f"cat {state}/evaluations.json"))["projects"]["project"]
549
550 # One pass, started by hand with the timer and the path unit stopped,
551 # so every change readied after it starts is built by that pass or by
552 # none. Its first scan finds the long and the short change, and it
553 # starts both batches at once. Each evaluation is estimated at 600
554 # MiB, and two do not fit the 1 GiB budget, so they take turns. Each
555 # ready push marks due, and the pass claims the mark itself and reads
556 # again. The long change builds until the test opens its gate, once
557 # the broken change has failed. Meanwhile the short change is built
558 # and published in the pass's second slot, the broken change fails,
559 # and two changes with one tree are built once. No two batches'
560 # evaluations overlap. The pass acknowledges every mark it claimed.
561 with subtest("a pass builds a short change beside a long one, evaluating one at a time when two do not fit the budget, takes on changes readied meanwhile, builds one tree once, and goes on past a failure"):
562 host.succeed("systemctl stop valley-worker.path")
563 evaluated = len(eval_spans())
564 seed_peaks(600)
565 ready("long", "${long}")
566 long = head("long")
567 ready("short", "${spin}")
568 short = head("short")
569 host.succeed("systemctl start --no-block valley-worker.service")
570 wait_said(long, "building", 120)
571 mark = started()
572 ready("early-broken", "${broken}")
573 early_broken = head("early-broken")
574 wait_said(short, "published", 120)
575 # The short change's evidence is on origin while the long batch
576 # still builds.
577 assert told(long, "published") == 0, journal()
578 assert unit_property("valley-worker.service", "ActiveState") == "activating"
579 # Two branches with one tree, readied one right after the other.
580 ready("twin-a", "${spin}")
581 host.succeed(
582 "cd /root/project && git checkout --quiet -b twin-b origin/main && git checkout --quiet twin-a -- .",
583 f"cd /root/project && {commit} -m twin-b",
584 )
585 push_ready("twin-b")
586 trees = host.succeed("git -C /root/project rev-parse twin-a^{tree} twin-b^{tree}").split()
587 assert trees[0] == trees[1], trees
588 twins = [head("twin-a"), head("twin-b")]
589 wait_said(early_broken, "the batch did not pass", 120)
590 # Writing to the gate waits until the long build reads it.
591 host.succeed("timeout 300 sh -c 'echo open > /run/valley-worker-e2e-gate/long'")
592 wait_said(long, "published", 300)
593 host.wait_until_succeeds(
594 "test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating", timeout=300
595 )
596 said = journal()
597 assert started() == mark, "a second pass ran"
598 # The long, short and broken batches and the twins' one batch
599 # each evaluated, and each evaluation ended before the next began.
600 spans = eval_spans()[evaluated:]
601 print(f"evaluations: {[(str(b), str(e), w, p) for b, e, w, p in spans]}")
602 assert len(spans) >= 4, spans
603 assert all(p > 0 for _, _, _, p in spans), spans
604 for (_, ended, _, _), (began, _, _, _) in zip(spans, spans[1:]):
605 assert ended <= began, spans
606 for change in [long, short, early_broken]:
607 assert told(change, "building") == 1, (change, said)
608 assert said.index(f" at {early_broken}: the batch did not pass") < said.index(f" at {long}: published"), said
609 assert sum(told(t, "building") for t in twins) == 1, said
610 assert sum(told(t, "published") for t in twins) == 1, said
611 assert any(told(t, "origin holds evidence for every nix check it requires") for t in twins), said
612 host.succeed(f"test ! -e {wake}/due -a ! -e {wake}/claimed")
613 # The record keeps the project's last five peaks: the four or
614 # more this pass measured, each a real evaluation's, and the
615 # seeded one before them while there is room.
616 kept = peaks()
617 assert len(kept) == 5 and all(0 < p < 600 << 20 for p in kept[-4:]), kept
618 # Every scan reads each ready change, so the changes this pass
619 # built are withdrawn, and the passes below read no more changes
620 # than they did before this scenario.
621 for branch in ["long", "short", "early-broken", "twin-a", "twin-b"]:
622 host.succeed(f"{contributor} valley withdraw {branch}")
623
624 # A pass whose first scan finds two changes, each estimated at 300
625 # MiB: both fit the 1 GiB budget, so their evaluations overlap. The
626 # pass starts the second batch a moment after the first, so each
627 # change's flake evaluates slowly.
628 with subtest("evaluations whose estimates fit the budget together run at once"):
629 evaluated = len(eval_spans())
630 seed_peaks(300)
631 ready("fit-a", "${spin}", "${slowFlake}")
632 ready("fit-b", "${spin}", "${slowFlake}")
633 host.succeed("systemctl start --no-block valley-worker.service")
634 wait_said(head("fit-a"), "published", 120)
635 wait_said(head("fit-b"), "published", 120)
636 host.wait_until_succeeds(
637 "test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating", timeout=120
638 )
639 spans = eval_spans()[evaluated:]
640 print(f"evaluations: {[(str(b), str(e), w, p) for b, e, w, p in spans]}")
641 assert len(spans) == 2 and all(p > 0 for _, _, _, p in spans), spans
642 assert spans[1][0] < spans[0][1], spans
643 for branch in ["fit-a", "fit-b"]:
644 host.succeed(f"{contributor} valley withdraw {branch}")
645 host.succeed("systemctl start valley-worker.path")
646 idle()
647 host.succeed(f"test ! -e {wake}/claimed")
648
649 # A change's first version builds a long batch, and the change gains
650 # a second version with another tree, as a restack makes one. The
651 # scan that finds it stops the long batch, whose build ends, and the
652 # second version builds and publishes. The stopped batch is recorded
653 # as cancelled, with its reason, and as no failure. Both versions'
654 # commits are pushed at once, so only the second ready marks the
655 # worker while the long batch runs.
656 with subtest("a running batch whose version another tree supersedes is stopped, and the new version builds"):
657 import json
658 change_id = "zyxwvutsrqponmlk" * 2
659 trailer = shlex.quote(f"Change-Id: {change_id}")
660 host.succeed(
661 "cd /root/project && git checkout --quiet -b superseded origin/main",
662 "cp ${stopped} /root/project/first.sh && echo superseded >> /root/project/README.md",
663 f"cd /root/project && git add -A && {commit} -m superseded -m {trailer}",
664 "cp ${spin} /root/project/first.sh",
665 f"cd /root/project && git add -A && {commit} -m superseded -m {trailer}",
666 )
667 host.wait_until_succeeds(f"{contributor} git push --quiet origin superseded", timeout=60)
668 old, new = head("superseded~1"), head("superseded")
669 first = host.succeed("git -C /root/project rev-parse superseded~1").strip()
670 host.wait_until_succeeds(f"{contributor} valley ready --head {first} superseded", timeout=60)
671 host.wait_until_succeeds("pgrep -f 'valley-stopped-buil[d]'", timeout=120)
672 host.wait_until_succeeds(f"{contributor} valley ready superseded", timeout=60)
673 wait_said(old, "the batch stopped; nothing is published", 60)
674 host.wait_until_fails("pgrep -f 'valley-stopped-buil[d]'", timeout=10)
675 wait_said(new, "published", 120)
676 host.succeed(f"{contributor} valley withdraw superseded")
677 idle()
678 assert told(old, "stopping the batch: v2 supersedes it") == 1, journal()
679 assert told(old, "published") == 0, journal()
680 worker = json.loads(host.succeed(f"cat {state}/telemetry/state.json"))
681 ended = [a for a in worker["recent"] if a["kind"] == "build" and a.get("change") == change_id]
682 assert [(a["change_version"], a["result"]) for a in ended] == [(2, "passed"), (1, "cancelled")], ended
683 assert "v2 supersedes it" in ended[1]["reason"], ended
684 assert not [f for f in worker["failures"] or [] if f.get("change") == change_id], worker["failures"]
685
686 with subtest("marks from the git user and the integrator's user are one file, and a stale mark builds nothing"):
687 host.succeed("systemctl stop valley-worker.path")
688 integrator = unit_property("valley-integrator@project.service", "User")
689 for who in ["git", integrator, "git", integrator]:
690 host.succeed(f"sudo -u {who} bash -c 'set -C; : > {wake}/due' 2>/dev/null || test -e {wake}/due")
691 assert host.succeed(f"ls -A {wake}").split() == ["due", "lock"]
692 host.succeed(f"rm {wake}/due && sudo -u {integrator} bash -c 'set -C; : > {wake}/due'")
693 building = journal().count("building first, second")
694 pushes = journal().count("published ")
695 host.succeed("systemctl start valley-worker.path")
696 idle()
697 assert host.succeed(f"ls -A {wake}").split() == ["lock"]
698 assert journal().count("building first, second") == building
699 assert journal().count("published ") == pushes
700
701 with subtest("a claim a killed pass left starts nothing, and the next pass acknowledges it"):
702 host.succeed(f"sudo -u valley-worker touch {wake}/claimed")
703 mark = started()
704 host.succeed("sleep 5")
705 assert started() == mark
706 host.succeed("systemctl start valley-worker.service")
707 host.succeed(f"test ! -e {wake}/claimed")
708
709 with subtest("a pass that cannot claim due reads all the same and is started again only after its hold-off"):
710 restarts = int(unit_property("valley-worker.service", "NRestarts"))
711 host.succeed(f"chmod 0550 {wake} && touch {wake}/due")
712 host.wait_until_succeeds("journalctl -u valley-worker -o cat | grep -q 'could not claim'", timeout=60)
713 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value valley-worker)\" = auto-restart")
714 # due is still there, and nothing starts a pass during the
715 # hold-off of one interval.
716 mark = started()
717 host.sleep(5)
718 assert started() == mark
719 assert int(unit_property("valley-worker.service", "NRestarts")) == restarts
720 host.fail("systemctl is-failed valley-worker.path")
721 assert "origin holds evidence for every nix check it requires" in journal()
722 host.succeed(f"chmod 0770 {wake}")
723 idle()
724 host.succeed("systemctl is-active valley-worker.path")
725
726 with subtest("a push to the instance, which the worker does not build, and a check request's create, move and delete mark it due, and knots and bookkeeping do not"):
727 host.succeed("systemctl stop valley-worker.path")
728 host.succeed(
729 f"cd /root && rm -rf instance && GIT_SSH_COMMAND={ssh} git clone --quiet git@localhost:instance.git instance",
730 f"cd /root/instance && git checkout --quiet -b floor-probe && echo probe > probe && git add probe && {commit} -m probe",
731 )
732 hook = "/srv/git/instance.git/hooks/post-receive.d/valley-wake"
733 zero = "0" * 40
734 host.succeed(f"echo '{zero} {zero} refs/the-valley/knots' | sudo -u git {hook}")
735 host.succeed(f"echo '{zero} {zero} refs/the-valley/integration-outcomes/main/x' | sudo -u git {hook}")
736 host.succeed(f"test ! -e {wake}/due")
737 host.succeed(f"cd /root/instance && GIT_SSH_COMMAND={ssh} git push --quiet origin floor-probe")
738 host.succeed(f"test -e {wake}/due")
739 request = "refs/the-valley/check-requests/alice/0123456789abcdef/0123456789abcdef"
740 for old, new in [(zero, "1" * 40), ("1" * 40, "2" * 40), ("2" * 40, zero)]:
741 host.succeed(f"rm {wake}/due && echo '{old} {new} {request}' | sudo -u git {hook} && test -e {wake}/due")
742
743 with subtest("a signer publication marks the worker due only when it moves the ref"):
744 host.succeed(f"rm -f {wake}/due")
745 host.succeed("systemctl start valley-signers.service")
746 host.succeed(f"test ! -e {wake}/due")
747 host.succeed(f"{git} -C /srv/git/instance.git update-ref -d refs/the-valley/signers")
748 host.succeed("systemctl start valley-signers.service")
749 host.succeed(f"test -e {wake}/due")
750 host.succeed("systemctl start valley-worker.path")
751 idle()
752
753 with subtest("with the mirror and the bus hung, a landing by the integrator's service and a ready push mark the worker at once"):
754 # The mirror takes the drain's push of main and never answers it,
755 # and what listens at the bus's address takes a connection and
756 # never answers it.
757 host.succeed(
758 "printf '#!/bin/sh\\nexec /run/current-system/sw/bin/sleep 100001\\n' > /srv/hung.git/hooks/pre-receive",
759 "chmod 755 /srv/hung.git/hooks/pre-receive",
760 "systemctl stop valley-bus.service",
761 "systemd-run --unit=hung-bus ${pkgs.socat}/bin/socat TCP-LISTEN:4222,bind=127.0.0.1,fork,reuseaddr"
762 " SYSTEM:'exec ${pkgs.coreutils}/bin/sleep 100000'",
763 )
764 host.wait_for_open_port(4222)
765 # The good change lands by the integrator's own service, which
766 # marks due from inside its sandbox. The request ref is written
767 # locally, which runs no hook, so the landing's mark is the only one.
768 host.succeed("systemctl stop valley-worker.path")
769 base = host.succeed(f"{git} -C /srv/git/project.git rev-parse refs/heads/main").strip()
770 good = host.succeed("git -C /root/project rev-parse good").strip()
771 host.succeed(f"{git} -C /srv/git/project.git update-ref refs/the-valley/integration-requests/main/good {good}")
772 host.wait_until_succeeds(
773 f"test \"$({git} -C /srv/git/project.git rev-parse refs/heads/main^)\" = {base}", timeout=120
774 )
775 landed = time.monotonic()
776 host.wait_until_succeeds(f"test -e {wake}/due", timeout=10)
777 print(f"landing to mark, mirror and bus hung: {time.monotonic() - landed:.1f}s")
778 host.wait_until_succeeds(
779 "journalctl -u valley-integrator@project -o cat | grep -q 'bus publish of .* FAILED'", timeout=120
780 )
781 said_by = host.succeed("journalctl -u valley-integrator@project -o cat")
782 assert said_by.index("wake the check worker is due") < said_by.index("bus publish of"), said_by
783 host.wait_until_succeeds("pgrep -f 'sleep 10000[1]'", timeout=60)
784 host.succeed("systemctl start valley-worker.path")
785 idle()
786 # With the mirror's push still hung, a ready push starts a pass.
787 ready("hung", "${spin}")
788 readied = time.monotonic()
789 wait_said(head("hung"), "building", 120)
790 print(f"ready to building, mirror and bus hung: {time.monotonic() - readied:.1f}s")
791 wait_said(head("hung"), "published", 120)
792 idle()
793 host.succeed("pgrep -f 'sleep 10000[1]'")
794 host.succeed(
795 "rm /srv/hung.git/hooks/pre-receive && pkill -f 'sleep 10000[1]'",
796 "systemctl stop hung-bus && systemctl start valley-bus.service",
797 )
798
799 with subtest("a floor landed in the instance, which the worker does not build, marks it, and the next pass reads the floor it landed"):
800 host.succeed("systemctl stop valley-worker.path")
801 # Each scan reads every ready change, and the new floor's third
802 # check is added to the evidence of each, so the changes earlier
803 # scenarios left ready are withdrawn but one.
804 for branch in ["good", "wake-first"]:
805 host.succeed(f"{contributor} valley withdraw {branch}")
806 host.succeed(f"rm -f {wake}/due")
807 floor_base = host.succeed(f"{git} -C /srv/git/instance.git rev-parse refs/heads/main").strip()
808 host.succeed(
809 "cp ${floorThird} /tmp/instance/policy/instance/floor.cue",
810 f"cd /tmp/instance && sudo -u git {commit} -am third",
811 f"{git} -C /srv/git/instance.git fetch --quiet /tmp/instance main:refs/the-valley/integration-requests/main/third",
812 )
813 host.wait_until_succeeds(
814 f"test \"$({git} -C /srv/git/instance.git rev-parse refs/heads/main^)\" = {floor_base}", timeout=120
815 )
816 host.wait_until_succeeds(f"test -e {wake}/due", timeout=10)
817 host.succeed("journalctl -u valley-integrator@instance -o cat | grep -q 'wake the check worker is due'")
818 # The pass reads the new floor. A change built before it holds this
819 # worker's evidence for its tree without the third check, so the
820 # pass builds that check and adds its note to the ref.
821 host.succeed("systemctl start valley-worker.path")
822 host.wait_until_succeeds(
823 "journalctl -u valley-worker -o cat | grep -q ': added third to refs/the-valley/attestations/'", timeout=120
824 )
825 idle()
826 assert "instance:" not in journal()
827
828 with subtest("a pass killed during a build leaves its claim, and the timer's next pass builds the change"):
829 # The push and the ready mark are made before the pass starts,
830 # so they are one due, which the pass claims.
831 host.succeed("systemctl stop valley-worker.path")
832 ready("killed", "${slow}")
833 killed = head("killed")
834 host.succeed("systemctl start valley-worker.path")
835 wait_said(killed, "building", 120)
836 host.wait_until_succeeds("ps -eo user= | grep -q '^nixbld'", timeout=60)
837 host.succeed("systemctl kill --signal=KILL valley-worker.service")
838 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" = failed", timeout=60)
839 assert host.succeed(f"ls -A {wake}").split() == ["claimed", "lock"]
840 host.wait_until_succeeds("! ps -eo user= | grep -q '^nixbld'", timeout=60)
841 # Nothing watches claimed, so nothing starts a pass, until the
842 # timer runs the recovery scan one interval after the kill.
843 mark = started()
844 host.sleep(5)
845 assert started() == mark
846 assert told(killed, "published") == 0
847 host.succeed("systemctl start valley-worker.timer")
848 wait_said(killed, "published", 300)
849 idle()
850 host.succeed(f"test ! -e {wake}/claimed")
851 assert told(killed, "building") == 2
852
853 with subtest("a pass that cannot reach the repositories leaves its claim, and the timer's next pass builds the change with no new mark"):
854 # The timer is stopped until sshd is back, so the pass that fails
855 # is the one the path starts.
856 host.succeed("systemctl stop valley-worker.timer valley-worker.path")
857 ready("outage", "${spin}")
858 outage = head("outage")
859 host.succeed("systemctl stop sshd.service")
860 host.succeed("systemctl start valley-worker.path")
861 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" = failed", timeout=120)
862 assert host.succeed(f"ls -A {wake}").split() == ["claimed", "lock"]
863 assert told(outage, "building") == 0
864 triggered = unit_property("valley-worker.timer", "LastTriggerUSecMonotonic")
865 host.succeed("systemctl start sshd.service valley-worker.timer")
866 wait_said(outage, "published", 300)
867 assert unit_property("valley-worker.timer", "LastTriggerUSecMonotonic") != triggered
868 idle()
869 host.succeed(f"test ! -e {wake}/claimed")
870
871 with subtest("a failed batch is not built again before its wait, however many marks and timer passes come"):
872 ready("broken", "${broken}")
873 broken = head("broken")
874 wait_said(broken, "the batch did not pass", 120)
875 idle()
876 ready("unrelated", "${spin}")
877 wait_said(head("unrelated"), "published", 120)
878 idle()
879 host.succeed(
880 f"{git} -C /srv/git/instance.git update-ref -d refs/the-valley/signers",
881 "systemctl start valley-signers.service",
882 )
883 idle()
884 host.succeed(f"cd /root/instance && echo again >> probe && {commit} -am again && GIT_SSH_COMMAND={ssh} git push --quiet origin floor-probe")
885 idle()
886 triggered = unit_property("valley-worker.timer", "LastTriggerUSecMonotonic")
887 host.wait_until_succeeds(
888 f"test \"$(systemctl show -p LastTriggerUSecMonotonic --value valley-worker.timer)\" != '{triggered}'", timeout=150
889 )
890 idle()
891 assert told(broken, "building") == 1
892 assert told(broken, "the batch did not pass") == 1
893 assert told(broken, "its batch") >= 4, journal()
894 # The scenarios below start each pass themselves.
895 host.succeed("systemctl stop valley-worker.timer valley-worker.path")
896 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating")
897
898 with subtest("the key is the same after many starts, and is not said again"):
899 host.succeed("systemctl start valley-worker.service")
900 assert host.succeed(f"ssh-keygen -lf {state}/key").strip() == fingerprint
901 assert host.succeed(f"cat {state}/verifier").strip() == verifier
902 assert journal().count("verifier line is") == 1
903
904 with subtest("the worker roots the outputs it builds, prunes the roots it has not used, and a later change with the same checks reuses them without building"):
905 import json
906 roots = f"{state}/roots"
907
908 def rooted():
909 links = host.succeed(f"find {roots} -mindepth 1 -maxdepth 1 -type l -printf '%f\\n'").split()
910 return {link: host.succeed(f"readlink {roots}/{link}").strip() for link in links}
911
912 def registered(paths):
913 info = json.loads(host.succeed("nix --extra-experimental-features nix-command path-info --json " + " ".join(paths)))
914 if isinstance(info, dict):
915 info = [dict(v, path=k) for k, v in info.items()]
916 return {i["path"]: i["registrationTime"] for i in info}
917
918 def publish(branch):
919 # Every root's last use is set long past, so the pass prunes
920 # each one, and its batch roots again only what it uses.
921 host.succeed(f"find {roots} -mindepth 1 -maxdepth 1 -type l -exec touch -h -d @1 {{}} +")
922 ready(branch, "${spin}")
923 host.succeed("systemctl start valley-worker.service")
924 assert told(head(branch), "published") == 1
925 now = rooted()
926 assert now, f"the batch for {branch} rooted no output"
927 for link in now:
928 assert int(host.succeed(f"stat -c %Y {roots}/{link}")) > 1, f"{link} was not used by the batch for {branch}, and was not pruned"
929 return now
930
931 first = publish("kept")
932 known = host.succeed("nix-store --gc --print-roots")
933 for link, path in first.items():
934 assert link == path.removeprefix("/nix/store/"), (link, path)
935 assert f"{roots}/{link} -> {path}" in known, f"the daemon does not know {roots}/{link}"
936 built = registered(first.values())
937 again = publish("kept-again")
938 assert again == first, (first, again)
939 assert registered(again.values()) == built, "an output was built again"
940
941 # The project's own layer, landed below, gives docs a class that a
942 # third check follows.
943 with subtest("a landing that touches a class sets the check that follows it due, which runs on main after the ready change's checks and adds its pass to the worker's ref for main's tree"):
944 # Each scan reads every ready change, so the ones earlier
945 # scenarios left ready are withdrawn first.
946 for branch in ["hung", "killed", "outage", "broken", "unrelated", "kept", "kept-again"]:
947 host.execute(f"{contributor} valley withdraw {branch}")
948 host.succeed(
949 "cd /root/project && git checkout --quiet -b follows origin/main && mkdir -p policy/project docs",
950 "cp ${followsLayer} /root/project/policy/project/follows.cue && echo docs > /root/project/docs/a.md",
951 f"cd /root/project && git add -A && {commit} -m follows",
952 )
953 push_ready("follows")
954 host.succeed("systemctl start valley-worker.service")
955 main_tip = head("follows")
956 assert told(main_tip, "published") == 1
957 # A clean landing leaves main at the tree the worker attested at
958 # the gate. It is a local write, as an operator seeds main.
959 host.succeed(f"{git} -C /srv/git/project.git update-ref refs/heads/main $({git} -C /srv/git/project.git rev-parse follows)")
960 ready("after-follows", "${spin}")
961 main_state = host.succeed(f"{contributor} valley pending").splitlines()[0]
962 assert main_state.startswith("main ◐ clearing · later due") and main_tip in main_state, main_state
963 host.succeed("systemctl start valley-worker.service")
964 journal_now = journal()
965 assert journal_now.index(f" at {head('after-follows')}: building") < journal_now.index(f": main at {main_tip}: building later"), journal_now
966 assert journal_now.count(f": main at {main_tip}: added later") == 1
967 notes = [host.succeed(f"{git} -C /srv/git/project.git ls-tree --name-only {ref}").split() for ref in attestations()]
968 # The gate's notes, as the floor stands by now, and the pass.
969 assert [n for n in notes if "later" in n] == [["first", "later", "second", "third"]], notes
970 main_state = host.succeed(f"{contributor} valley pending").splitlines()[0]
971 assert main_state == f"main ✓ clear · checks passed at {main_tip}", main_state
972 '';
973 };
974}