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
import argparse,json,re,sqlite3
from pathlib import Path
from urllib.parse import urlparse
from eval_overlap import coverage as exact_coverage
from eval_observations import qualify
p=argparse.ArgumentParser();p.add_argument('roots',nargs='+',type=Path);p.add_argument('--output',type=Path,required=True);p.add_argument('--external-eval',type=Path);a=p.parse_args()
def metric(s,key):
m=re.search('^'+re.escape(key)+r'\s+(\S+)',s.get('metrics') or '',re.M)
return float(m[1]) if m else None
def cpu(s):
fields=s['cpu'][s['cpu'].rfind(')')+2:].split()
return int(fields[11])+int(fields[12])
def histogram_coverage(rows):
by={r['host']:json.loads(r['overlap']) for r in rows};pilot=by['ws://127.0.0.1:3000'];one=by['bsky.network'];two=by['relay.waow.tech']
triple=pilot[2]
assert triple==one[2]==two[2]
twice=one[1]+two[1]-pilot[1]
assert twice>=0 and twice%2==0
ref_pair_only=twice//2
return {'reference_agreement_dids':triple+ref_pair_only,'pilot_dids_in_reference_agreement':triple,'reference_agreement_coverage':triple/(triple+ref_pair_only)}
assert histogram_coverage([{'host':'ws://127.0.0.1:3000','overlap':'[2,18,17]'}, {'host':'bsky.network','overlap':'[3,20,17]'}, {'host':'relay.waow.tech','overlap':'[5,24,17]'}])['reference_agreement_dids']==30
results=[]
for root in a.roots:
samples=[json.loads(l) for l in (root/'output/samples.jsonl').read_text().splitlines()]
usable=[s for s in samples if metric(s,'relay_seq') is not None]
first,last=usable[0],usable[-1]
state=json.loads((root/'fly-resources.json').read_text());summary=json.loads((root/'output/summary.json').read_text())
snapshot_path=root/'output/index-snapshot.json'
index_snapshot=json.loads(snapshot_path.read_text()) if snapshot_path.exists() else state.get('index_snapshot')
evaluator=a.external_eval or root
eval_log=(evaluator/'output/eval.log').read_text()
reference_errors=[line for line in eval_log.splitlines() if 'error(collector)' in line and 'ws://127.0.0.1:3000' not in line]
rows=[]
with sqlite3.connect(f'file:{evaluator / "output/eval.db"}?mode=ro',uri=True) as db:
db.row_factory=sqlite3.Row
rows=[dict(r) for r in db.execute('select host,events,unique_dids,connected,overlap from relay_stats')]
transport=None
if a.external_eval:
observations=json.loads((evaluator/'output/eval-observations.json').read_text())
pilot=urlparse(state['public_url']).hostname
measured=exact_coverage(observations,['bsky.network','relay.waow.tech'],[pilot])
pilot_result=measured['pilots'][pilot]
coverage={'reference_agreement_dids':measured['reference_intersection_dids'],
'pilot_dids_in_reference_agreement':pilot_result['reference_intersection_seen'],
'reference_agreement_coverage':pilot_result['coverage']}
transport=qualify(observations,[row['host'] for row in observations['collectors']])
else:
coverage=histogram_coverage(rows)
stages={}
for stage in ['frame','validate','index','post_index']:
def delta(key):return metric(last,key)-metric(first,key)
count=delta(f'relay_stage_count{{stage="{stage}"}}');ns=delta(f'relay_stage_ns_total{{stage="{stage}"}}')
stages[stage]={'count':count,'worker_seconds':ns/1e9,'mean_ms':ns/count/1e6 if count else None,'max_ms':metric(last,f'relay_stage_ns_max{{stage="{stage}"}}')/1e6}
authority_seconds=(metric(last,'relay_host_authority_time_us_total')-metric(first,'relay_host_authority_time_us_total'))/1e6
elapsed=last['seconds']-first['seconds']
def counter_delta(start,end,key):
before,after=metric(start,key),metric(end,key)
return None if before is None or after is None else after-before
authority={}
for name,key,scale in [
('checks','relay_host_authority_checks_total',1),
('network_checks','relay_host_authority_network_checks_total',1),
('network_seconds','relay_host_authority_network_time_us_total',1e6),
('pool_wait_seconds','relay_host_authority_pool_wait_us_total',1e6),
('cached_rejections','relay_host_authority_cache_hits_total',1)]:
value=counter_delta(first,last,key)
authority[name]=None if value is None else value/scale
authority['elapsed_seconds']=elapsed
authority['mean_network_concurrency']=None if authority['network_seconds'] is None else authority['network_seconds']/elapsed
authority['mean_workers_waiting_for_slot']=None if authority['pool_wait_seconds'] is None else authority['pool_wait_seconds']/elapsed
points=[]
previous=first
targets=list(range(60,int(last['seconds'])+1,60))
if not targets or last['seconds']-targets[-1]>5:targets.append(last['seconds'])
for end in targets:
s=min(usable,key=lambda s:abs(s['seconds']-end));dt=s['seconds']-previous['seconds']
row={'seconds':s['seconds'],'events_per_second':(s['messages']-previous['messages'])/dt,'relay_cpu_cores':(cpu(s)-cpu(previous))/100/dt,'rss_mib':int(re.search(r'VmRSS:\s+(\d+)',s['status'])[1])/1024,'queued_mib':metric(s,'relay_pool_queued_bytes')/2**20}
if s.get('machineCpu') and previous.get('machineCpu'):
def ticks(x):return list(map(int,x['machineCpu'].splitlines()[0].split()[1:9]))
ds=[e-b for e,b in zip(ticks(s),ticks(previous))];total=sum(ds)
row.update(machine_busy_cores=state['cpus']*(ds[0]+ds[1]+ds[2]+ds[5]+ds[6])/total,steal_pct=100*ds[7]/total,iowait_pct=100*ds[4]/total)
for name,key in [('authority_network_concurrency','relay_host_authority_network_time_us_total'),('authority_wait_workers','relay_host_authority_pool_wait_us_total')]:
value=counter_delta(previous,s,key)
row[name]=None if value is None else value/1e6/dt
count=counter_delta(previous,s,'relay_stage_count{stage="index"}')
ns=counter_delta(previous,s,'relay_stage_ns_total{stage="index"}')
row['index_mean_ms']=None if not count or ns is None else ns/count/1e6
points.append(row);previous=s
result={'engine':state['engine'],'table_encoding':state.get('table_encoding','legacy'),'cpus':state['cpus'],'index_snapshot':index_snapshot,'reference_collector_errors':reference_errors,'app':state['app'],'cpu_kind':state['cpu_kind'],'memory_mib':state['memory_mib'],'cleanup_verified':state['cleanup_verified'],'summary':summary,'eval':rows,'coverage':coverage,'transport':transport,'stages':stages,'authority_worker_seconds':authority_seconds,'authority':authority,'stage_frame_worker_seconds':stages['frame']['worker_seconds'],'index_worker_share':stages['index']['worker_seconds']/stages['frame']['worker_seconds'],'authority_worker_share':authority_seconds/stages['frame']['worker_seconds'],'metrics_timeouts':sum(s['health']!=200 for s in samples),'minute_points':points,'window_complete':summary['stopped'] in ['duration','steady-consumer-verified'],'tail_queue_max_mib':max(metric(s,'relay_pool_queued_bytes')/2**20 for s in usable if s['seconds']>=max(first['seconds'],last['seconds']-120)),'last_metrics':last['metrics']}
results.append(result)
a.output.write_text(json.dumps(results,indent=2)+'\n')
for r in results:
print(r['engine'], 'events',r['summary']['messages'],'coverage',r['coverage'],'stages',r['stages'],'authority share',r['authority_worker_share'],'tail',r['minute_points'][-1], 'queue max tail',r['tail_queue_max_mib'])