gunk-dev/the-valley

worker-e2e.nix

sourced76157dbe10cmain's published tip history
40.6 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 # Each check's result records the capacity the pass built on: the
381 # slots, the default two batches, nix's max-jobs and cores, and
382 # the machine's CPUs.
383 import json
384 results = [
385 r for r in map(json.loads, host.succeed(f"cat {state}/telemetry/stream/seg-*.jsonl").splitlines())
386 if r["type"] == "check.result"
387 ]
388 assert sorted(r["check"] for r in results) == ["first", "second"], results
389 assert all(r["data"]["capacity"] == "slots=2 batches=2 max_jobs=2 cores=2 cpus=6" for r in results), results
390 # Both checks at once, each in the daemon's cgroup, inside the
391 # slice, each told it may use the 2 cores the host configures.
392 builders = [int(n) for n in host.succeed("cat /tmp/builders").split()]
393 assert max(builders) >= 2, builders
394 cgroups = set(host.succeed("cat /tmp/build-cgroups").split())
395 assert cgroups and all(c.startswith("0::/valley.slice/valley-builds.slice/nix-daemon.service") for c in cgroups), cgroups
396 for check in ["first", "second"]:
397 assert host.succeed(f"cat /nix/store/*-worker-{check}").strip() == "2", check
398 for unit in ["valley-worker.service", "nix-daemon.service"]:
399 assert host.succeed(f"systemctl show -p Slice --value {unit}").strip() == "valley-builds.slice", unit
400
401 with subtest("the timer runs the next pass, which finds the evidence on origin and builds nothing"):
402 # The pass above read the change again after publishing, and said
403 # this line once already.
404 covered = journal().count("origin holds evidence for every nix check it requires")
405 host.succeed("systemctl start valley-worker.timer")
406 host.wait_until_succeeds(
407 "test $(journalctl -u valley-worker -o cat | grep -c 'origin holds evidence for every nix check it requires')"
408 f" -gt {covered}",
409 timeout=150,
410 )
411 host.succeed("systemctl stop valley-worker.timer")
412 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating")
413 assert len(attestations()) == 1
414
415 def idle():
416 host.wait_until_succeeds(
417 "test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating"
418 f" && test ! -e {wake}/due",
419 timeout=300,
420 )
421
422 def started():
423 return unit_property("valley-worker.service", "ExecMainStartTimestampMonotonic")
424
425 with subtest("the wake directory is the worker's and its writers', and the worker's access is unchanged"):
426 assert host.succeed(f"stat -c '%U %G %a' {wake}").strip() == "valley-worker valley-worker-wake 770"
427 assert "valley-worker-wake" in host.succeed("id -nG git").split()
428 assert "valley-worker-wake" in host.succeed(f"id -nG {unit_property('valley-integrator@project.service', 'User')}").split()
429 assert host.succeed("id -nG valley-worker").split() == ["valley-worker"]
430 host.fail("sudo -u valley-worker ls /srv/git/project.git/refs")
431 host.succeed("systemctl cat valley-worker.path | grep -qx 'PathExists=/var/lib/valley-worker-wake/due'")
432 assert unit_property("valley-worker.service", "StartLimitIntervalUSec") == "0"
433 assert unit_property("valley-worker.service", "RestartForceExitStatus") == "75"
434 host.fail("systemctl show -p WantedBy --value valley-worker.service | grep -q multi-user")
435 # The marks the seeding pushes and the signer publication left
436 # are read by one pass, which builds nothing.
437 host.succeed("systemctl start valley-worker.path")
438 idle()
439 host.succeed(f"test ! -e {wake}/claimed")
440 assert len(attestations()) == 1
441
442 def head(branch):
443 return host.succeed(f"git -C /root/project rev-parse --short=7 {branch}").strip()
444
445 def told(commit, what):
446 return journal().count(f" at {commit}: {what}")
447
448 def wait_said(commit, what, timeout):
449 host.wait_until_succeeds(f"journalctl -u valley-worker -o cat | grep -qF ' at {commit}: {what}'", timeout=timeout)
450
451 with subtest("a ready push starts a pass at once with no timer"):
452 import time
453 host.fail("systemctl is-active valley-worker.timer")
454 ready("wake-first", "${spin}")
455 readied = time.monotonic()
456 wait_said(head("wake-first"), "building", 120)
457 print(f"ready to building: {time.monotonic() - readied:.1f}s")
458 wait_said(head("wake-first"), "published", 120)
459 idle()
460 host.succeed(f"test ! -e {wake}/claimed")
461
462 def eval_spans():
463 # When each attest run's evaluation began and ended, from its
464 # eval.start and eval.end records, in the order they began.
465 import datetime
466 import json
467 spans = {}
468 for line in host.succeed(f"cat {state}/telemetry/stream/seg-*.jsonl 2>/dev/null || true").splitlines():
469 r = json.loads(line)
470 if r["type"] in ("eval.start", "eval.end"):
471 spans.setdefault(r["run"], {})[r["type"]] = r
472 return sorted(
473 (datetime.datetime.fromisoformat(s["eval.start"]["time"].replace("Z", "+00:00")),
474 datetime.datetime.fromisoformat(s["eval.end"]["time"].replace("Z", "+00:00")),
475 s["eval.end"]["data"]["eval_wait_ms"])
476 for s in spans.values() if len(s) == 2
477 )
478
479 # One pass, started by hand with the timer and the path unit stopped,
480 # so every change readied after it starts is built by that pass or by
481 # none. Its first scan finds the long and the short change, and it
482 # starts both batches at once; their evaluations take turns. Each
483 # ready push marks due, and the pass claims the mark itself and reads
484 # again. The long change builds for about twenty seconds; meanwhile
485 # the short change is built and published in the pass's second slot,
486 # a broken change fails, two changes with one tree are built once,
487 # and the long change publishes after the failure. No two batches'
488 # evaluations overlap. The pass acknowledges every mark it claimed.
489 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"):
490 host.succeed("systemctl stop valley-worker.path")
491 evaluated = len(eval_spans())
492 ready("long", "${long}")
493 long = head("long")
494 ready("short", "${spin}")
495 short = head("short")
496 host.succeed("systemctl start --no-block valley-worker.service")
497 wait_said(long, "building", 120)
498 mark = started()
499 ready("early-broken", "${broken}")
500 early_broken = head("early-broken")
501 wait_said(short, "published", 120)
502 # The short change's evidence is on origin while the long batch
503 # still builds.
504 assert told(long, "published") == 0, journal()
505 assert unit_property("valley-worker.service", "ActiveState") == "activating"
506 # Two branches with one tree, readied one right after the other.
507 ready("twin-a", "${spin}")
508 host.succeed(
509 "cd /root/project && git checkout --quiet -b twin-b origin/main && git checkout --quiet twin-a -- .",
510 f"cd /root/project && {commit} -m twin-b",
511 )
512 push_ready("twin-b")
513 trees = host.succeed("git -C /root/project rev-parse twin-a^{tree} twin-b^{tree}").split()
514 assert trees[0] == trees[1], trees
515 twins = [head("twin-a"), head("twin-b")]
516 wait_said(early_broken, "the batch did not pass", 120)
517 wait_said(long, "published", 300)
518 host.wait_until_succeeds(
519 "test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating", timeout=300
520 )
521 said = journal()
522 assert started() == mark, "a second pass ran"
523 # The long, short and broken batches and the twins' one batch
524 # each evaluated, and each evaluation ended before the next began.
525 spans = eval_spans()[evaluated:]
526 print(f"evaluations: {[(str(b), str(e), w) for b, e, w in spans]}")
527 assert len(spans) >= 4, spans
528 for (_, ended, _), (began, _, _) in zip(spans, spans[1:]):
529 assert ended <= began, spans
530 for change in [long, short, early_broken]:
531 assert told(change, "building") == 1, (change, said)
532 assert said.index(f" at {early_broken}: the batch did not pass") < said.index(f" at {long}: published"), said
533 assert sum(told(t, "building") for t in twins) == 1, said
534 assert sum(told(t, "published") for t in twins) == 1, said
535 assert any(told(t, "origin holds evidence for every nix check it requires") for t in twins), said
536 host.succeed(f"test ! -e {wake}/due -a ! -e {wake}/claimed")
537 # Every scan reads each ready change, so the changes this pass
538 # built are withdrawn, and the passes below read no more changes
539 # than they did before this scenario.
540 for branch in ["long", "short", "early-broken", "twin-a", "twin-b"]:
541 host.succeed(f"{contributor} valley withdraw {branch}")
542 host.succeed("systemctl start valley-worker.path")
543 idle()
544 host.succeed(f"test ! -e {wake}/claimed")
545
546 with subtest("marks from the git user and the integrator's user are one file, and a stale mark builds nothing"):
547 host.succeed("systemctl stop valley-worker.path")
548 integrator = unit_property("valley-integrator@project.service", "User")
549 for who in ["git", integrator, "git", integrator]:
550 host.succeed(f"sudo -u {who} bash -c 'set -C; : > {wake}/due' 2>/dev/null || test -e {wake}/due")
551 assert host.succeed(f"ls -A {wake}").split() == ["due", "lock"]
552 host.succeed(f"rm {wake}/due && sudo -u {integrator} bash -c 'set -C; : > {wake}/due'")
553 building = journal().count("building first, second")
554 pushes = journal().count("published ")
555 host.succeed("systemctl start valley-worker.path")
556 idle()
557 assert host.succeed(f"ls -A {wake}").split() == ["lock"]
558 assert journal().count("building first, second") == building
559 assert journal().count("published ") == pushes
560
561 with subtest("a claim a killed pass left starts nothing, and the next pass acknowledges it"):
562 host.succeed(f"sudo -u valley-worker touch {wake}/claimed")
563 mark = started()
564 host.succeed("sleep 5")
565 assert started() == mark
566 host.succeed("systemctl start valley-worker.service")
567 host.succeed(f"test ! -e {wake}/claimed")
568
569 with subtest("a pass that cannot claim due reads all the same and is started again only after its hold-off"):
570 restarts = int(unit_property("valley-worker.service", "NRestarts"))
571 host.succeed(f"chmod 0550 {wake} && touch {wake}/due")
572 host.wait_until_succeeds("journalctl -u valley-worker -o cat | grep -q 'could not claim'", timeout=60)
573 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value valley-worker)\" = auto-restart")
574 # due is still there, and nothing starts a pass during the
575 # hold-off of one interval.
576 mark = started()
577 host.sleep(5)
578 assert started() == mark
579 assert int(unit_property("valley-worker.service", "NRestarts")) == restarts
580 host.fail("systemctl is-failed valley-worker.path")
581 assert "origin holds evidence for every nix check it requires" in journal()
582 host.succeed(f"chmod 0770 {wake}")
583 idle()
584 host.succeed("systemctl is-active valley-worker.path")
585
586 with subtest("a push to the instance, which the worker does not build, marks it due, and knots and bookkeeping do not"):
587 host.succeed("systemctl stop valley-worker.path")
588 host.succeed(
589 f"cd /root && rm -rf instance && GIT_SSH_COMMAND={ssh} git clone --quiet git@localhost:instance.git instance",
590 f"cd /root/instance && git checkout --quiet -b floor-probe && echo probe > probe && git add probe && {commit} -m probe",
591 )
592 hook = "/srv/git/instance.git/hooks/post-receive.d/valley-wake"
593 zero = "0" * 40
594 host.succeed(f"echo '{zero} {zero} refs/the-valley/knots' | sudo -u git {hook}")
595 host.succeed(f"echo '{zero} {zero} refs/the-valley/integration-outcomes/main/x' | sudo -u git {hook}")
596 host.succeed(f"test ! -e {wake}/due")
597 host.succeed(f"cd /root/instance && GIT_SSH_COMMAND={ssh} git push --quiet origin floor-probe")
598 host.succeed(f"test -e {wake}/due")
599
600 with subtest("a signer publication marks the worker due only when it moves the ref"):
601 host.succeed(f"rm -f {wake}/due")
602 host.succeed("systemctl start valley-signers.service")
603 host.succeed(f"test ! -e {wake}/due")
604 host.succeed(f"{git} -C /srv/git/instance.git update-ref -d refs/the-valley/signers")
605 host.succeed("systemctl start valley-signers.service")
606 host.succeed(f"test -e {wake}/due")
607 host.succeed("systemctl start valley-worker.path")
608 idle()
609
610 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"):
611 # The mirror takes the drain's push of main and never answers it,
612 # and what listens at the bus's address takes a connection and
613 # never answers it.
614 host.succeed(
615 "printf '#!/bin/sh\\nexec /run/current-system/sw/bin/sleep 100001\\n' > /srv/hung.git/hooks/pre-receive",
616 "chmod 755 /srv/hung.git/hooks/pre-receive",
617 "systemctl stop valley-bus.service",
618 "systemd-run --unit=hung-bus ${pkgs.socat}/bin/socat TCP-LISTEN:4222,bind=127.0.0.1,fork,reuseaddr"
619 " SYSTEM:'exec ${pkgs.coreutils}/bin/sleep 100000'",
620 )
621 host.wait_for_open_port(4222)
622 # The good change lands by the integrator's own service, which
623 # marks due from inside its sandbox. The request ref is written
624 # locally, which runs no hook, so the landing's mark is the only one.
625 host.succeed("systemctl stop valley-worker.path")
626 base = host.succeed(f"{git} -C /srv/git/project.git rev-parse refs/heads/main").strip()
627 good = host.succeed("git -C /root/project rev-parse good").strip()
628 host.succeed(f"{git} -C /srv/git/project.git update-ref refs/the-valley/integration-requests/main/good {good}")
629 host.wait_until_succeeds(
630 f"test \"$({git} -C /srv/git/project.git rev-parse refs/heads/main^)\" = {base}", timeout=120
631 )
632 landed = time.monotonic()
633 host.wait_until_succeeds(f"test -e {wake}/due", timeout=10)
634 print(f"landing to mark, mirror and bus hung: {time.monotonic() - landed:.1f}s")
635 host.wait_until_succeeds(
636 "journalctl -u valley-integrator@project -o cat | grep -q 'bus publish of .* FAILED'", timeout=120
637 )
638 said_by = host.succeed("journalctl -u valley-integrator@project -o cat")
639 assert said_by.index("wake the check worker is due") < said_by.index("bus publish of"), said_by
640 host.wait_until_succeeds("pgrep -f 'sleep 10000[1]'", timeout=60)
641 host.succeed("systemctl start valley-worker.path")
642 idle()
643 # With the mirror's push still hung, a ready push starts a pass.
644 ready("hung", "${spin}")
645 readied = time.monotonic()
646 wait_said(head("hung"), "building", 120)
647 print(f"ready to building, mirror and bus hung: {time.monotonic() - readied:.1f}s")
648 wait_said(head("hung"), "published", 120)
649 idle()
650 host.succeed("pgrep -f 'sleep 10000[1]'")
651 host.succeed(
652 "rm /srv/hung.git/hooks/pre-receive && pkill -f 'sleep 10000[1]'",
653 "systemctl stop hung-bus && systemctl start valley-bus.service",
654 )
655
656 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"):
657 host.succeed("systemctl stop valley-worker.path")
658 floor_base = host.succeed(f"{git} -C /srv/git/instance.git rev-parse refs/heads/main").strip()
659 host.succeed(
660 "cp ${floorThird} /tmp/instance/policy/instance/floor.cue",
661 f"cd /tmp/instance && sudo -u git {commit} -am third",
662 f"{git} -C /srv/git/instance.git fetch --quiet /tmp/instance main:refs/the-valley/integration-requests/main/third",
663 )
664 host.wait_until_succeeds(
665 f"test \"$({git} -C /srv/git/instance.git rev-parse refs/heads/main^)\" = {floor_base}", timeout=120
666 )
667 host.wait_until_succeeds(f"test -e {wake}/due", timeout=10)
668 host.succeed("journalctl -u valley-integrator@instance -o cat | grep -q 'wake the check worker is due'")
669 # The pass reads the new floor. A change built before it holds this
670 # worker's evidence for its tree, which admits no addition, so the
671 # pass says the third check is not covered.
672 host.succeed("systemctl start valley-worker.path")
673 host.wait_until_succeeds(
674 "journalctl -u valley-worker -o cat | grep -q 'and it does not cover third'", timeout=120
675 )
676 idle()
677 assert "instance:" not in journal()
678
679 with subtest("a pass killed during a build leaves its claim, and the timer's next pass builds the change"):
680 # The push and the ready mark are made before the pass starts,
681 # so they are one due, which the pass claims.
682 host.succeed("systemctl stop valley-worker.path")
683 ready("killed", "${slow}")
684 killed = head("killed")
685 host.succeed("systemctl start valley-worker.path")
686 wait_said(killed, "building", 120)
687 host.wait_until_succeeds("ps -eo user= | grep -q '^nixbld'", timeout=60)
688 host.succeed("systemctl kill --signal=KILL valley-worker.service")
689 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" = failed", timeout=60)
690 assert host.succeed(f"ls -A {wake}").split() == ["claimed", "lock"]
691 host.wait_until_succeeds("! ps -eo user= | grep -q '^nixbld'", timeout=60)
692 # Nothing watches claimed, so nothing starts a pass, until the
693 # timer runs the recovery scan one interval after the kill.
694 mark = started()
695 host.sleep(5)
696 assert started() == mark
697 assert told(killed, "published") == 0
698 host.succeed("systemctl start valley-worker.timer")
699 wait_said(killed, "published", 300)
700 idle()
701 host.succeed(f"test ! -e {wake}/claimed")
702 assert told(killed, "building") == 2
703
704 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"):
705 # The timer is stopped until sshd is back, so the pass that fails
706 # is the one the path starts.
707 host.succeed("systemctl stop valley-worker.timer valley-worker.path")
708 ready("outage", "${spin}")
709 outage = head("outage")
710 host.succeed("systemctl stop sshd.service")
711 host.succeed("systemctl start valley-worker.path")
712 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" = failed", timeout=120)
713 assert host.succeed(f"ls -A {wake}").split() == ["claimed", "lock"]
714 assert told(outage, "building") == 0
715 triggered = unit_property("valley-worker.timer", "LastTriggerUSecMonotonic")
716 host.succeed("systemctl start sshd.service valley-worker.timer")
717 wait_said(outage, "published", 300)
718 assert unit_property("valley-worker.timer", "LastTriggerUSecMonotonic") != triggered
719 idle()
720 host.succeed(f"test ! -e {wake}/claimed")
721
722 with subtest("a failed batch is not built again before its wait, however many marks and timer passes come"):
723 ready("broken", "${broken}")
724 broken = head("broken")
725 wait_said(broken, "the batch did not pass", 120)
726 idle()
727 ready("unrelated", "${spin}")
728 wait_said(head("unrelated"), "published", 120)
729 idle()
730 host.succeed(
731 f"{git} -C /srv/git/instance.git update-ref -d refs/the-valley/signers",
732 "systemctl start valley-signers.service",
733 )
734 idle()
735 host.succeed(f"cd /root/instance && echo again >> probe && {commit} -am again && GIT_SSH_COMMAND={ssh} git push --quiet origin floor-probe")
736 idle()
737 triggered = unit_property("valley-worker.timer", "LastTriggerUSecMonotonic")
738 host.wait_until_succeeds(
739 f"test \"$(systemctl show -p LastTriggerUSecMonotonic --value valley-worker.timer)\" != '{triggered}'", timeout=150
740 )
741 idle()
742 assert told(broken, "building") == 1
743 assert told(broken, "the batch did not pass") == 1
744 assert told(broken, "its batch") >= 4, journal()
745 # The scenarios below start each pass themselves.
746 host.succeed("systemctl stop valley-worker.timer valley-worker.path")
747 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating")
748
749 with subtest("the key is the same after many starts, and is not said again"):
750 host.succeed("systemctl start valley-worker.service")
751 assert host.succeed(f"ssh-keygen -lf {state}/key").strip() == fingerprint
752 assert host.succeed(f"cat {state}/verifier").strip() == verifier
753 assert journal().count("verifier line is") == 1
754
755 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"):
756 import json
757 roots = f"{state}/roots"
758
759 def rooted():
760 links = host.succeed(f"find {roots} -mindepth 1 -maxdepth 1 -type l -printf '%f\\n'").split()
761 return {link: host.succeed(f"readlink {roots}/{link}").strip() for link in links}
762
763 def registered(paths):
764 info = json.loads(host.succeed("nix --extra-experimental-features nix-command path-info --json " + " ".join(paths)))
765 if isinstance(info, dict):
766 info = [dict(v, path=k) for k, v in info.items()]
767 return {i["path"]: i["registrationTime"] for i in info}
768
769 def publish(branch):
770 # Every root's last use is set long past, so the pass prunes
771 # each one, and its batch roots again only what it uses.
772 host.succeed(f"find {roots} -mindepth 1 -maxdepth 1 -type l -exec touch -h -d @1 {{}} +")
773 ready(branch, "${spin}")
774 host.succeed("systemctl start valley-worker.service")
775 assert told(head(branch), "published") == 1
776 now = rooted()
777 assert now, f"the batch for {branch} rooted no output"
778 for link in now:
779 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"
780 return now
781
782 first = publish("kept")
783 known = host.succeed("nix-store --gc --print-roots")
784 for link, path in first.items():
785 assert link == path.removeprefix("/nix/store/"), (link, path)
786 assert f"{roots}/{link} -> {path}" in known, f"the daemon does not know {roots}/{link}"
787 built = registered(first.values())
788 again = publish("kept-again")
789 assert again == first, (first, again)
790 assert registered(again.values()) == built, "an output was built again"
791 '';
792 };
793}