interplane.Get Omega
Read in your language

interplane-forge

INTERPLANE Forge

Brought by drakestapleton

branch main Branches Tags History

interplane-forge / infra / test / sandbox-refresh.py

211 lines · 9025 bytes Raw Blame History
1#!/usr/bin/env python3
2"""External measurement oracle. Python is not a service/build dependency."""
3import hashlib
4import http.client
5import json
6import os
7from pathlib import Path
8import signal
9import subprocess
10import sys
11import threading
12import time
13
14T, ROOT, PORT = Path(sys.argv[1]), Path(sys.argv[2]), int(sys.argv[3])
15H = T / 'home'
16PUBLIC = H / 'forge-public'
17RIDS = H / 'handoffs/radicle/RIDS.md'
18RID = 'z631r2JJiVT8it4tST7RK24hpowi'
19READER = T / 'public-read'
20INTERVAL = 2
21
22def atomic(path, content):
23 tmp = path.with_name(path.name + '.new')
24 tmp.write_bytes(content)
25 tmp.replace(path)
26
27def until(check, seconds=12):
28 deadline = time.monotonic() + seconds
29 while time.monotonic() < deadline:
30 if check():
31 return
32 time.sleep(.02)
33 raise AssertionError('deadline: ' + repr(check))
34
35def request(path='/'):
36 conn = http.client.HTTPConnection('127.0.0.1', PORT, timeout=1)
37 try:
38 conn.request('GET', path)
39 resp = conn.getresponse()
40 return resp.status, resp.read()
41 except (OSError, http.client.HTTPException):
42 return 0, b''
43 finally:
44 conn.close()
45
46def safe_read(path, expected=None):
47 result = subprocess.run([READER, str(path)], capture_output=True, timeout=3)
48 if expected is None:
49 assert result.returncode != 0 and result.stdout == b'', (path, result)
50 else:
51 assert result.returncode == 0 and result.stdout == expected
52
53def negative_controls():
54 n = T / 'mirror-negative'
55 n.mkdir()
56 secret = n / 'secret'
57 secret.write_bytes(b'MUST-NOT-EXPORT')
58 (n / 'leaf').symlink_to(secret)
59 safe_read(n / 'leaf')
60 (n / 'parent').symlink_to(n, target_is_directory=True)
61 safe_read(n / 'parent/secret')
62 os.mkfifo(n / 'fifo')
63 safe_read(n / 'fifo')
64 safe_read(n)
65 cap = 1048576
66 (n / 'cap').write_bytes(b'x' * cap)
67 safe_read(n / 'cap', b'x' * cap)
68 (n / 'large').write_bytes(b'x' * (cap + 1))
69 safe_read(n / 'large')
70 # Race an ancestor between a genuine directory and an outside symlink.
71 (n / 'good').mkdir()
72 (n / 'good/file').write_bytes(b'public')
73 (n / 'outside').mkdir()
74 (n / 'outside/file').write_bytes(b'MUST-NOT-EXPORT')
75 halt = threading.Event()
76 def racer():
77 while not halt.is_set():
78 (n / 'good').rename(n / 'held')
79 (n / 'good').symlink_to(n / 'outside', target_is_directory=True)
80 (n / 'good').unlink()
81 (n / 'held').rename(n / 'good')
82 thread = threading.Thread(target=racer)
83 thread.start()
84 try:
85 for _ in range(100):
86 r = subprocess.run([READER, str(n / 'good/file')], capture_output=True, timeout=3)
87 assert (r.returncode == 0 and r.stdout == b'public') or (r.returncode != 0 and not r.stdout)
88 finally:
89 halt.set()
90 thread.join()
91 print('PASS mirror reader: leaf links, ancestor links and races, FIFO, directory, exact cap and cap+1')
92
93negative_controls()
94env = dict(os.environ, FORGED_BIN=str(T/'forged'), FORGED_PORT=str(PORT),
95 FORGED_CPUS=os.environ.get('FORGED_CPUS', '12,13'), FORGED_MIRROR_INTERVAL=str(INTERVAL))
96log = (T / 'refresh-supervisor-process.log').open('wb')
97proc = subprocess.Popen(['bash', str(ROOT/'infra/spark/forged-service.sh'), '_loop'],
98 env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
99
100def child():
101 try:
102 for pid in Path(f'/proc/{proc.pid}/task/{proc.pid}/children').read_text().split():
103 cmd = Path(f'/proc/{pid}/cmdline').read_bytes()
104 if b'bwrap' in cmd and b'/app/forged' in cmd:
105 return int(pid)
106 except (FileNotFoundError, ProcessLookupError):
107 pass
108 return None
109
110try:
111 until(lambda: request()[0] == 200)
112 original_child = child()
113 assert original_child
114 # Atomically replace metadata without changing the mount set.
115 nodes = H/'.local/state/aien-factory/nodes.txt'
116 verdict = H/'handoffs/hive/manager/reviews/fixture.verdict.txt'
117 receipt = H/'handoffs/hive/forge/receipts/fixture.receipt.txt'
118 updates = [(RIDS, b'# r2 replacement\n'+RIDS.read_bytes()),
119 (nodes, nodes.read_bytes().replace(b'\n2\n'+RID.encode(), b'\n7\n'+RID.encode())),
120 (verdict, b'public verdict replaced\n'), (receipt, b'public receipt replaced\n')]
121 # First wait for a mirror pass, then replace. Bound includes copy and scheduling time.
122 initial = PUBLIC/'RIDS.md'
123 atomic(RIDS, b'# align\n'+RIDS.read_bytes())
124 until(lambda: initial.read_bytes() == RIDS.read_bytes())
125 began = time.monotonic_ns()
126 for src, body in updates:
127 atomic(src, body)
128 until(lambda: all((PUBLIC/src.name).exists() and (PUBLIC/src.name).read_bytes() == body
129 for src, body in updates), INTERVAL + 2)
130 elapsed = time.monotonic_ns() - began
131 assert child() == original_child, 'metadata-only update restarted child'
132 assert b'"peers":7' in request('/status.json')[1], request('/status.json')
133 print('PASS replaced RIDS, nodes, verdict and receipt mirrored; same child; elapsed_ns=', elapsed)
134 # Stale exports are removed on missing, unsafe and oversized source inputs.
135 verdict.unlink()
136 until(lambda: not (PUBLIC/verdict.name).exists())
137 receipt.unlink()
138 receipt.symlink_to(T/'mirror-negative/secret')
139 until(lambda: not (PUBLIC/receipt.name).exists())
140 receipt.unlink()
141 atomic(receipt, b'x'*1048577)
142 until(lambda: not (PUBLIC/receipt.name).exists())
143 time.sleep(INTERVAL + .1)
144 assert not (PUBLIC/receipt.name).exists()
145 receipt.unlink()
146 print('PASS mirror revokes removed, linked and oversized sources')
147 # Pushing into an existing directory must not change the child/mount identity.
148 before = child()
149 marker = b'# new commit while sandbox runs\n'
150 (T/'source/README.md').write_bytes(marker)
151 subprocess.run(['git', '-C', str(T/'source'), 'add', 'README.md'], check=True)
152 subprocess.run(['git', '-C', str(T/'source'), '-c', 'user.name=Drake Stapleton',
153 '-c', 'user.email=213298340+drakestapleton@users.noreply.github.com',
154 'commit', '-qm', 'fixture live push'], check=True)
155 subprocess.run(['git', '-C', str(T/'source'), 'push', str(H/'.radicle/storage'/RID), 'main'], check=True)
156 until(lambda: request('/drakestapleton/cuda-crack/raw/main/README.md') == (200, marker))
157 time.sleep(INTERVAL + .1)
158 assert child() == before
159 print('PASS pushed commit visible without child restart')
160 # Continuous root requests bracket each actual process replacement.
161 samples, halt = [], threading.Event()
162 def sample():
163 while not halt.is_set():
164 pid_before = child()
165 start = time.monotonic_ns()
166 status, _ = request()
167 finished = time.monotonic_ns()
168 pid_after = child()
169 # Discard generation attribution when a restart crossed the request.
170 generation = pid_after if pid_before == pid_after else None
171 samples.append((start, finished, status, generation))
172 time.sleep(.01)
173 sampler = threading.Thread(target=sample)
174 sampler.start()
175 gaps = []
176 try:
177 for i in range(5):
178 rid = RID + str(i)
179 subprocess.run(['git', 'clone', '-q', '--bare', '--no-hardlinks', str(T/'source'),
180 str(H/'.radicle/storage'/rid)], check=True)
181 old = child()
182 index = len(samples)
183 atomic(RIDS, RIDS.read_bytes() + f'| sandbox{i} | rad:{rid} | main | - | - | - |\n'.encode())
184 until(lambda: child() not in (None, old) and request(f'/drakestapleton/sandbox{i}')[0] == 200)
185 new = child()
186 until(lambda: any(s[2] == 200 and s[3] == new for s in samples[index:]))
187 segment = samples[index:]
188 first = next(s for s in segment if s[2] == 200 and s[3] == new)
189 previous = [s for s in samples if s[2] == 200 and s[3] == old and s[1] < first[0]]
190 assert previous
191 last = previous[-1]
192 gaps.append(dict(restart=i+1, old_pid=old, new_pid=new, last_good_ns=last[1],
193 first_good_ns=first[1], gap_ns=first[1]-last[1]))
194 print('PASS new repository after automatic restart', i+1, 'gap_ns=', gaps[-1]['gap_ns'])
195 finally:
196 halt.set()
197 sampler.join()
198 (T/'restarts.json').write_text(json.dumps(dict(mirror_interval_seconds=INTERVAL,
199 metadata_refresh_ns=elapsed, polling_seconds=.01, gaps=gaps, samples=samples), indent=2)+'\n')
200 text = (H/'forge-data/logs/forged.log').read_text()
201 assert text.count('allowed repository set changed; restarting child') == 5
202 assert 'crash loop' not in text
203 print('PASS exactly five reason lines; no crash backoff')
204finally:
205 proc.terminate()
206 try:
207 proc.wait(timeout=10)
208 except subprocess.TimeoutExpired:
209 os.killpg(proc.pid, signal.SIGKILL)
210 proc.wait()
211 log.close()