gunk-dev/the-valley

telemetry.nix

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