gunk-dev/the-valley

worker-e2e.nix

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