gunk-dev/the-valley

worker-e2e.nix

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