gunk-dev/the-valley

worker-e2e.nix

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