1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import argparse
import hashlib
import gzip
import re
import json
import signal
import sqlite3
import subprocess
import tarfile
import uuid
from pathlib import Path
from eval_observations import qualify
parser = argparse.ArgumentParser()
parser.add_argument('--binary', type=Path)
parser.add_argument('--references-only', action='store_true')
parser.add_argument('--eval-pilot', action='append', default=[])
parser.add_argument('--public', action='store_true')
parser.add_argument('--linger', type=int, default=0)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--memory', type=int, choices=[1024, 2048, 4096], default=1024)
parser.add_argument('--seconds', type=int, choices=[45, 120, 600], default=45)
parser.add_argument('--steady', action='store_true')
parser.add_argument('--network-mib', type=int)
parser.add_argument('--eval-binary', type=Path)
parser.add_argument('--engine', choices=['zkv','rocks'], default='zkv')
parser.add_argument('--source', type=Path)
parser.add_argument('--encoding', choices=['legacy', 'grouped'], default='legacy')
parser.add_argument('--cpus', type=int, choices=[1, 2], default=2)
parser.add_argument('--cpu-kind', choices=['shared','performance'], default='shared')
args = parser.parse_args()
if not 0 <= args.linger <= 600:
parser.error('linger must be 0..600 seconds')
if args.references_only and (args.public or args.linger):
parser.error('public ports and linger apply to relay pilots')
if args.eval_pilot and (not args.references_only or any(not re.fullmatch(r'zkv-live-[0-9a-f]{10}\.fly\.dev', host) for host in args.eval_pilot)):
parser.error('eval-pilot must be an isolated zkv-live Fly hostname in reference-only mode')
if args.network_mib is not None and not 512 <= args.network_mib <= 8192:
parser.error('network budget must be 512..8192 MiB')
if args.references_only and (not args.eval_binary or args.steady):
parser.error('reference-only probes need --eval-binary and a fixed window')
if not args.references_only and (not args.binary or not args.binary.is_file() or args.binary.stat().st_size > 32_000_000):
parser.error('provide the existing stripped ZKV relay binary below 32 MB')
args.output.mkdir(parents=True, exist_ok=True)
compressed_binary = args.output / 'zlay.gz'
if not args.references_only:
compressed_binary.write_bytes(gzip.compress(args.binary.read_bytes(), mtime=0))
app = 'zkv-live-' + uuid.uuid4().hex[:10]
state = {'app': app, 'region': 'ord', 'cpu_kind': args.cpu_kind, 'cpus': args.cpus,
'memory_mib': args.memory, 'rootfs_gb': 2, 'volume_created': False,
'machine_lifetime_seconds': 2100 if args.steady else (1500 if args.eval_binary else 900), 'relay_lifetime_seconds': 1800 if args.steady else max(150, args.seconds + 180),
'observe_seconds': 1500 if args.steady else args.seconds, 'steady_mode': args.steady, 'history_enabled': False, 'cleanup_verified': False,
'binary_sha256': None if args.references_only else hashlib.sha256(args.binary.read_bytes()).hexdigest(),
'references_only': args.references_only,
'network_mib': None if args.references_only else args.network_mib or (4096 if args.steady or args.seconds >= 600 else 512)}
source = Path(__file__).resolve().parent
repo = source.parents[1]
if args.references_only:
state['machine_lifetime_seconds'] = max(300, args.seconds + 180)
state['relay_lifetime_seconds'] = 0
state['machine_lifetime_seconds'] += args.linger
state['relay_lifetime_seconds'] += args.linger
state['linger_seconds'] = args.linger
state['public_url'] = f'https://{app}.fly.dev' if args.public else None
state['eval_pilot'] = args.eval_pilot
state['engine'] = None if args.references_only else args.engine
state['table_encoding'] = None if args.references_only else args.encoding
state['index_sync'] = None if args.references_only else True
if args.source: repo = args.source.resolve()
state['source_revision'] = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip()
state['source_files'] = {str(path.relative_to(repo)): hashlib.sha256(path.read_bytes()).hexdigest()
for path in [repo / 'build.zig', repo / 'build.zig.zon', repo / 'src/main.zig', repo / 'src/internal/event_log.zig', repo / 'src/internal/broadcaster.zig']}
def save():
(args.output / 'fly-resources.json').write_text(json.dumps(state, indent=2) + '\n')
def run(command, timeout=60):
try:
result = subprocess.run(command, check=True, capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired as error:
state.setdefault('command_errors', []).append({'command':command[:4], 'timeout_seconds':error.timeout})
save()
raise
except subprocess.CalledProcessError as error:
state.setdefault('command_errors', []).append({'command': command[:4], 'stderr': error.stderr[-8000:]})
save()
raise
return result.stdout
def terminate(signum, frame):
raise KeyboardInterrupt(f'signal {signum}')
signal.signal(signal.SIGTERM, terminate)
save()
attempted = False
try:
attempted = True
print('Creating disposable app ' + app, flush=True)
run(['fly', 'apps', 'create', app, '--org', 'personal', '--yes'])
machine_command = ['fly', 'machine', 'run', 'node:24-bookworm-slim', 'sleep', str(state['machine_lifetime_seconds']),
'-a', app, '-r', 'ord', '--name', 'live-relay', '--vm-cpu-kind', args.cpu_kind,
'--vm-cpus', str(args.cpus), '--vm-memory', str(args.memory), '--rootfs-size', '2',
'--restart', 'no', '--rm', '--detach']
if args.public:
machine_command += ['-p', '443:3000/tcp:tls:http', '--autostart=false']
run(machine_command, timeout=180)
if args.public:
run(['fly', 'ips', 'allocate-v4', '--shared', '-a', app])
run(['fly', 'ips', 'allocate-v6', '-a', app])
state['addresses'] = json.loads(run(['fly', 'ips', 'list', '-a', app, '--json']))
save()
state['machines'] = json.loads(run(['fly', 'machine', 'list', '-a', app, '--json']))
save()
run(['fly', 'ssh', 'console', '-a', app, '-C', 'mkdir -p /tmp/live/output'])
uploads = [(source / 'fly-live-remote.sh', 'run.sh')]
if not args.references_only:
uploads += [(compressed_binary, 'zlay.gz'), (source / 'fly-live-observer.mjs', 'observer.mjs'),
(source / 'fly-index-snapshot.mjs', 'index-snapshot.mjs'), (source / 'fly-steady-window.mjs', 'fly-steady-window.mjs')]
for local, remote in uploads:
run(['fly', 'ssh', 'sftp', 'put', '-a', app, '--mode', '0755', str(local.resolve()), '/tmp/live/' + remote], timeout=240)
if args.eval_binary:
eval_compressed = args.output / 'relay-eval.gz'
eval_compressed.write_bytes(gzip.compress(args.eval_binary.read_bytes(), mtime=0))
run(['fly', 'ssh', 'sftp', 'put', '-a', app, '--mode', '0755', str(eval_compressed.resolve()), '/tmp/live/relay-eval.gz'], timeout=240)
state['eval_sha256'] = hashlib.sha256(args.eval_binary.read_bytes()).hexdigest()
save()
print('Running reference collectors only' if args.references_only else 'Running the full relay with live bootstrap; no history or volume', flush=True)
tail_argument = (",".join(args.eval_pilot) or "none") if args.references_only else str(args.linger)
output = run(['fly', 'ssh', 'console', '-a', app, '-C', f'timeout -k 10 {(1950 if args.steady else max(600, args.seconds + 360)) + args.linger} sh /tmp/live/run.sh {1500 if args.steady else args.seconds} {"references" if args.references_only else "steady" if args.steady else "fixed"} {args.encoding} {state["network_mib"] or 0} {tail_argument}'], timeout=(1970 if args.steady else max(620, args.seconds + 380)) + args.linger)
(args.output / 'remote-console.txt').write_text(output)
state['remote_complete'] = True
save()
finally:
if attempted:
try:
archive = args.output / 'live-results.tar.gz'
run(['fly', 'ssh', 'sftp', 'get', '-a', app, '/tmp/live-results.tar.gz', str(archive.resolve())], timeout=60)
with tarfile.open(archive) as bundle:
bundle.extractall(args.output, filter='data')
state['exported'] = True
except (subprocess.SubprocessError, OSError) as error:
state['export_error'] = type(error).__name__
save()
try:
machines = json.loads(run(['fly', 'machine', 'list', '-a', app, '--json']))
for machine in machines:
run(['fly', 'machine', 'destroy', machine['id'], '-a', app, '--force'])
state['machines_deleted'] = not json.loads(run(['fly', 'machine', 'list', '-a', app, '--json']))
volumes = json.loads(run(['fly', 'volumes', 'list', '-a', app, '--json']))
state['volumes_absent'] = not volumes
assert state['machines_deleted'] and state['volumes_absent']
finally:
for attempt in range(3):
try:
run(['fly', 'apps', 'destroy', app, '--yes'])
break
except subprocess.SubprocessError:
if attempt == 2:
raise
apps = json.loads(run(['fly', 'apps', 'list', '--json']))
state['cleanup_verified'] = not any(item.get('Name', item.get('name')) == app for item in apps)
save()
assert state['cleanup_verified'], 'app remains: ' + app
print('Disposable app deleted and absence verified', flush=True)
if args.eval_binary:
report = json.loads((args.output / 'output/eval-observations.json').read_text())
hosts = ['bsky.network', 'relay.waow.tech']
if not args.references_only:
hosts.insert(0, 'ws://127.0.0.1:3000')
elif args.eval_pilot:
hosts.extend(args.eval_pilot)
state['evaluator_window'] = qualify(report, hosts)
with sqlite3.connect('file:' + str(args.output / 'output/eval.db') + '?mode=ro', uri=True) as db:
db.row_factory = sqlite3.Row
rows = [dict(row) for row in db.execute('SELECT host,events,unique_dids,connected,overlap FROM relay_stats')]
(args.output / 'eval-summary.json').write_text(json.dumps(rows, indent=2) + '\n')
state['eval_verified'] = len(rows) == len(hosts) and all(row['events'] > 0 and row['unique_dids'] > 0 and row['connected'] for row in rows)
save()
if args.references_only:
assert state['eval_verified'] and state['evaluator_window']['valid_window'], 'reference collector window was incomplete or empty'
raise SystemExit(0)
if args.engine == 'zkv':
snapshot = json.loads((args.output / 'output/index-snapshot.json').read_text())
state['index_snapshot'] = snapshot
assert snapshot['sst']['unknown'] == 0, snapshot
other = 'legacy' if args.encoding == 'grouped' else 'grouped'
assert snapshot['sst'][other] == 0, snapshot
if args.seconds >= 600:
assert snapshot['sst'][args.encoding] > 0, 'no table exercised requested encoding'
summary = json.loads((args.output / 'output/summary.json').read_text())
state['window_complete'] = summary['stopped'] == ('steady-consumer-verified' if args.steady else 'duration')
state['traffic_verified'] = summary['opened'] and summary['messages'] > 0
state['live_delivery_checks'] = (summary['malformed'] == 0 and summary['sequenceErrors'] == 0
and summary['sequenceGaps'] == 0 and summary['unexpectedClose'] is None)
if args.seconds >= 600:
state['membership_verified'] = bool(summary['membershipChecks']) and all(row['ok'] for row in summary['membershipChecks'])
save()
assert state['membership_verified'], 'sampled collection membership verification failed'
replay = summary.get('replayResponse')
state['no_history_verified'] = summary['eventHistoryBytes'] == 0 and isinstance(replay, dict) and replay.get('body', {}).get('error') == 'ReplayDisabled'
samples = [json.loads(line) for line in (args.output / 'output/samples.jsonl').read_text().splitlines()]
history = [int(match.group(1)) for sample in samples if (match := re.search(r'^relay_history_entries\s+(\d+)', sample.get('metrics') or '', re.M))]
state['ram_history_disabled'] = bool(history) and not any(history)
save()
if args.steady:
state['steady_verified'] = bool(summary.get('steadyQualified')) and summary.get('sequenceGaps') == 0 and len(summary.get('membershipChecks', [])) > 0 and all(check['ok'] for check in summary['membershipChecks'])
save()
assert state['steady_verified'], 'active steady state and fresh-consumer verification were not established'
assert state['window_complete'], 'observer stopped early: ' + summary['stopped']
assert state['ram_history_disabled'], 'RAM replay history was retained'
assert state['traffic_verified'], 'live relay received no downstream traffic; this is not a capacity result'
assert state['live_delivery_checks'] and state['no_history_verified']
if args.eval_binary:
assert state['eval_verified'] and state['evaluator_window']['valid_window'], 'one or more evaluator collectors lacked a complete window'