gunk-dev/the-valley

worker-e2e.nix

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