gunk-dev/the-valley

telemetry.nix

sourcebc00697b19b5main's published tip history
44.5 KiB
1# Telemetry: the collector's unit tests, and telemetry on a host end to end.
2#
3# telemetry-e2e is one NixOS machine running the module with the worker,
4# the controllers, the registry compiler and the collector. Every read and
5# report goes over its real sshd, through the git user's shell.
6#
7# Right after seeding, valley-init's lifecycle: an activation that leaves
8# its unit alone stops no controller, and one that changes it reruns it
9# with the controllers running after. A valley-init that fails before it
10# touches its converged record holds back the registry compiler and the
11# signers publisher while a registry change lands, and starting it again
12# once repaired compiles, publishes the change and restores the
13# controllers, which every later scenario relies on.
14#
15# Then the boundary: an enrolled observer reads, and nobody else does. A
16# contributor without the grant, an untagged key, a key claiming another
17# principal through its environment, a reporter, and every malformed or
18# hostile command are refused, and none reaches a shell. A forced
19# fetch-only key stays fetch-only. Reads work while pushes are held. The
20# git user and the collector cannot read the worker's key, and the git
21# user cannot read the diagnostics on disk.
22#
23# Then the worker: a pass's slow check prints its output while it builds,
24# and a reader sees it then. The pass is killed during the build; the
25# source reads as stale, the journal shows the kill, and the next pass
26# records the interruption, inferred, and finishes. A change whose check
27# fails leaves a backoff naming the change, its head, its tree and why.
28#
29# Then the workstation, alice, a second user reaching the host over ssh
30# as its own principal. Her approval of a fresh change builds a slow and a
31# fast check side by side; the observer sees the fast one finish, and the
32# slow one's output, while the slow one still builds, and then the request
33# published, with alice's CLI version and her own timestamps. An approval
34# reusing the worker's evidence beside a local command check, and one
35# reusing everything, are observable too, and so is the integrator's
36# decision. The operator, who observes the worker, asks it for two
37# commits' checks with valley checks --build: one passes, and one whose
38# check fails is not established, with the worker's records for its tree,
39# the failed check's build error and the nix log command for its
40# derivation.
41# Every command alice runs records its verb, its flag names, its exit
42# status, its time and, for pending, its phases, and never an argument's
43# value; with telemetry off it records nothing and writes no spool, and
44# with the host unreachable it prints and exits as it does off.
45#
46# Last, outage: with the collector stopped, and with the telemetry remote
47# unreachable, approvals and pushes still complete, within a bounded
48# overhead; once the collector is back, one flush sends what was spooled,
49# and a second sends nothing again. Report and read limits hold on the
50# server whatever is asked.
51{
52 pkgs,
53 lib,
54 self,
55 packages,
56 machineValley,
57 ...
58}:
59let
60 keys = pkgs.runCommand "valley-telemetry-e2e-keys" { nativeBuildInputs = [ pkgs.openssh ]; } ''
61 mkdir $out
62 for who in integrator contributor operator alice stranger fetcher; do
63 ssh-keygen -q -t ed25519 -N "" -C "$who" -f "$out/$who"
64 done
65 '';
66 pub = who: lib.fileContents "${keys}/${who}.pub";
67 pubBlob = who: lib.concatStringsSep " " (lib.take 2 (lib.splitString " " (pub who)));
68
69 # The projects the host declares, each with its protection block. Each
70 # is protected, so each has a controller.
71 projects = {
72 instance = ''protection: refs: ["refs/heads/main"]'';
73 project = "protection: {}";
74 };
75
76 declaration = pkgs.writeText "valley-telemetry-e2e.cue" ''
77 package valley
78
79 projects: {
80 ${lib.concatStrings (lib.mapAttrsToList (name: block: " \"${name}\": ${block}\n") projects)}}
81 '';
82
83 # Every change requires a slow and a fast nix check; one that touches
84 # local/ also requires a command check, which the worker leaves to
85 # approve.
86 floor = pkgs.writeText "floor.cue" ''
87 package verification
88
89 floor: {
90 checks: {
91 slow: {runner: "nix", attribute: "slow"}
92 fast: {runner: "nix", attribute: "fast"}
93 local: {runner: "command", command: "echo local check ran"}
94 }
95 classes: {
96 policy: {paths: {"policy/**": true}, requires: {}}
97 local: {paths: {"local/**": true}, requires: {slow: true, fast: true, local: true}}
98 }
99 unclassified: {slow: true, fast: true}
100 }
101 '';
102
103 flake = pkgs.writeText "flake.nix" ''
104 {
105 outputs =
106 { self }:
107 let
108 check = name: script: derivation {
109 inherit name;
110 system = "x86_64-linux";
111 builder = "/bin/sh";
112 args = [ script ];
113 };
114 in
115 {
116 checks.x86_64-linux = {
117 slow = check "telemetry-slow" ./slow.sh;
118 fast = check "telemetry-fast" ./fast.sh;
119 };
120 };
121 }
122 '';
123 flakeLock = pkgs.writeText "flake.lock" ''{"nodes":{"root":{}},"root":"root","version":7}'';
124 # About half a second a tick, a line of output each, and a terminal
125 # escape in the first, which a reader must see escaped.
126 slow = pkgs.writeText "slow.sh" ''
127 printf 'slow start \033[31mred\033[0m\n'
128 n=0
129 while [ $n -lt 40 ]; do
130 i=0
131 while [ $i -lt 250000 ]; do i=$((i+1)); done
132 n=$((n+1))
133 echo "slow tick $n"
134 done
135 echo slow > $out
136 '';
137 fast = pkgs.writeText "fast.sh" "echo fast > $out";
138 broken = pkgs.writeText "broken.sh" ''
139 echo "broken check says why"
140 exit 1
141 '';
142in
143{
144 telemetry-unit = packages.telemetry.unit;
145
146 telemetry-e2e = pkgs.testers.runNixOSTest {
147 name = "valley-telemetry-e2e";
148 nodes.host =
149 { lib, ... }:
150 {
151 imports = [ self.nixosModules.default ];
152 virtualisation.cores = 4;
153 virtualisation.memorySize = 3072;
154 environment.systemPackages = [
155 pkgs.git
156 machineValley
157 ];
158 users.users.alice.isNormalUser = true;
159 services.valley = {
160 enable = true;
161 config = declaration;
162 authorizedKeys = [
163 {
164 principal = "contributor";
165 key = pub "contributor";
166 }
167 {
168 principal = "operator";
169 key = pub "operator";
170 }
171 {
172 principal = "alice";
173 key = pub "alice";
174 }
175 (pub "stranger")
176 ''command="git-upload-pack 'project.git'" ${pub "fetcher"}''
177 ];
178 grants.request = [ "alice" ];
179 identity.enable = true;
180 buildSlice.enable = true;
181 integrator = {
182 enable = true;
183 interval = "5s";
184 signingKeyFile = "${keys}/integrator";
185 instanceProject = "instance";
186 signerProjects."worker/attestations" = [ "project" ];
187 };
188 worker = {
189 enable = true;
190 projects = [ "project" ];
191 signerName = "worker/attestations";
192 };
193 telemetry = {
194 enable = true;
195 observers = [ "operator" ];
196 localSources = [
197 {
198 name = "host-probe";
199 description = "a service of the host's own, which fails";
200 units = [ "host-probe.service" ];
201 }
202 ];
203 reporters = [
204 "alice"
205 "receiver"
206 ];
207 remoteSources = [
208 {
209 name = "remote-receiver";
210 description = "a web receiver on another machine";
211 principal = "receiver";
212 }
213 ];
214 };
215 };
216 # A unit of the host's own, which nothing starts and which fails.
217 systemd.services.host-probe = {
218 serviceConfig.Type = "oneshot";
219 script = "echo host-probe says why; exit 3";
220 };
221 systemd.timers.valley-worker.timerConfig.OnActiveSec = lib.mkForce "1h";
222 nix.settings.experimental-features = [
223 "nix-command"
224 "flakes"
225 ];
226 nix.settings.substituters = lib.mkForce [ ];
227 networking.useDHCP = false;
228 # The same host with valley-init's unit changed and nothing else.
229 specialisation.init-changed.configuration.systemd.services.valley-init.environment.VALLEY_INIT_CHANGED = "1";
230 };
231
232 testScript = ''
233 import json
234 import re
235 import shlex
236 import time
237
238 host.wait_for_unit("multi-user.target")
239 host.succeed("systemctl stop valley-worker.timer valley-worker.path")
240
241 git = "sudo -u git git"
242 ssh_opts = "-o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
243 commit = "git -c user.name=t -c user.email=t@example.org commit --quiet"
244
245 def raw(who, command, extra=""):
246 """The telemetry command as a session sends it, with who's key."""
247 return f"ssh {ssh_opts} {extra} -i /root/keys/{who} git@localhost {shlex.quote(command)}"
248
249 def lines(out):
250 return [json.loads(l) for l in out.splitlines() if l.strip()]
251
252 def observe(args):
253 """valley telemetry as the operator, outside any checkout."""
254 return lines(host.succeed(f"cd / && valley telemetry --remote git@localhost:project.git --json {args}"))
255
256 def of(ls, kind):
257 return [l for l in ls if l.get("kind") == kind]
258
259 def records(ls, **match):
260 return [l for l in of(ls, "record") if all(l.get(k) == v for k, v in match.items())]
261
262 def source(name):
263 return [s for s in of(observe("snapshot"), "source") if s["name"] == name][0]
264
265 def as_alice(cmd, check=True):
266 full = f"sudo -u alice -H env VALLEY_ATTEST_KEY=/home/alice/keys/alice VALLEY_ATTEST_NAME=alice/attestations bash -c {shlex.quote('cd /home/alice/project && ' + cmd)}"
267 return host.succeed(full) if check else host.execute(full)
268
269 def registry(worker, operator=False):
270 def human(who, signs):
271 s = f', signs: "{who}/attestations"' if signs else ""
272 return [
273 f'"{who}": {{',
274 ' kind: "human"',
275 f' keys: [{{class: "ssh-ed25519", bound: "host", public: "{blob[who]}"{s}}}]',
276 ' grants: {push: boundary: "push", govern: boundary: "registry"}',
277 "}",
278 ]
279 principals = human("contributor", False) + human("alice", True)
280 if operator:
281 principals += human("operator", True)
282 if worker:
283 principals += [
284 '"worker": {',
285 ' kind: "machine"',
286 f' keys: [{{class: "ssh-ed25519", bound: "host", public: "{worker}", signs: "worker/attestations"}}]',
287 ' grants: push: boundary: "push"',
288 ' expires: "2099-01-01"',
289 "}",
290 ]
291 return "\n".join(['package identity', 'boundaries: {"push": kind: "git-push", "registry": kind: "registry"}',
292 'genesis: "contributor"', "principals: {"] + principals + ["}"])
293
294 blob = {"contributor": "${pubBlob "contributor"}", "alice": "${pubBlob "alice"}", "operator": "${pubBlob "operator"}"}
295
296 def land_instance(worker, operator=False, compile=True):
297 host.succeed(
298 "rm -rf /tmp/instance && mkdir -p /tmp/instance/policy/instance /tmp/instance/identity",
299 "cp ${floor} /tmp/instance/policy/instance/floor.cue",
300 f"cat > /tmp/instance/identity/registry.cue <<'EOF'\n{registry(worker, operator)}\nEOF",
301 f"cd /tmp/instance && git init --quiet --initial-branch=main && git add -A && {commit} -m instance",
302 "chown -R git:git /tmp/instance",
303 f"{git} -C /srv/git/instance.git fetch --quiet --force /tmp/instance main:refs/heads/main",
304 )
305 if compile:
306 host.succeed("systemctl start valley-identity.service")
307
308 def settle():
309 """Waits out a valley-init run, during which pushes pause."""
310 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-init)\" != activating", timeout=60)
311
312 def pushing(cmd):
313 """Runs a push of alice's, again if a valley-init run paused it."""
314 for attempt in range(3):
315 settle()
316 status, out = as_alice(cmd, check=False)
317 if status == 0:
318 return out
319 time.sleep(2)
320 raise Exception(f"alice could not run {cmd}: {out}")
321
322 def side_by_side(head, ended):
323 """Reads alice's records until the observer sees the fast check of
324 her approval at head done while the slow one still prints, and
325 returns that read. It reads for as long as the approval runs, and
326 fails if the slow check ends first."""
327 deadline = time.monotonic() + 300
328 while time.monotonic() < deadline and not ended():
329 ls = observe("read --source=report.alice --limit=1000 --logs")
330 fast_done = [r for r in records(ls, type="check.result", check="fast") if r["head"] == head]
331 if fast_done:
332 run = fast_done[0]["run"]
333 assert not [r for r in records(ls, type="check.result", check="slow") if r["run"] == run], "the slow check ended before the observer saw the fast one end"
334 if [r for r in records(ls, type="check.output", check="slow") if r["run"] == run and "slow tick" in r["data"]["text"]]:
335 return ls
336 time.sleep(1)
337 raise Exception(f"never saw the fast check done while the slow one built, at {head}")
338
339 def filed(head):
340 """Flushes alice's records until the observer reads her approval at
341 head filed, and returns that read and those approve.end records."""
342 for _ in range(60):
343 as_alice("valley telemetry flush")
344 ls = observe("read --source=report.alice --limit=1000")
345 ends = [r for r in records(ls, type="approve.end") if r["head"] == head and r["data"]["result"] == "filed"]
346 if ends:
347 return ls, ends
348 time.sleep(1)
349 raise Exception(f"the approval at {head} was never observed filed")
350
351 def ready(branch, path, script=None, rebuild=False):
352 """A change by alice: one new file, and the slow check's script
353 given, or changed so that its derivation is built again."""
354 cp = f"cp {script} slow.sh && " if script else ""
355 if rebuild:
356 cp += f"echo '# {branch}' >> slow.sh && "
357 as_alice(
358 f"git fetch --quiet origin && git checkout --quiet -B {branch} origin/main && {cp}"
359 f"mkdir -p $(dirname {path}) && echo {branch} > {path} && git add -A && {commit} -m {branch}"
360 )
361 pushing(f"git push --quiet origin {branch} && valley ready {branch}")
362 return as_alice(f"git rev-parse {branch}").strip()
363
364 with subtest("the instance and the project are seeded, and alice has a checkout"):
365 land_instance(None)
366 host.succeed(
367 "mkdir -p /tmp/project/policy",
368 "cp ${flake} /tmp/project/flake.nix",
369 "cp ${flakeLock} /tmp/project/flake.lock",
370 "cp ${slow} /tmp/project/slow.sh",
371 "cp ${fast} /tmp/project/fast.sh",
372 "echo 'git@host:instance.git' > /tmp/project/policy/valley",
373 f"cd /tmp/project && git init --quiet --initial-branch=main && git add -A && {commit} -m project",
374 "chown -R git:git /tmp/project",
375 f"{git} -C /srv/git/project.git fetch --quiet /tmp/project main:refs/heads/main",
376 "mkdir -p /root/keys /root/.ssh && cp ${keys}/* /root/keys/ && chmod 600 /root/keys/*",
377 "printf 'Host localhost host\\n IdentityFile /root/keys/operator\\n IdentitiesOnly yes\\n"
378 " StrictHostKeyChecking no\\n UserKnownHostsFile /dev/null\\n' > /root/.ssh/config",
379 "mkdir -p /home/alice/keys /home/alice/.ssh && install -m 600 ${keys}/alice /home/alice/keys/alice",
380 "printf 'Host localhost host\\n IdentityFile /home/alice/keys/alice\\n IdentitiesOnly yes\\n"
381 " StrictHostKeyChecking no\\n UserKnownHostsFile /dev/null\\n' > /home/alice/.ssh/config",
382 "chown -R alice /home/alice",
383 )
384 host.succeed("sudo -u alice -H git clone --quiet git@localhost:project.git /home/alice/project")
385 as_alice("git config valley.principal alice && git config user.name alice && git config user.email alice@example.org"
386 " && git config valley.telemetry true")
387 # The worker makes its key, and is enrolled.
388 host.fail("systemctl start valley-worker.service")
389 land_instance(" ".join(host.succeed("cat /var/lib/valley-worker/key.pub").split()[:2]))
390 host.wait_until_succeeds(
391 f"{git} -C /srv/git/instance.git cat-file blob refs/the-valley/signers:known-signers | grep -q '^alice/attestations+'",
392 timeout=60,
393 )
394
395 with subtest("valley-init keeps the controllers across activations, holds back the compiler and the publisher once failed, and its repair restores all three"):
396 def show(unit, prop):
397 return host.succeed(f"systemctl show -P {prop} {unit}").strip()
398 # One controller for each project the host declares.
399 controllers = [${lib.concatMapStringsSep ", " (name: ''"valley-integrator@${name}.service"'') (lib.attrNames projects)}]
400 running = " && ".join(f"systemctl is-active -q {c}" for c in controllers)
401 watched = controllers + ["valley-init"]
402 host.succeed(running)
403 # An activation that leaves valley-init's unit alone stops nothing.
404 before = {u: show(u, "InvocationID") for u in watched}
405 host.succeed("/run/booted-system/bin/switch-to-configuration test")
406 assert {u: show(u, "InvocationID") for u in watched} == before, "an activation that left valley-init alone stopped something"
407 host.succeed(running)
408 # One that changes it runs it again, and the controllers run after,
409 # there and back.
410 host.succeed("/run/booted-system/specialisation/init-changed/bin/switch-to-configuration test")
411 assert show("valley-init", "InvocationID") != before["valley-init"]
412 host.wait_until_succeeds(running, timeout=60)
413 host.succeed("/run/booted-system/bin/switch-to-configuration test")
414 host.wait_until_succeeds(running, timeout=60)
415 # Activation starts the worker's path and timer, which this test
416 # keeps stopped.
417 host.succeed("systemctl stop valley-worker.timer valley-worker.path")
418 # valley-init fails before its script runs, so its record stays,
419 # and a registry enrolling the operator as a signer lands. With the
420 # compiler's timers stopped, only valley-init's repair can compile
421 # and publish it.
422 host.succeed("systemctl stop valley-identity.timer valley-identity-midnight.timer")
423 host.succeed(
424 "mkdir -p /run/systemd/system/valley-init.service.d",
425 "printf '[Service]\\nExecStartPre=/run/current-system/sw/bin/false\\n'"
426 " > /run/systemd/system/valley-init.service.d/fail.conf",
427 "systemctl daemon-reload",
428 )
429 host.fail("systemctl restart valley-init.service")
430 host.succeed("test -e /srv/git/.valley-converged")
431 assert not any(show(c, "ActiveState") == "active" for c in controllers), "a controller runs after valley-init failed"
432 consumers = ["valley-identity", "valley-signers"]
433 ran = {u: show(u, "InvocationID") for u in consumers}
434 signers = f"{git} -C /srv/git/instance.git cat-file blob refs/the-valley/signers:known-signers"
435 land_instance(" ".join(host.succeed("cat /var/lib/valley-worker/key.pub").split()[:2]), operator=True, compile=False)
436 for u in consumers:
437 host.fail(f"systemctl start {u}.service")
438 assert {u: show(u, "InvocationID") for u in consumers} == ran, "a consumer ran after valley-init failed"
439 host.fail(f"{signers} | grep -q '^operator/attestations+'")
440 host.succeed(
441 "rm /run/systemd/system/valley-init.service.d/fail.conf",
442 "systemctl daemon-reload",
443 "systemctl restart valley-init.service",
444 )
445 host.wait_until_succeeds(f"{signers} | grep -q '^operator/attestations+'", timeout=60)
446 host.wait_until_succeeds(running, timeout=60)
447 host.succeed("systemctl start valley-identity.timer valley-identity-midnight.timer")
448
449 with subtest("an enrolled observer reads the catalog, and nobody else does"):
450 srcs = {s["name"]: s for s in of(observe("sources"), "source")}
451 for name in ["worker", "integrator", "identity", "signers", "mirrors", "convergence", "telemetry", "report.alice"]:
452 assert srcs[name]["enabled"], (name, srcs[name])
453 for name in ["bus", "backup", "web-publisher", "web-receiver", "restacker"]:
454 assert srcs[name]["state"] == "disabled", srcs[name]
455 assert srcs["remote-receiver"]["location"] == "remote" and srcs["remote-receiver"]["state"] == "unavailable", srcs["remote-receiver"]
456 assert srcs["integrator"]["not_instrumented"], srcs["integrator"]
457 assert srcs["worker"]["configured"]["attest"].startswith("/nix/store/"), srcs["worker"]
458 props = srcs["worker"]["unit_states"][0]
459 assert "Environment" not in props and props["Id"] == "valley-worker.service", props
460
461 for who, command, said in [
462 ("contributor", "valley-telemetry sources", "does not hold the telemetry observe grant"),
463 ("stranger", "valley-telemetry sources", "a key that names a principal"),
464 ("alice", "valley-telemetry sources", "does not hold the telemetry observe grant"),
465 ("operator", "valley-telemetry report", "does not hold the telemetry report grant"),
466 ("operator", "valley-telemetry sources; id", "not a telemetry operation"),
467 ("operator", "valley-telemetry sources && id", "is not a flag"),
468 ("operator", "valley-telemetry read --source=../../var/lib/valley-worker/key", "not a source name"),
469 ("operator", "valley-telemetry read --source=valley-*", "not a source name"),
470 ("operator", "valley-telemetry read --unit=sshd.service", "takes no --unit"),
471 ("operator", "valley-telemetry exec id", "not a telemetry operation"),
472 ("operator", "valley-telemetry read --source=nosuch", "no source is named nosuch"),
473 ]:
474 status, out = host.execute(raw(who, command) + " < /dev/null 2>&1")
475 assert status != 0 and said in out and "uid=" not in out, (who, command, status, out)
476 for command in ["id", "sh -c id", "systemctl restart valley-worker", "journalctl -u valley-worker"]:
477 status, out = host.execute(raw("operator", command) + " < /dev/null 2>&1")
478 assert status != 0 and "uid=" not in out and '"kind"' not in out, (command, out)
479 # A principal the client names in its environment is no principal.
480 status, out = host.execute(raw("contributor", "valley-telemetry sources", "-o SetEnv=VALLEY_PRINCIPAL=operator") + " 2>&1")
481 assert status != 0 and '"kind": "source"' not in out and '"kind":"source"' not in out, out
482 # A forced fetch-only key runs its forced command whatever it asks.
483 status, out = host.execute(raw("fetcher", "valley-telemetry sources") + " < /dev/null 2>&1")
484 assert '"kind"' not in out and "refs/heads/main" in out, out
485 # Reading is open while pushes are held.
486 host.succeed("touch /srv/git/.valley-hold")
487 assert of(observe("sources"), "end")
488 host.fail("sudo -u alice -H bash -c 'cd /home/alice/project && git push --quiet origin HEAD:refs/heads/held'")
489 host.succeed("rm /srv/git/.valley-hold")
490
491 with subtest("private keys stay private, and the diagnostics are the collector's alone to read"):
492 for user in ["git", "valley-telemetry"]:
493 host.fail(f"sudo -u {user} cat /var/lib/valley-worker/key")
494 host.fail(f"sudo -u {user} ls /var/lib/valley-worker")
495 host.fail("sudo -u git ls /var/lib/valley-telemetry/worker")
496 host.fail("sudo -u git ls /var/lib/valley-telemetry/collector")
497 assert "systemd-journal" not in host.succeed("id -nG git")
498 assert host.succeed("stat -c '%a %U %G' /var/lib/valley-telemetry/worker").strip() == "2750 valley-worker valley-telemetry"
499 assert host.succeed("stat -c '%a %U %G' /var/lib/valley-worker").strip() == "700 valley-worker valley-worker"
500 assert host.succeed("stat -c '%a %U' /run/valley-telemetry.sock").strip() == "600 git"
501
502 with subtest("a unit the host declares is a source, failed and logged as the module's own are"):
503 host.fail("systemctl start host-probe.service")
504 probe = source("host-probe")
505 assert probe["location"] == "local" and probe["state"] == "failed", probe
506 assert "host-probe.service" in probe["detail"] and probe["unit_states"][0]["ExecMainStatus"] == "3", probe
507 assert probe["unit_states"][0]["Id"] == "host-probe.service" and "Environment" not in probe["unit_states"][0], probe
508 assert [s for s in of(observe("sources"), "source") if s["name"] == "host-probe"][0]["state"] == "failed"
509 shown = host.succeed("valley telemetry --remote git@localhost:project.git read --source=host-probe --logs")
510 assert "host-probe says why" in shown and "untrusted output" in shown, shown
511 assert "host-probe says why" not in json.dumps(observe("read --source=host-probe")), "lifecycle only without --logs"
512
513 with subtest("a reader sees a worker's slow check build while it builds, and its interruption after a kill"):
514 good = ready("good", "good.txt")
515 host.succeed("systemctl start --no-block valley-worker.service")
516 host.wait_until_succeeds(
517 "valley telemetry --remote git@localhost:project.git read --source=worker --logs | grep -q 'slow tick 3'",
518 timeout=180,
519 )
520 ls = observe("read --source=worker --limit=1000")
521 starts = records(ls, type="check.build-start", check="slow")
522 assert starts and not records(ls, type="check.result", check="slow"), ls
523 assert starts[-1]["head"] == good and starts[-1]["tree"] and starts[-1]["change"], starts[-1]
524 shown = host.succeed("valley telemetry --remote git@localhost:project.git read --source=worker --logs")
525 assert "untrusted output" in shown and "\\x1b[31mred" in shown and "\x1b" not in shown, shown
526 assert "\x1b" not in "".join(json.dumps(l) for l in observe("read --source=worker --logs"))
527 assert not [r for r in observe("read --source=worker") if "slow tick" in json.dumps(r)]
528
529 host.succeed("systemctl kill --signal=KILL valley-worker.service")
530 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating")
531 worker = source("worker")
532 assert worker["state"] == "stale" and "interrupted" in worker["detail"], worker
533 assert worker["unit_states"][0]["Result"] == "signal", worker
534 lifecycle = of(observe("read --source=worker"), "lifecycle")
535 assert any("status=9/KILL" in l["message"] for l in lifecycle), lifecycle
536
537 host.succeed("systemctl start valley-worker.service")
538 state = source("worker")["exported_state"]
539 assert state["pass"] is None, state
540 kinds = [(a["kind"], a["result"]) for a in state["recent"]]
541 assert ("pass", "interrupted") in kinds and ("pass", "passed") in kinds and ("build", "passed") in kinds, kinds
542 interrupted = [a for a in state["recent"] if a["result"] == "interrupted"][0]
543 assert interrupted["inferred"] and interrupted["head"] == good, interrupted
544 ls = observe("read --source=worker --limit=1000")
545 assert records(ls, type="pass.interrupted") and records(ls, type="publish.end")
546 results = records(ls, type="check.result")
547 assert {r["check"] for r in results} >= {"slow", "fast"}, results
548 assert all(r["data"]["result"] == "passed" and r["data"]["build_ms"] >= 0 for r in results[-2:]), results
549
550 with subtest("a failed batch leaves a backoff naming the change, its head, its tree and why"):
551 broken = ready("broken", "broken.txt", "${broken}")
552 host.fail("systemctl start valley-worker.service")
553 state = source("worker")["exported_state"]
554 failure = [f for f in state["failures"] if f["head"] == broken]
555 assert failure and failure[0]["tree"] and failure[0]["change"] and failure[0]["retry"], state
556 assert "slow failed" in failure[0]["reason"], failure
557 backoff = records(observe("read --source=worker --limit=1000"), type="backoff")
558 assert backoff and backoff[-1]["head"] == broken and backoff[-1]["data"]["retry"], backoff
559 assert "broken check says why" in host.succeed("valley telemetry --remote git@localhost:project.git read --source=worker --logs")
560 # Records survive the collector's restart: each connection is a
561 # collector of its own, and its state is on disk.
562 host.succeed("systemctl restart valley-telemetry.socket")
563 assert records(observe("read --source=worker --limit=1000"), type="backoff")
564
565 with subtest("an observer watches alice's approval build a slow and a fast check side by side"):
566 fresh = ready("fresh", "fresh.txt", rebuild=True)
567 settle()
568 host.succeed(
569 "systemd-run --unit=approve-fresh --uid=alice --setenv=HOME=/home/alice"
570 " --setenv=PATH=/run/wrappers/bin:/run/current-system/sw/bin"
571 " --setenv=VALLEY_ATTEST_KEY=/home/alice/keys/alice --setenv=VALLEY_ATTEST_NAME=alice/attestations"
572 " --working-directory=/home/alice/project --remain-after-exit"
573 f" valley approve --build-here --head {fresh} fresh"
574 )
575 def fresh_ended():
576 assert host.succeed("systemctl show -p Result --value approve-fresh").strip() == "success", "the approval failed"
577 return host.succeed("systemctl show -p SubState --value approve-fresh").strip() == "exited"
578 seen = side_by_side(fresh, fresh_ended)
579 assert all(r["data"]["untrusted"] for r in records(seen, type="check.output"))
580 assert not records(observe("read --source=report.alice --limit=1000"), type="check.output")
581 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value approve-fresh)\" = exited", timeout=300)
582 assert host.succeed("systemctl show -p ExecMainStatus --value approve-fresh").strip() == "0"
583 ls, _ = filed(fresh)
584 mine = [r for r in of(ls, "record") if r.get("head") == fresh]
585 types = [r["type"] for r in mine]
586 for want in ["approve.start", "approve.policy", "approve.coverage", "approve.checks", "run.start", "check.result", "evidence.stored", "run.end", "approve.request", "approve.end"]:
587 assert want in types, (want, types)
588 start = [r for r in mine if r["type"] == "approve.start"][0]
589 assert start["principal"] == "alice" and start["received"] and start["producer"]["version"] and start["producer"]["exe"].startswith("/nix/store/"), start
590 cover = [r for r in mine if r["type"] == "approve.coverage"][0]["data"]
591 assert cover["reused"] == [] and sorted(cover["missing"]) == ["fast", "slow"], cover
592 slow_r = [r for r in mine if r["type"] == "check.result" and r["check"] == "slow"][0]["data"]
593 fast_r = [r for r in mine if r["type"] == "check.result" and r["check"] == "fast"][0]["data"]
594 assert fast_r["build_ended"] < slow_r["build_ended"] and fast_r["build_ms"] < slow_r["build_ms"], (fast_r, slow_r)
595 assert [r for r in mine if r["type"] == "approve.request"][0]["data"]["result"] == "pushed"
596 assert [r for r in mine if r["type"] == "approve.end"][0]["data"]["result"] == "filed"
597
598 with subtest("an observer watches an approval made from review, after a refused attempt in the same session"):
599 reviewed = ready("reviewed", "reviewed.txt", rebuild=True)
600 # One review session answers a, is refused for want of a key,
601 # and answers a again once the key is there. Its answers come
602 # through a FIFO a sleeping writer holds open between them.
603 review = shlex.quote(
604 "sudo -u alice -H env VALLEY_ATTEST_KEY=/home/alice/keys/later VALLEY_ATTEST_NAME=alice/attestations"
605 " bash -c 'cd /home/alice/project && exec valley review --build-here reviewed'"
606 " < /tmp/review.fifo > /tmp/review.out 2>&1"
607 )
608 host.succeed("rm -f /tmp/review.fifo /home/alice/keys/later && mkfifo -m 600 /tmp/review.fifo")
609 settle()
610 host.succeed(f"setsid -f sh -c {review} < /dev/null > /dev/null 2>&1")
611 host.succeed("setsid -f sh -c 'echo $$ > /tmp/review.holder; exec sleep 900 > /tmp/review.fifo' < /dev/null > /dev/null 2>&1")
612 host.wait_until_succeeds("grep -q 'pprove' /tmp/review.out", timeout=120)
613 host.succeed("echo a > /tmp/review.fifo")
614 refused: list = []
615 for _ in range(60):
616 ls = observe("read --source=report.alice --limit=1000")
617 refused = [r for r in records(ls, type="approve.end") if r["head"] == reviewed and r["data"]["result"] == "refused"]
618 if refused:
619 break
620 time.sleep(1)
621 assert refused, "the refused approval from review was never observed"
622 first = refused[0]["run"]
623 first_types = [r["type"] for r in of(ls, "record") if r.get("run") == first]
624 assert first_types[:3] == ["approve.start", "approve.policy", "approve.coverage"] and "approve.checks" not in first_types, first_types
625
626 host.succeed("install -m 600 -o alice ${keys}/alice /home/alice/keys/later")
627 host.wait_until_succeeds("test $(grep -o 'pprove' /tmp/review.out | wc -l) -ge 2", timeout=60)
628 host.succeed("echo a > /tmp/review.fifo")
629 side_by_side(reviewed, lambda: host.execute("grep -q ' approved' /tmp/review.out")[0] == 0)
630 host.wait_until_succeeds("grep -q ' approved' /tmp/review.out", timeout=300)
631 host.succeed("kill $(cat /tmp/review.holder)")
632 ls, second = filed(reviewed)
633 assert len(second) == 1 and second[0]["run"] != first, second
634 run = second[0]["run"]
635 types = [r["type"] for r in of(ls, "record") if r.get("run") == run]
636 for want in ["approve.start", "approve.policy", "approve.coverage", "approve.checks", "approve.request", "approve.end"]:
637 assert want in types, (want, types)
638 assert [r for r in records(ls, type="approve.request") if r["run"] == run][0]["data"]["result"] == "pushed"
639 slow = [r for r in records(ls, type="check.result", check="slow") if r["run"] == run + "-checks"]
640 assert slow and slow[0]["data"]["result"] == "passed", slow
641 assert len([r for r in records(ls, type="approve.end") if r["run"] == first]) == 1
642
643 with subtest("an approval reusing the worker's evidence beside a local check, and one reusing everything, are observable"):
644 mixed = ready("mixed", "local/mixed.txt")
645 host.succeed("systemctl start valley-worker.service")
646 pushing(f"valley approve --head {mixed} mixed")
647 pushing(f"valley approve --head {good} good")
648 as_alice("valley telemetry flush")
649 ls = observe("read --source=report.alice --limit=1000")
650 cover = [r for r in records(ls, type="approve.coverage") if r["head"] == mixed][0]["data"]
651 assert sorted(cover["reused"]) == ["fast", "slow"] and cover["missing"] == ["local"], cover
652 assert len(cover["reused_by"]) == 2 and all("worker" in s for s in cover["reused_by"]), cover
653 local = [r for r in records(ls, type="check.result", check="local") if r["head"] == mixed]
654 assert local and local[0]["data"]["result"] == "passed", local
655 cover = [r for r in records(ls, type="approve.coverage") if r["head"] == good][0]["data"]
656 assert sorted(cover["reused"]) == ["fast", "slow"] and cover["missing"] == [], cover
657 good_types = [r["type"] for r in of(ls, "record") if r.get("head") == good]
658 assert "approve.checks" not in good_types and "approve.end" in good_types, good_types
659 host.wait_until_succeeds(
660 "valley telemetry --remote git@localhost:project.git --json read --source=integrator | grep -q '\"type\":\"decision\"'",
661 timeout=120,
662 )
663 decision = records(observe("read --source=integrator"), type="decision")[-1]
664 assert decision["project"] and decision["data"]["outcome"] and "duration_ms" in decision["data"], decision
665
666 with subtest("checks --build passes once origin holds every check's evidence, and otherwise says why not"):
667 # Two commits ask at once, from two worktrees, and one worker pass
668 # builds both. The first passes. The second's slow check fails, so
669 # its outcome is not established, with the worker's records for its
670 # tree, the slow check's build error, the nix log command for the
671 # slow check's derivation, and where to look when nix has no log.
672 requests = f"{git} -C /srv/git/project.git for-each-ref refs/the-valley/check-requests/"
673 host.succeed("git clone --quiet git@localhost:project.git /root/project && git -C /root/project config valley.principal operator")
674 for branch, cp in [("asked", ""), ("asked-broken", "cp ${broken} slow.sh && ")]:
675 host.succeed(f"git -C /root/project worktree add --quiet -b {branch} /root/{branch} origin/main && cd /root/{branch} && {cp}"
676 f"echo {branch} > {branch}.txt && git add -A && {commit} -m {branch}")
677 asking = shlex.quote(f"cd /root/{branch} && valley checks --build > /tmp/{branch}.out 2>&1; echo $? > /tmp/{branch}.status")
678 host.succeed(f"setsid -f sh -c {asking} < /dev/null > /dev/null 2>&1")
679 host.wait_until_succeeds(f"test $({requests}operator/ | wc -l) = 2", timeout=120)
680 host.execute("systemctl start valley-worker.service")
681 host.wait_until_succeeds("test -s /tmp/asked.status && test -s /tmp/asked-broken.status", timeout=300)
682 passed, failed = host.succeed("cat /tmp/asked.out"), host.succeed("cat /tmp/asked-broken.out")
683 assert host.succeed("cat /tmp/asked.status").strip() == "0" and "2 checks passed" in passed, passed
684 assert host.succeed("cat /tmp/asked-broken.status").strip() == "1", failed
685 assert "not established" in failed and " slow failed" in failed, failed
686 assert re.search(r"^ slow · failed · the worker's build error, untrusted: .+$", failed, re.M), failed
687 assert re.search(r"^ run: nix log /nix/store/[0-9a-z]{32}-telemetry-slow\.drv$", failed, re.M), failed
688 assert " see: valley telemetry read --source worker --logs" in failed, failed
689 assert not host.succeed(requests), "a request was left on origin"
690
691 with subtest("approval and pushes go on when telemetry cannot be reached, and each run's records go only where its run began"):
692 def timed_approve(branch, path):
693 head = ready(branch, path)
694 settle()
695 began = time.monotonic()
696 as_alice(f"valley approve --head {head} {branch}")
697 return time.monotonic() - began, head
698 as_alice("git config valley.telemetry false")
699 plain, _ = timed_approve("plain", "policy/plain.txt")
700 as_alice("git config valley.telemetry true")
701 host.succeed("systemctl stop valley-telemetry.socket")
702 down, head_down = timed_approve("down", "policy/down.txt")
703 as_alice("git config valley.telemetry.remote ssh://git@192.0.2.1/project.git")
704 unreachable, head_away = timed_approve("away", "policy/away.txt")
705 as_alice("git config --unset valley.telemetry.remote")
706 print(f"approve took {plain:.1f}s plain, {down:.1f}s with the collector down, {unreachable:.1f}s with it unreachable")
707 # A guest under load varies one approval by seconds; a wait on
708 # telemetry would be its 20-second flush deadline.
709 assert down < plain + 15 and unreachable < plain + 15, (plain, down, unreachable)
710 pushing("git push --quiet origin HEAD:refs/heads/still-pushes")
711 host.fail("sudo -u alice -H bash -c 'cd /home/alice/project && valley telemetry --remote origin flush'")
712 host.succeed("systemctl start valley-telemetry.socket")
713 time.sleep(12)
714 as_alice("valley telemetry --remote origin flush")
715 assert "0 records sent to ssh://git@localhost" in as_alice("valley telemetry --remote origin flush 2>&1")
716 # The run begun while the telemetry remote named 192.0.2.1 stays
717 # bound to it: a flush from the same checkout, back on origin,
718 # tries that destination and sends its records nowhere else.
719 status, out = as_alice("valley telemetry flush 2>&1", check=False)
720 assert status != 0 and "ssh://git@192.0.2.1" in out, out
721 ls = observe("read --source=report.alice --limit=1000")
722 ends = [r for r in records(ls, type="approve.end") if r["head"] == head_down]
723 assert len(ends) == 1 and ends[0]["data"]["result"] == "filed", ends
724 assert not [r for r in of(ls, "record") if r.get("head") == head_away], "a run bound to another destination reached this one"
725
726 with subtest("every command records its verb, flags, status, time and phases, never a value, and only with telemetry on"):
727 def commands(verb):
728 # Only origin's spool: the outage left one bound to 192.0.2.1.
729 as_alice("valley telemetry --remote origin flush")
730 ls = observe("read --source=report.alice --limit=1000")
731 return ls, [r for r in records(ls, type="command") if r["data"]["verb"] == verb]
732 as_alice("valley pending --json > /tmp/on.json")
733 as_alice("valley status --json zx81q-secret", check=False)
734 ls, pending = commands("pending")
735 d = pending[-1]["data"]
736 assert d["status"] == 0 and d["flags"] == ["--json"] and pending[-1].get("project"), pending[-1]
737 assert d["elapsed_ms"] >= d["fetch_ms"] > 0 and d["fetch_procs"] > 0 and "records_ms" in d, d
738 named = [r for r in records(ls, type="command") if r["data"]["verb"] == "status"]
739 assert named and named[-1]["data"]["status"] == 1 and named[-1]["data"]["flags"] == ["--json"], named
740 assert "zx81q" not in json.dumps(ls), "an argument's value reached the report stream"
741 # Off: no record, and no spool file, under a state home of its own.
742 as_alice("git config --unset valley.telemetry")
743 off = as_alice("XDG_STATE_HOME=/tmp/alice-off valley pending --json > /tmp/off.json"
744 " && XDG_STATE_HOME=/tmp/alice-off valley status --json zx81q-secret; echo $?")
745 host.fail("test -e /tmp/alice-off")
746 assert len(commands("pending")[1]) == len(pending)
747 # Unreachable: the same output and exit status as off.
748 as_alice("git config valley.telemetry true && git config valley.telemetry.remote ssh://git@192.0.2.1/project.git")
749 away = as_alice("valley pending --json > /tmp/away.json && valley status --json zx81q-secret; echo $?")
750 as_alice("git config --unset valley.telemetry.remote")
751 assert away == off and host.succeed("cat /tmp/away.json") == host.succeed("cat /tmp/off.json"), (away, off)
752
753 with subtest("the server holds every request to its limits"):
754 big = '{"type":"approve.start","time":"2026-01-01T00:00:00.000Z","client_id":"0123456789abcdef:1","data":{"x":"' + "y" * 20000 + '"}}'
755 host.succeed(f"echo '{big}' > /tmp/big.json")
756 answer = lines(host.succeed(raw("alice", "valley-telemetry report") + " < /tmp/big.json"))
757 assert of(answer, "ack")[0]["rejected"] == 1 and of(answer, "ack")[0]["accepted"] == 0, answer
758 host.execute("timeout 5 " + raw("operator", "valley-telemetry follow --seconds=99999 --source=telemetry") + " < /dev/null > /tmp/follow.json")
759 header = of(lines(host.succeed("head -1 /tmp/follow.json")), "header")[0]
760 assert header["limits"]["follow_seconds"] == 300, header
761 header = of(observe("read --limit=999999"), "header")[0]
762 assert header["limits"]["read_limit"] == 1000, header
763 '';
764 };
765}