gunk-dev/the-valley

telemetry.nix

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