gunk-dev/the-valley

telemetry.nix

source30e24c82839bmain's published tip history
46.6 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 # valley pending surfaces the failed unit (and any unavailable source)
513 # above needs you for an observer, once across --all, and carries it
514 # in --json; a caller without observe sees no host entry and no warning.
515 host.succeed("git clone --quiet git@localhost:project.git /root/project && git -C /root/project config valley.principal operator")
516 pending_op = host.succeed("cd /root/project && valley pending")
517 assert "host host-probe failed · host-probe.service: failed, result exit-code, status 3\n see: valley telemetry read --source host-probe --logs\n" in pending_op, pending_op
518 assert pending_op.index("host host-probe") < pending_op.index("nothing needs you"), pending_op
519 assert "host remote-receiver unavailable · " in pending_op, pending_op
520 for ok_name in ["worker", "integrator", "identity", "signers", "mirrors", "convergence", "telemetry", "bus", "backup"]:
521 assert f"host {ok_name} " not in pending_op, (ok_name, pending_op)
522 pending_all = host.succeed("cd /root/project && valley pending --all")
523 assert pending_all.count("host host-probe ") == 1, pending_all
524 pending_json = json.loads(host.succeed("cd /root/project && valley pending --json"))
525 by_src = {h["source"]: h for h in pending_json["host_sources"]}
526 assert by_src["host-probe"]["state"] == "failed" and by_src["host-probe"]["units"] == ["host-probe.service"], by_src
527 assert "host-probe.service" in by_src["host-probe"]["reason"], by_src
528 assert by_src["remote-receiver"]["state"] == "unavailable" and by_src["remote-receiver"]["units"] == [], by_src
529 pending_alice = as_alice("valley pending 2>/tmp/alice-pending.err")
530 alice_err = host.succeed("cat /tmp/alice-pending.err")
531 assert "host " not in pending_alice and "valley:" not in alice_err and "observe" not in alice_err, (pending_alice, alice_err)
532 alice_json = json.loads(as_alice("valley pending --json"))
533 assert alice_json["host_sources"] == [], alice_json
534 host.succeed("systemctl reset-failed host-probe.service")
535 assert "host host-probe " not in host.succeed("cd /root/project && valley pending")
536
537 with subtest("a reader sees a worker's slow check build while it builds, and its interruption after a kill"):
538 good = ready("good", "good.txt")
539 host.succeed("systemctl start --no-block valley-worker.service")
540 host.wait_until_succeeds(
541 "valley telemetry --remote git@localhost:project.git read --source=worker --logs | grep -q 'slow tick 3'",
542 timeout=180,
543 )
544 ls = observe("read --source=worker --limit=1000")
545 starts = records(ls, type="check.build-start", check="slow")
546 assert starts and not records(ls, type="check.result", check="slow"), ls
547 assert starts[-1]["head"] == good and starts[-1]["tree"] and starts[-1]["change"], starts[-1]
548 shown = host.succeed("valley telemetry --remote git@localhost:project.git read --source=worker --logs")
549 assert "untrusted output" in shown and "\\x1b[31mred" in shown and "\x1b" not in shown, shown
550 assert "\x1b" not in "".join(json.dumps(l) for l in observe("read --source=worker --logs"))
551 assert not [r for r in observe("read --source=worker") if "slow tick" in json.dumps(r)]
552
553 host.succeed("systemctl kill --signal=KILL valley-worker.service")
554 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating")
555 worker = source("worker")
556 assert worker["state"] == "stale" and "interrupted" in worker["detail"], worker
557 assert worker["unit_states"][0]["Result"] == "signal", worker
558 lifecycle = of(observe("read --source=worker"), "lifecycle")
559 assert any("status=9/KILL" in l["message"] for l in lifecycle), lifecycle
560
561 host.succeed("systemctl start valley-worker.service")
562 state = source("worker")["exported_state"]
563 assert state["pass"] is None, state
564 kinds = [(a["kind"], a["result"]) for a in state["recent"]]
565 assert ("pass", "interrupted") in kinds and ("pass", "passed") in kinds and ("build", "passed") in kinds, kinds
566 interrupted = [a for a in state["recent"] if a["result"] == "interrupted"][0]
567 assert interrupted["inferred"] and interrupted["head"] == good, interrupted
568 ls = observe("read --source=worker --limit=1000")
569 assert records(ls, type="pass.interrupted") and records(ls, type="publish.end")
570 results = records(ls, type="check.result")
571 assert {r["check"] for r in results} >= {"slow", "fast"}, results
572 assert all(r["data"]["result"] == "passed" and r["data"]["build_ms"] >= 0 for r in results[-2:]), results
573
574 with subtest("a failed batch leaves a backoff naming the change, its head, its tree and why"):
575 broken = ready("broken", "broken.txt", "${broken}")
576 host.fail("systemctl start valley-worker.service")
577 state = source("worker")["exported_state"]
578 failure = [f for f in state["failures"] if f["head"] == broken]
579 assert failure and failure[0]["tree"] and failure[0]["change"] and failure[0]["retry"], state
580 assert "slow failed" in failure[0]["reason"], failure
581 backoff = records(observe("read --source=worker --limit=1000"), type="backoff")
582 assert backoff and backoff[-1]["head"] == broken and backoff[-1]["data"]["retry"], backoff
583 assert "broken check says why" in host.succeed("valley telemetry --remote git@localhost:project.git read --source=worker --logs")
584 # Records survive the collector's restart: each connection is a
585 # collector of its own, and its state is on disk.
586 host.succeed("systemctl restart valley-telemetry.socket")
587 assert records(observe("read --source=worker --limit=1000"), type="backoff")
588
589 with subtest("an observer watches alice's approval build a slow and a fast check side by side"):
590 fresh = ready("fresh", "fresh.txt", rebuild=True)
591 settle()
592 host.succeed(
593 "systemd-run --unit=approve-fresh --uid=alice --setenv=HOME=/home/alice"
594 " --setenv=PATH=/run/wrappers/bin:/run/current-system/sw/bin"
595 " --setenv=VALLEY_ATTEST_KEY=/home/alice/keys/alice --setenv=VALLEY_ATTEST_NAME=alice/attestations"
596 " --working-directory=/home/alice/project --remain-after-exit"
597 f" valley approve --build-here --head {fresh} fresh"
598 )
599 def fresh_ended():
600 assert host.succeed("systemctl show -p Result --value approve-fresh").strip() == "success", "the approval failed"
601 return host.succeed("systemctl show -p SubState --value approve-fresh").strip() == "exited"
602 seen = side_by_side(fresh, fresh_ended)
603 assert all(r["data"]["untrusted"] for r in records(seen, type="check.output"))
604 assert not records(observe("read --source=report.alice --limit=1000"), type="check.output")
605 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value approve-fresh)\" = exited", timeout=300)
606 assert host.succeed("systemctl show -p ExecMainStatus --value approve-fresh").strip() == "0"
607 ls, _ = filed(fresh)
608 mine = [r for r in of(ls, "record") if r.get("head") == fresh]
609 types = [r["type"] for r in mine]
610 for want in ["approve.start", "approve.policy", "approve.coverage", "approve.checks", "run.start", "check.result", "evidence.stored", "run.end", "approve.request", "approve.end"]:
611 assert want in types, (want, types)
612 start = [r for r in mine if r["type"] == "approve.start"][0]
613 assert start["principal"] == "alice" and start["received"] and start["producer"]["version"] and start["producer"]["exe"].startswith("/nix/store/"), start
614 cover = [r for r in mine if r["type"] == "approve.coverage"][0]["data"]
615 assert cover["reused"] == [] and sorted(cover["missing"]) == ["fast", "slow"], cover
616 slow_r = [r for r in mine if r["type"] == "check.result" and r["check"] == "slow"][0]["data"]
617 fast_r = [r for r in mine if r["type"] == "check.result" and r["check"] == "fast"][0]["data"]
618 assert fast_r["build_ended"] < slow_r["build_ended"] and fast_r["build_ms"] < slow_r["build_ms"], (fast_r, slow_r)
619 assert [r for r in mine if r["type"] == "approve.request"][0]["data"]["result"] == "pushed"
620 assert [r for r in mine if r["type"] == "approve.end"][0]["data"]["result"] == "filed"
621
622 with subtest("an observer watches an approval made from review, after a refused attempt in the same session"):
623 reviewed = ready("reviewed", "reviewed.txt", rebuild=True)
624 # One review session answers a, is refused for want of a key,
625 # and answers a again once the key is there. Its answers come
626 # through a FIFO a sleeping writer holds open between them.
627 review = shlex.quote(
628 "sudo -u alice -H env VALLEY_ATTEST_KEY=/home/alice/keys/later VALLEY_ATTEST_NAME=alice/attestations"
629 " bash -c 'cd /home/alice/project && exec valley review --build-here reviewed'"
630 " < /tmp/review.fifo > /tmp/review.out 2>&1"
631 )
632 host.succeed("rm -f /tmp/review.fifo /home/alice/keys/later && mkfifo -m 600 /tmp/review.fifo")
633 settle()
634 host.succeed(f"setsid -f sh -c {review} < /dev/null > /dev/null 2>&1")
635 host.succeed("setsid -f sh -c 'echo $$ > /tmp/review.holder; exec sleep 900 > /tmp/review.fifo' < /dev/null > /dev/null 2>&1")
636 host.wait_until_succeeds("grep -q 'pprove' /tmp/review.out", timeout=120)
637 host.succeed("echo a > /tmp/review.fifo")
638 refused: list = []
639 for _ in range(60):
640 ls = observe("read --source=report.alice --limit=1000")
641 refused = [r for r in records(ls, type="approve.end") if r["head"] == reviewed and r["data"]["result"] == "refused"]
642 if refused:
643 break
644 time.sleep(1)
645 assert refused, "the refused approval from review was never observed"
646 first = refused[0]["run"]
647 first_types = [r["type"] for r in of(ls, "record") if r.get("run") == first]
648 assert first_types[:3] == ["approve.start", "approve.policy", "approve.coverage"] and "approve.checks" not in first_types, first_types
649
650 host.succeed("install -m 600 -o alice ${keys}/alice /home/alice/keys/later")
651 host.wait_until_succeeds("test $(grep -o 'pprove' /tmp/review.out | wc -l) -ge 2", timeout=60)
652 host.succeed("echo a > /tmp/review.fifo")
653 side_by_side(reviewed, lambda: host.execute("grep -q ' approved' /tmp/review.out")[0] == 0)
654 host.wait_until_succeeds("grep -q ' approved' /tmp/review.out", timeout=300)
655 host.succeed("kill $(cat /tmp/review.holder)")
656 ls, second = filed(reviewed)
657 assert len(second) == 1 and second[0]["run"] != first, second
658 run = second[0]["run"]
659 types = [r["type"] for r in of(ls, "record") if r.get("run") == run]
660 for want in ["approve.start", "approve.policy", "approve.coverage", "approve.checks", "approve.request", "approve.end"]:
661 assert want in types, (want, types)
662 assert [r for r in records(ls, type="approve.request") if r["run"] == run][0]["data"]["result"] == "pushed"
663 slow = [r for r in records(ls, type="check.result", check="slow") if r["run"] == run + "-checks"]
664 assert slow and slow[0]["data"]["result"] == "passed", slow
665 assert len([r for r in records(ls, type="approve.end") if r["run"] == first]) == 1
666
667 with subtest("an approval reusing the worker's evidence beside a local check, and one reusing everything, are observable"):
668 mixed = ready("mixed", "local/mixed.txt")
669 host.succeed("systemctl start valley-worker.service")
670 pushing(f"valley approve --head {mixed} mixed")
671 pushing(f"valley approve --head {good} good")
672 as_alice("valley telemetry flush")
673 ls = observe("read --source=report.alice --limit=1000")
674 cover = [r for r in records(ls, type="approve.coverage") if r["head"] == mixed][0]["data"]
675 assert sorted(cover["reused"]) == ["fast", "slow"] and cover["missing"] == ["local"], cover
676 assert len(cover["reused_by"]) == 2 and all("worker" in s for s in cover["reused_by"]), cover
677 local = [r for r in records(ls, type="check.result", check="local") if r["head"] == mixed]
678 assert local and local[0]["data"]["result"] == "passed", local
679 cover = [r for r in records(ls, type="approve.coverage") if r["head"] == good][0]["data"]
680 assert sorted(cover["reused"]) == ["fast", "slow"] and cover["missing"] == [], cover
681 good_types = [r["type"] for r in of(ls, "record") if r.get("head") == good]
682 assert "approve.checks" not in good_types and "approve.end" in good_types, good_types
683 host.wait_until_succeeds(
684 "valley telemetry --remote git@localhost:project.git --json read --source=integrator | grep -q '\"type\":\"decision\"'",
685 timeout=120,
686 )
687 decision = records(observe("read --source=integrator"), type="decision")[-1]
688 assert decision["project"] and decision["data"]["outcome"] and "duration_ms" in decision["data"], decision
689
690 with subtest("checks --build passes once origin holds every check's evidence, and otherwise says why not"):
691 # Two commits ask at once, from two worktrees, and one worker pass
692 # builds both. The first passes. The second's slow check fails, so
693 # its outcome is not established, with the worker's records for its
694 # tree, the slow check's build error, the nix log command for the
695 # slow check's derivation, and where to look when nix has no log.
696 requests = f"{git} -C /srv/git/project.git for-each-ref refs/the-valley/check-requests/"
697 host.succeed("git -C /root/project fetch --quiet origin")
698 for branch, cp in [("asked", ""), ("asked-broken", "cp ${broken} slow.sh && ")]:
699 host.succeed(f"git -C /root/project worktree add --quiet -b {branch} /root/{branch} origin/main && cd /root/{branch} && {cp}"
700 f"echo {branch} > {branch}.txt && git add -A && {commit} -m {branch}")
701 asking = shlex.quote(f"cd /root/{branch} && valley checks --build > /tmp/{branch}.out 2>&1; echo $? > /tmp/{branch}.status")
702 host.succeed(f"setsid -f sh -c {asking} < /dev/null > /dev/null 2>&1")
703 host.wait_until_succeeds(f"test $({requests}operator/ | wc -l) = 2", timeout=120)
704 host.execute("systemctl start valley-worker.service")
705 host.wait_until_succeeds("test -s /tmp/asked.status && test -s /tmp/asked-broken.status", timeout=300)
706 passed, failed = host.succeed("cat /tmp/asked.out"), host.succeed("cat /tmp/asked-broken.out")
707 assert host.succeed("cat /tmp/asked.status").strip() == "0" and "2 checks passed" in passed, passed
708 assert host.succeed("cat /tmp/asked-broken.status").strip() == "1", failed
709 assert "not established" in failed and " slow failed" in failed, failed
710 assert re.search(r"^ slow · failed · the worker's build error, untrusted: .+$", failed, re.M), failed
711 assert re.search(r"^ run: nix log /nix/store/[0-9a-z]{32}-telemetry-slow\.drv$", failed, re.M), failed
712 assert " see: valley telemetry read --source worker --logs" in failed, failed
713 assert not host.succeed(requests), "a request was left on origin"
714
715 with subtest("approval and pushes go on when telemetry cannot be reached, and each run's records go only where its run began"):
716 def timed_approve(branch, path):
717 head = ready(branch, path)
718 settle()
719 began = time.monotonic()
720 as_alice(f"valley approve --head {head} {branch}")
721 return time.monotonic() - began, head
722 as_alice("git config valley.telemetry false")
723 plain, _ = timed_approve("plain", "policy/plain.txt")
724 as_alice("git config valley.telemetry true")
725 host.succeed("systemctl stop valley-telemetry.socket")
726 down, head_down = timed_approve("down", "policy/down.txt")
727 as_alice("git config valley.telemetry.remote ssh://git@192.0.2.1/project.git")
728 unreachable, head_away = timed_approve("away", "policy/away.txt")
729 as_alice("git config --unset valley.telemetry.remote")
730 print(f"approve took {plain:.1f}s plain, {down:.1f}s with the collector down, {unreachable:.1f}s with it unreachable")
731 # A guest under load varies one approval by seconds; a wait on
732 # telemetry would be its 20-second flush deadline.
733 assert down < plain + 15 and unreachable < plain + 15, (plain, down, unreachable)
734 pushing("git push --quiet origin HEAD:refs/heads/still-pushes")
735 host.fail("sudo -u alice -H bash -c 'cd /home/alice/project && valley telemetry --remote origin flush'")
736 host.succeed("systemctl start valley-telemetry.socket")
737 time.sleep(12)
738 as_alice("valley telemetry --remote origin flush")
739 assert "0 records sent to ssh://git@localhost" in as_alice("valley telemetry --remote origin flush 2>&1")
740 # The run begun while the telemetry remote named 192.0.2.1 stays
741 # bound to it: a flush from the same checkout, back on origin,
742 # tries that destination and sends its records nowhere else.
743 status, out = as_alice("valley telemetry flush 2>&1", check=False)
744 assert status != 0 and "ssh://git@192.0.2.1" in out, out
745 ls = observe("read --source=report.alice --limit=1000")
746 ends = [r for r in records(ls, type="approve.end") if r["head"] == head_down]
747 assert len(ends) == 1 and ends[0]["data"]["result"] == "filed", ends
748 assert not [r for r in of(ls, "record") if r.get("head") == head_away], "a run bound to another destination reached this one"
749
750 with subtest("every command records its verb, flags, status, time and phases, never a value, and only with telemetry on"):
751 def commands(verb):
752 # Only origin's spool: the outage left one bound to 192.0.2.1.
753 as_alice("valley telemetry --remote origin flush")
754 ls = observe("read --source=report.alice --limit=1000")
755 return ls, [r for r in records(ls, type="command") if r["data"]["verb"] == verb]
756 as_alice("valley pending --json > /tmp/on.json")
757 as_alice("valley status --json zx81q-secret", check=False)
758 ls, pending = commands("pending")
759 d = pending[-1]["data"]
760 assert d["status"] == 0 and d["flags"] == ["--json"] and pending[-1].get("project"), pending[-1]
761 assert d["elapsed_ms"] >= d["fetch_ms"] > 0 and d["fetch_procs"] > 0 and "records_ms" in d, d
762 named = [r for r in records(ls, type="command") if r["data"]["verb"] == "status"]
763 assert named and named[-1]["data"]["status"] == 1 and named[-1]["data"]["flags"] == ["--json"], named
764 assert "zx81q" not in json.dumps(ls), "an argument's value reached the report stream"
765 # Off: no record, and no spool file, under a state home of its own.
766 as_alice("git config --unset valley.telemetry")
767 off = as_alice("XDG_STATE_HOME=/tmp/alice-off valley pending --json > /tmp/off.json"
768 " && XDG_STATE_HOME=/tmp/alice-off valley status --json zx81q-secret; echo $?")
769 host.fail("test -e /tmp/alice-off")
770 assert len(commands("pending")[1]) == len(pending)
771 # Unreachable: the same output and exit status as off.
772 as_alice("git config valley.telemetry true && git config valley.telemetry.remote ssh://git@192.0.2.1/project.git")
773 away = as_alice("valley pending --json > /tmp/away.json && valley status --json zx81q-secret; echo $?")
774 as_alice("git config --unset valley.telemetry.remote")
775 assert away == off and host.succeed("cat /tmp/away.json") == host.succeed("cat /tmp/off.json"), (away, off)
776
777 with subtest("the server holds every request to its limits"):
778 big = '{"type":"approve.start","time":"2026-01-01T00:00:00.000Z","client_id":"0123456789abcdef:1","data":{"x":"' + "y" * 20000 + '"}}'
779 host.succeed(f"echo '{big}' > /tmp/big.json")
780 answer = lines(host.succeed(raw("alice", "valley-telemetry report") + " < /tmp/big.json"))
781 assert of(answer, "ack")[0]["rejected"] == 1 and of(answer, "ack")[0]["accepted"] == 0, answer
782 host.execute("timeout 5 " + raw("operator", "valley-telemetry follow --seconds=99999 --source=telemetry") + " < /dev/null > /tmp/follow.json")
783 header = of(lines(host.succeed("head -1 /tmp/follow.json")), "header")[0]
784 assert header["limits"]["follow_seconds"] == 300, header
785 header = of(observe("read --limit=999999"), "header")[0]
786 assert header["limits"]["read_limit"] == 1000, header
787 '';
788 };
789}