gunk-dev/the-valley

telemetry.nix

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