gunk-dev/the-valley

worker-e2e.nix

source16d422ffa0femain's published tip history
34.2 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. A floor landed in the
16# instance, which the worker does not build, marks it, and the next pass
17# reads the new floor. A pass killed during a build, and a pass that
18# cannot reach the repositories, leave their claim, and the timer's next
19# pass builds the change with no new mark. A failed batch is not built
20# again before its wait, however many marks and timer passes come. Last,
21# the key is the same after many starts.
22#
23# The worker's interval here is 15 seconds rather than the module's
24# minute, so a scenario that waits for a timer pass or a hold-off waits
25# seconds. module-eval holds what the module renders: the minute, the
26# slice's caps, and the nix daemon's OOM policy.
27{
28 pkgs,
29 lib,
30 self,
31 machineValley,
32 ...
33}:
34let
35 # Throwaway keys, made once at build time. They hold no authority
36 # anywhere: the machine that trusts them exists for one test run. The
37 # worker's key is not among them: the worker makes its own on the host.
38 keys = pkgs.runCommand "valley-worker-e2e-keys" { nativeBuildInputs = [ pkgs.openssh ]; } ''
39 mkdir $out
40 for who in integrator contributor; do
41 ssh-keygen -q -t ed25519 -N "" -C "$who" -f "$out/$who"
42 done
43 '';
44 pub = who: lib.fileContents "${keys}/${who}.pub";
45
46 declaration = pkgs.writeText "valley-worker-e2e.cue" ''
47 package valley
48
49 projects: {
50 // The instance repository, which carries the floor and the registry.
51 "instance": protection: refs: ["refs/heads/main"]
52 // The project's mirror is a local repository, which a scenario
53 // below makes hang.
54 "project": {
55 protection: {}
56 mirrors: ["/srv/hung.git"]
57 }
58 }
59 '';
60
61 # A floor that requires two nix checks of every change but one to the
62 # policy alone, so the instance's own floor lands by integration with no
63 # evidence. floorThird, which a scenario lands in the instance, requires a
64 # third check of the same attribute as the second.
65 floorWith = third: pkgs.writeText "floor.cue" ''
66 package verification
67
68 floor: {
69 checks: {
70 first: {runner: "nix", attribute: "first"}
71 second: {runner: "nix", attribute: "second"}
72 ${lib.optionalString third ''third: {runner: "nix", attribute: "second"}''}
73 }
74 classes: policy: {paths: {"policy/**": true}, requires: {}}
75 unclassified: {first: true, second: true${lib.optionalString third ", third: true"}}
76 }
77 '';
78 floor = floorWith false;
79 floorThird = floorWith true;
80
81 # The project's flake, with no inputs, so the machine builds it offline.
82 # Each check runs a script from the project's tree in the sandbox's
83 # shell, and the script is the derivation's one input. The project's own
84 # scripts spin for about half a second, several of the sampler's ticks,
85 # so the two builds a pass runs at once are seen at once, and write the
86 # cores the daemon gave them.
87 flake = pkgs.writeText "flake.nix" ''
88 {
89 outputs =
90 { self }:
91 let
92 check = name: script: derivation {
93 inherit name;
94 system = "x86_64-linux";
95 builder = "/bin/sh";
96 args = [ script ];
97 };
98 in
99 {
100 checks.x86_64-linux = {
101 first = check "worker-first" ./first.sh;
102 second = check "worker-second" ./second.sh;
103 };
104 };
105 }
106 '';
107 flakeLock = pkgs.writeText "flake.lock" ''{"nodes":{"root":{}},"root":"root","version":7}'';
108 spin = pkgs.writeText "spin.sh" ''
109 i=0
110 while [ $i -lt 250000 ]; do i=$((i+1)); done
111 echo $NIX_BUILD_CORES > $out
112 '';
113 # A build long enough to be killed in: about twenty seconds of spinning.
114 slow = pkgs.writeText "slow.sh" ''
115 i=0
116 while [ $i -lt 10000000 ]; do i=$((i+1)); done
117 echo $NIX_BUILD_CORES > $out
118 '';
119 broken = pkgs.writeText "broken.sh" "exit 1";
120
121 # What the daemon's builds look like while the worker runs: the number
122 # of build users with a process, and the cgroup of each such process,
123 # sampled ten times a second.
124 sampler = pkgs.writeShellScript "valley-worker-e2e-sampler" ''
125 PATH=${
126 lib.makeBinPath [
127 pkgs.coreutils
128 pkgs.gawk
129 pkgs.procps
130 ]
131 }
132 while :; do
133 ps -eo user:32=,cgroup:512= | awk '$1 ~ /^nixbld/' > /tmp/sample
134 awk '{print $1}' /tmp/sample | sort -u | wc -l >> /tmp/builders
135 awk '{print $2}' /tmp/sample >> /tmp/build-cgroups
136 sleep 0.1
137 done
138 '';
139in
140{
141 worker-e2e = pkgs.testers.runNixOSTest {
142 name = "valley-worker-e2e";
143 nodes.host = {
144 imports = [ self.nixosModules.default ];
145 # Six CPUs: more than the worker's slots, so the slots and not the
146 # CPU count decide how many checks build at once.
147 virtualisation.cores = 6;
148 virtualisation.memorySize = 2048;
149 environment.systemPackages = [
150 pkgs.git
151 machineValley
152 ];
153 services.valley = {
154 enable = true;
155 config = declaration;
156 buildSlice.enable = true;
157 authorizedKeys = [
158 {
159 principal = "contributor";
160 key = pub "contributor";
161 }
162 ];
163 identity.enable = true;
164 bus.enable = true;
165 integrator = {
166 enable = true;
167 signingKeyFile = "${keys}/integrator";
168 instanceProject = "instance";
169 signerProjects."worker/attestations" = [ "project" ];
170 };
171 # Two checks at once, each told it may use two cores, rather
172 # than the defaults of one check at a time on four.
173 worker = {
174 enable = true;
175 projects = [ "project" ];
176 signerName = "worker/attestations";
177 buildSlots = 2;
178 maxJobs = 2;
179 cores = 2;
180 # A timer pass, and the hold-off after a pass that could not
181 # claim due, come 15 seconds after the last pass ends. The
182 # window below in which the hold-off starts nothing is 5 seconds.
183 interval = "15s";
184 };
185 };
186 # The test starts each pass itself until it checks the timer, so no
187 # pass runs before the test is ready for it. A timer pass starts
188 # within a second of its interval, rather than up to a minute of
189 # systemd's accuracy later.
190 systemd.timers.valley-worker.timerConfig.OnActiveSec = lib.mkForce "1h";
191 systemd.timers.valley-worker.timerConfig.AccuracySec = "1s";
192 # The machine has no network. Without these, every new build waits
193 # for the daemon's lookups in cache.nixos.org to fail, and every boot
194 # waits for a DHCP lease on an interface nothing here uses.
195 nix.settings.substituters = lib.mkForce [ ];
196 networking.useDHCP = false;
197 };
198
199 testScript = ''
200 import shlex
201
202 host.wait_for_unit("multi-user.target")
203 host.succeed("systemctl is-active valley-worker.timer valley-worker.path")
204 host.succeed("systemctl stop valley-worker.timer valley-worker.path")
205
206 git = "sudo -u git git"
207 wake = "/var/lib/valley-worker-wake"
208 state = "/var/lib/valley-worker"
209 ssh = shlex.quote(
210 "ssh -i /root/keys/contributor -o IdentitiesOnly=yes -o BatchMode=yes"
211 " -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
212 )
213 contributor = f"cd /root/project && GIT_SSH_COMMAND={ssh}"
214 commit = "git -c user.name=contributor -c user.email=contributor@localhost commit --quiet"
215
216 def journal():
217 return host.succeed("journalctl -u valley-worker -o cat")
218
219 def unit_property(name, prop):
220 return host.succeed(f"systemctl show -p {prop} --value {name}").strip()
221
222 def attestations():
223 return host.succeed(
224 f"{git} -C /srv/git/project.git for-each-ref --format='%(refname)' refs/the-valley/attestations/"
225 ).split()
226
227 def registry(worker):
228 principals = [
229 '"contributor": {',
230 ' kind: "human"',
231 ' keys: [{class: "ssh-ed25519", bound: "host", public: "${
232 lib.concatStringsSep " " (lib.take 2 (lib.splitString " " (pub "contributor")))
233 }"}]',
234 ' grants: {push: boundary: "push", govern: boundary: "registry"}',
235 "}",
236 ]
237 if worker:
238 principals += [
239 '"worker": {',
240 ' kind: "machine"',
241 f' keys: [{{class: "ssh-ed25519", bound: "host", public: "{worker}", signs: "worker/attestations"}}]',
242 ' grants: push: boundary: "push"',
243 ' expires: "2099-01-01"',
244 "}",
245 ]
246 return "\n".join(
247 [
248 "package identity",
249 'boundaries: {"push": kind: "git-push", "registry": kind: "registry"}',
250 'genesis: "contributor"',
251 "principals: {",
252 ]
253 + principals
254 + ["}"]
255 )
256
257 # The instance's main carries the floor and the registry. It is
258 # landed by a local write, which runs no hook, as an operator seeds
259 # a protected repository.
260 def land_instance(worker):
261 host.succeed(
262 "rm -rf /tmp/instance && mkdir -p /tmp/instance/policy/instance /tmp/instance/identity",
263 "cp ${floor} /tmp/instance/policy/instance/floor.cue",
264 f"cat > /tmp/instance/identity/registry.cue <<'EOF'\n{registry(worker)}\nEOF",
265 f"cd /tmp/instance && git init --quiet --initial-branch=main && git add -A && {commit} -m instance",
266 "chown -R git:git /tmp/instance",
267 f"{git} -C /srv/git/instance.git fetch --quiet --force /tmp/instance main:refs/heads/main",
268 "systemctl start valley-identity.service",
269 )
270
271 # A branch of the project with the first check's script given,
272 # pushed by the contributor and readied.
273 def ready(branch, first):
274 host.succeed(
275 f"cd /root/project && git checkout --quiet -b {branch} origin/main",
276 f"cp {first} /root/project/first.sh && echo {branch} >> /root/project/README.md",
277 f"cd /root/project && git add -A && {commit} -m {branch}",
278 f"{contributor} git push --quiet origin {branch}",
279 f"{contributor} valley ready {branch}",
280 )
281
282 with subtest("the instance and the project are seeded, and a change is ready"):
283 host.succeed("mkdir /srv/hung.git && chown git:git /srv/hung.git", f"{git} init --quiet --bare /srv/hung.git")
284 land_instance(None)
285 host.succeed(
286 "mkdir -p /tmp/project/policy",
287 "cp ${flake} /tmp/project/flake.nix",
288 "cp ${flakeLock} /tmp/project/flake.lock",
289 "cp ${spin} /tmp/project/first.sh",
290 "cp ${spin} /tmp/project/second.sh",
291 "echo 'git@host:instance.git' > /tmp/project/policy/valley",
292 "echo project > /tmp/project/README.md",
293 f"cd /tmp/project && git init --quiet --initial-branch=main && git add -A && {commit} -m project",
294 "chown -R git:git /tmp/project",
295 f"{git} -C /srv/git/project.git fetch --quiet /tmp/project main:refs/heads/main",
296 "mkdir -p /root/keys && install -m 600 ${keys}/contributor /root/keys/contributor",
297 f"GIT_SSH_COMMAND={ssh} git clone --quiet git@localhost:project.git /root/project",
298 "git -C /root/project config valley.principal contributor",
299 "git -C /root/project config user.name contributor",
300 "git -C /root/project config user.email contributor@localhost",
301 )
302 ready("good", "${spin}")
303
304 with subtest("the first start makes the key, readable by the worker alone, and says its public halves"):
305 host.fail(f"test -e {state}/key")
306 # What an earlier start killed half way leaves: a partial key and
307 # public half under the temporary names, and a public half with
308 # no key.
309 host.succeed(
310 f"sudo -u valley-worker sh -c 'echo partial > {state}/key.new;"
311 f" echo partial > {state}/key.new.pub; echo stale > {state}/key.pub'"
312 )
313 # Not enrolled yet, so the host's sshd turns the worker away and
314 # the pass stops before it builds anything.
315 host.fail("systemctl start valley-worker.service")
316 assert host.succeed(f"stat -c '%a %U %G' {state}").strip() == "700 valley-worker valley-worker"
317 assert host.succeed(f"stat -c '%a %U %G' {state}/key").strip() == "400 valley-worker valley-worker"
318 host.succeed(f"test -f {state}/key && test ! -L {state}/key")
319 for other in ["git", "valley-integrator", "nobody"]:
320 host.fail(f"sudo -u {other} cat {state}/key")
321 public = host.succeed(f"cat {state}/key.pub").strip()
322 verifier = host.succeed(f"cat {state}/verifier").strip()
323 assert verifier.startswith("worker/attestations+"), verifier
324 keyhash = verifier.split("+")[1]
325 said = journal()
326 assert f"the worker's ssh public key is {public}" in said, said
327 assert f"the worker's verifier line is {verifier}" in said, said
328 assert "PRIVATE KEY" not in said, said
329 assert host.succeed(f"ssh-keygen -y -f {state}/key").split()[1] == public.split()[1]
330 host.fail(f"ls {state} | grep -q '^key.new'")
331 fingerprint = host.succeed(f"ssh-keygen -lf {state}/key").strip()
332 assert attestations() == []
333
334 with subtest("enrolled in the registry, the worker builds the ready change's checks side by side and publishes them"):
335 land_instance(" ".join(public.split()[:2]))
336 host.succeed(f"grep -q '^worker/attestations+{keyhash}+' /var/lib/valley-identity/known-signers")
337 host.wait_until_succeeds(
338 f"{git} -C /srv/git/instance.git cat-file blob refs/the-valley/signers:known-signers"
339 f" | grep -q '^worker/attestations+{keyhash}+'",
340 timeout=60,
341 )
342 host.succeed("systemd-run --unit=valley-worker-e2e-sampler ${sampler}")
343 host.succeed("systemctl start valley-worker.service")
344 host.succeed("systemctl stop valley-worker-e2e-sampler")
345 said = journal()
346 assert "building first, second" in said, said
347 refs = attestations()
348 assert len(refs) == 1 and refs[0].endswith(f"/{keyhash}"), refs
349 assert f"published {refs[0]}" in said, said
350 for check in ["first", "second"]:
351 host.succeed(f"{git} -C /srv/git/project.git cat-file -e {refs[0]}:{check}/statement.note")
352 # Both checks at once, each in the daemon's cgroup, inside the
353 # slice, each told it may use the 2 cores the host configures.
354 builders = [int(n) for n in host.succeed("cat /tmp/builders").split()]
355 assert max(builders) >= 2, builders
356 cgroups = set(host.succeed("cat /tmp/build-cgroups").split())
357 assert cgroups and all(c.startswith("0::/valley.slice/valley-builds.slice/nix-daemon.service") for c in cgroups), cgroups
358 for check in ["first", "second"]:
359 assert host.succeed(f"cat /nix/store/*-worker-{check}").strip() == "2", check
360 for unit in ["valley-worker.service", "nix-daemon.service"]:
361 assert host.succeed(f"systemctl show -p Slice --value {unit}").strip() == "valley-builds.slice", unit
362
363 with subtest("the timer runs the next pass, which finds the evidence on origin and builds nothing"):
364 host.succeed("systemctl start valley-worker.timer")
365 host.wait_until_succeeds(
366 "journalctl -u valley-worker -o cat | grep -q 'origin holds evidence for every nix check it requires'",
367 timeout=150,
368 )
369 host.succeed("systemctl stop valley-worker.timer")
370 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating")
371 assert len(attestations()) == 1
372
373 def idle():
374 host.wait_until_succeeds(
375 "test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating"
376 f" && test ! -e {wake}/due",
377 timeout=300,
378 )
379
380 def started():
381 return unit_property("valley-worker.service", "ExecMainStartTimestampMonotonic")
382
383 with subtest("the wake directory is the worker's and its writers', and the worker's access is unchanged"):
384 assert host.succeed(f"stat -c '%U %G %a' {wake}").strip() == "valley-worker valley-worker-wake 770"
385 assert "valley-worker-wake" in host.succeed("id -nG git").split()
386 assert "valley-worker-wake" in host.succeed(f"id -nG {unit_property('valley-integrator@project.service', 'User')}").split()
387 assert host.succeed("id -nG valley-worker").split() == ["valley-worker"]
388 host.fail("sudo -u valley-worker ls /srv/git/project.git/refs")
389 host.succeed("systemctl cat valley-worker.path | grep -qx 'PathExists=/var/lib/valley-worker-wake/due'")
390 assert unit_property("valley-worker.service", "StartLimitIntervalUSec") == "0"
391 assert unit_property("valley-worker.service", "RestartForceExitStatus") == "75"
392 host.fail("systemctl show -p WantedBy --value valley-worker.service | grep -q multi-user")
393 # The marks the seeding pushes and the signer publication left
394 # are read by one pass, which builds nothing.
395 host.succeed("systemctl start valley-worker.path")
396 idle()
397 host.succeed(f"test ! -e {wake}/claimed")
398 assert len(attestations()) == 1
399
400 with subtest("a ready push starts a pass at once with no timer, and a change readied during it gets the next pass"):
401 import time
402 host.fail("systemctl is-active valley-worker.timer")
403 building = journal().count("building first, second")
404 evidence = len(attestations())
405 ready("wake-first", "${spin}")
406 readied = time.monotonic()
407 host.wait_until_succeeds(
408 f"test $(journalctl -u valley-worker -o cat | grep -c 'building first, second') -gt {building}",
409 timeout=120,
410 )
411 print(f"ready to building: {time.monotonic() - readied:.1f}s")
412 assert unit_property("valley-worker.service", "ActiveState") == "activating"
413 ready("wake-second", "${spin}")
414 host.wait_until_succeeds(f"test -e {wake}/due -a -e {wake}/claimed")
415 host.wait_until_succeeds(
416 f"test $({git} -C /srv/git/project.git for-each-ref refs/the-valley/attestations/ | wc -l) -eq {evidence + 2}",
417 timeout=600,
418 )
419 idle()
420 host.fail("systemctl is-active valley-worker.timer")
421 assert journal().count("building first, second") == building + 2
422
423 with subtest("marks from the git user and the integrator's user are one file, and a stale mark builds nothing"):
424 host.succeed("systemctl stop valley-worker.path")
425 integrator = unit_property("valley-integrator@project.service", "User")
426 for who in ["git", integrator, "git", integrator]:
427 host.succeed(f"sudo -u {who} bash -c 'set -C; : > {wake}/due' 2>/dev/null || test -e {wake}/due")
428 assert host.succeed(f"ls -A {wake}").split() == ["due", "lock"]
429 host.succeed(f"rm {wake}/due && sudo -u {integrator} bash -c 'set -C; : > {wake}/due'")
430 building = journal().count("building first, second")
431 pushes = journal().count("published ")
432 host.succeed("systemctl start valley-worker.path")
433 idle()
434 assert host.succeed(f"ls -A {wake}").split() == ["lock"]
435 assert journal().count("building first, second") == building
436 assert journal().count("published ") == pushes
437
438 with subtest("a claim a killed pass left starts nothing, and the next pass acknowledges it"):
439 host.succeed(f"sudo -u valley-worker touch {wake}/claimed")
440 mark = started()
441 host.succeed("sleep 5")
442 assert started() == mark
443 host.succeed("systemctl start valley-worker.service")
444 host.succeed(f"test ! -e {wake}/claimed")
445
446 with subtest("a pass that cannot claim due reads all the same and is started again only after its hold-off"):
447 restarts = int(unit_property("valley-worker.service", "NRestarts"))
448 host.succeed(f"chmod 0550 {wake} && touch {wake}/due")
449 host.wait_until_succeeds("journalctl -u valley-worker -o cat | grep -q 'could not claim'", timeout=60)
450 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value valley-worker)\" = auto-restart")
451 # due is still there, and nothing starts a pass during the
452 # hold-off of one interval.
453 mark = started()
454 host.sleep(5)
455 assert started() == mark
456 assert int(unit_property("valley-worker.service", "NRestarts")) == restarts
457 host.fail("systemctl is-failed valley-worker.path")
458 assert "origin holds evidence for every nix check it requires" in journal()
459 host.succeed(f"chmod 0770 {wake}")
460 idle()
461 host.succeed("systemctl is-active valley-worker.path")
462
463 with subtest("a push to the instance, which the worker does not build, marks it due, and knots and bookkeeping do not"):
464 host.succeed("systemctl stop valley-worker.path")
465 host.succeed(
466 f"cd /root && rm -rf instance && GIT_SSH_COMMAND={ssh} git clone --quiet git@localhost:instance.git instance",
467 f"cd /root/instance && git checkout --quiet -b floor-probe && echo probe > probe && git add probe && {commit} -m probe",
468 )
469 hook = "/srv/git/instance.git/hooks/post-receive.d/valley-wake"
470 zero = "0" * 40
471 host.succeed(f"echo '{zero} {zero} refs/the-valley/knots' | sudo -u git {hook}")
472 host.succeed(f"echo '{zero} {zero} refs/the-valley/integration-outcomes/main/x' | sudo -u git {hook}")
473 host.succeed(f"test ! -e {wake}/due")
474 host.succeed(f"cd /root/instance && GIT_SSH_COMMAND={ssh} git push --quiet origin floor-probe")
475 host.succeed(f"test -e {wake}/due")
476
477 with subtest("a signer publication marks the worker due only when it moves the ref"):
478 host.succeed(f"rm -f {wake}/due")
479 host.succeed("systemctl start valley-signers.service")
480 host.succeed(f"test ! -e {wake}/due")
481 host.succeed(f"{git} -C /srv/git/instance.git update-ref -d refs/the-valley/signers")
482 host.succeed("systemctl start valley-signers.service")
483 host.succeed(f"test -e {wake}/due")
484 host.succeed("systemctl start valley-worker.path")
485 idle()
486
487 def head(branch):
488 return host.succeed(f"git -C /root/project rev-parse --short=7 {branch}").strip()
489
490 def told(commit, what):
491 return journal().count(f" at {commit}: {what}")
492
493 def wait_said(commit, what, timeout):
494 host.wait_until_succeeds(f"journalctl -u valley-worker -o cat | grep -qF ' at {commit}: {what}'", timeout=timeout)
495
496 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"):
497 # The mirror takes the drain's push of main and never answers it,
498 # and what listens at the bus's address takes a connection and
499 # never answers it.
500 host.succeed(
501 "printf '#!/bin/sh\\nexec /run/current-system/sw/bin/sleep 100001\\n' > /srv/hung.git/hooks/pre-receive",
502 "chmod 755 /srv/hung.git/hooks/pre-receive",
503 "systemctl stop valley-bus.service",
504 "systemd-run --unit=hung-bus ${pkgs.socat}/bin/socat TCP-LISTEN:4222,bind=127.0.0.1,fork,reuseaddr"
505 " SYSTEM:'exec ${pkgs.coreutils}/bin/sleep 100000'",
506 )
507 host.wait_for_open_port(4222)
508 # The good change lands by the integrator's own service, which
509 # marks due from inside its sandbox. The request ref is written
510 # locally, which runs no hook, so the landing's mark is the only one.
511 host.succeed("systemctl stop valley-worker.path")
512 base = host.succeed(f"{git} -C /srv/git/project.git rev-parse refs/heads/main").strip()
513 good = host.succeed("git -C /root/project rev-parse good").strip()
514 host.succeed(f"{git} -C /srv/git/project.git update-ref refs/the-valley/integration-requests/main/good {good}")
515 host.wait_until_succeeds(
516 f"test \"$({git} -C /srv/git/project.git rev-parse refs/heads/main^)\" = {base}", timeout=120
517 )
518 landed = time.monotonic()
519 host.wait_until_succeeds(f"test -e {wake}/due", timeout=10)
520 print(f"landing to mark, mirror and bus hung: {time.monotonic() - landed:.1f}s")
521 host.wait_until_succeeds(
522 "journalctl -u valley-integrator@project -o cat | grep -q 'bus publish of .* FAILED'", timeout=120
523 )
524 said_by = host.succeed("journalctl -u valley-integrator@project -o cat")
525 assert said_by.index("wake the check worker is due") < said_by.index("bus publish of"), said_by
526 host.wait_until_succeeds("pgrep -f 'sleep 10000[1]'", timeout=60)
527 host.succeed("systemctl start valley-worker.path")
528 idle()
529 # With the mirror's push still hung, a ready push starts a pass.
530 ready("hung", "${spin}")
531 readied = time.monotonic()
532 wait_said(head("hung"), "building", 120)
533 print(f"ready to building, mirror and bus hung: {time.monotonic() - readied:.1f}s")
534 wait_said(head("hung"), "published", 120)
535 idle()
536 host.succeed("pgrep -f 'sleep 10000[1]'")
537 host.succeed(
538 "rm /srv/hung.git/hooks/pre-receive && pkill -f 'sleep 10000[1]'",
539 "systemctl stop hung-bus && systemctl start valley-bus.service",
540 )
541
542 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"):
543 host.succeed("systemctl stop valley-worker.path")
544 floor_base = host.succeed(f"{git} -C /srv/git/instance.git rev-parse refs/heads/main").strip()
545 host.succeed(
546 "cp ${floorThird} /tmp/instance/policy/instance/floor.cue",
547 f"cd /tmp/instance && sudo -u git {commit} -am third",
548 f"{git} -C /srv/git/instance.git fetch --quiet /tmp/instance main:refs/the-valley/integration-requests/main/third",
549 )
550 host.wait_until_succeeds(
551 f"test \"$({git} -C /srv/git/instance.git rev-parse refs/heads/main^)\" = {floor_base}", timeout=120
552 )
553 host.wait_until_succeeds(f"test -e {wake}/due", timeout=10)
554 host.succeed("journalctl -u valley-integrator@instance -o cat | grep -q 'wake the check worker is due'")
555 # The pass reads the new floor. A change built before it holds this
556 # worker's evidence for its tree, which admits no addition, so the
557 # pass says the third check is not covered.
558 host.succeed("systemctl start valley-worker.path")
559 host.wait_until_succeeds(
560 "journalctl -u valley-worker -o cat | grep -q 'and it does not cover third'", timeout=120
561 )
562 idle()
563 assert "instance:" not in journal()
564
565 with subtest("a pass killed during a build leaves its claim, and the timer's next pass builds the change"):
566 # The push and the ready mark are made before the pass starts,
567 # so they are one due, which the pass claims.
568 host.succeed("systemctl stop valley-worker.path")
569 ready("killed", "${slow}")
570 killed = head("killed")
571 host.succeed("systemctl start valley-worker.path")
572 wait_said(killed, "building", 120)
573 host.wait_until_succeeds("ps -eo user= | grep -q '^nixbld'", timeout=60)
574 host.succeed("systemctl kill --signal=KILL valley-worker.service")
575 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" = failed", timeout=60)
576 assert host.succeed(f"ls -A {wake}").split() == ["claimed", "lock"]
577 host.wait_until_succeeds("! ps -eo user= | grep -q '^nixbld'", timeout=60)
578 # Nothing watches claimed, so nothing starts a pass, until the
579 # timer runs the recovery scan one interval after the kill.
580 mark = started()
581 host.sleep(5)
582 assert started() == mark
583 assert told(killed, "published") == 0
584 host.succeed("systemctl start valley-worker.timer")
585 wait_said(killed, "published", 300)
586 idle()
587 host.succeed(f"test ! -e {wake}/claimed")
588 assert told(killed, "building") == 2
589
590 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"):
591 # The timer is stopped until sshd is back, so the pass that fails
592 # is the one the path starts.
593 host.succeed("systemctl stop valley-worker.timer valley-worker.path")
594 ready("outage", "${spin}")
595 outage = head("outage")
596 host.succeed("systemctl stop sshd.service")
597 host.succeed("systemctl start valley-worker.path")
598 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" = failed", timeout=120)
599 assert host.succeed(f"ls -A {wake}").split() == ["claimed", "lock"]
600 assert told(outage, "building") == 0
601 triggered = unit_property("valley-worker.timer", "LastTriggerUSecMonotonic")
602 host.succeed("systemctl start sshd.service valley-worker.timer")
603 wait_said(outage, "published", 300)
604 assert unit_property("valley-worker.timer", "LastTriggerUSecMonotonic") != triggered
605 idle()
606 host.succeed(f"test ! -e {wake}/claimed")
607
608 with subtest("a failed batch is not built again before its wait, however many marks and timer passes come"):
609 ready("broken", "${broken}")
610 broken = head("broken")
611 wait_said(broken, "the batch did not pass", 120)
612 idle()
613 ready("unrelated", "${spin}")
614 wait_said(head("unrelated"), "published", 120)
615 idle()
616 host.succeed(
617 f"{git} -C /srv/git/instance.git update-ref -d refs/the-valley/signers",
618 "systemctl start valley-signers.service",
619 )
620 idle()
621 host.succeed(f"cd /root/instance && echo again >> probe && {commit} -am again && GIT_SSH_COMMAND={ssh} git push --quiet origin floor-probe")
622 idle()
623 triggered = unit_property("valley-worker.timer", "LastTriggerUSecMonotonic")
624 host.wait_until_succeeds(
625 f"test \"$(systemctl show -p LastTriggerUSecMonotonic --value valley-worker.timer)\" != '{triggered}'", timeout=150
626 )
627 idle()
628 assert told(broken, "building") == 1
629 assert told(broken, "the batch did not pass") == 1
630 assert told(broken, "its batch") >= 4, journal()
631 # The scenarios below start each pass themselves.
632 host.succeed("systemctl stop valley-worker.timer valley-worker.path")
633 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating")
634
635 with subtest("the key is the same after many starts, and is not said again"):
636 host.succeed("systemctl start valley-worker.service")
637 assert host.succeed(f"ssh-keygen -lf {state}/key").strip() == fingerprint
638 assert host.succeed(f"cat {state}/verifier").strip() == verifier
639 assert journal().count("verifier line is") == 1
640
641 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"):
642 import json
643 roots = f"{state}/roots"
644
645 def rooted():
646 links = host.succeed(f"find {roots} -mindepth 1 -maxdepth 1 -type l -printf '%f\\n'").split()
647 return {link: host.succeed(f"readlink {roots}/{link}").strip() for link in links}
648
649 def registered(paths):
650 info = json.loads(host.succeed("nix --extra-experimental-features nix-command path-info --json " + " ".join(paths)))
651 if isinstance(info, dict):
652 info = [dict(v, path=k) for k, v in info.items()]
653 return {i["path"]: i["registrationTime"] for i in info}
654
655 def publish(branch):
656 # Every root's last use is set long past, so the pass prunes
657 # each one, and its batch roots again only what it uses.
658 host.succeed(f"find {roots} -mindepth 1 -maxdepth 1 -type l -exec touch -h -d @1 {{}} +")
659 ready(branch, "${spin}")
660 host.succeed("systemctl start valley-worker.service")
661 assert told(head(branch), "published") == 1
662 now = rooted()
663 assert now, f"the batch for {branch} rooted no output"
664 for link in now:
665 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"
666 return now
667
668 first = publish("kept")
669 known = host.succeed("nix-store --gc --print-roots")
670 for link, path in first.items():
671 assert link == path.removeprefix("/nix/store/"), (link, path)
672 assert f"{roots}/{link} -> {path}" in known, f"the daemon does not know {roots}/{link}"
673 built = registered(first.values())
674 again = publish("kept-again")
675 assert again == first, (first, again)
676 assert registered(again.values()) == built, "an output was built again"
677 '';
678 };
679}