#!/usr/bin/env python3 """Export nonsecret measured evidence and figures supporting the 26-thread choice.""" from pathlib import Path import argparse,csv,json,statistics,os,datetime as dt HERE=Path(__file__).resolve().parent p=argparse.ArgumentParser();p.add_argument('--results',type=Path,default=HERE/'results');p.add_argument('--output',type=Path,default=HERE/'evidence/26-thread-choice');a=p.parse_args() a.output.mkdir(parents=True,exist_ok=True);os.environ.setdefault('MPLCONFIGDIR',str(a.results/'.figure-cache')) import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.dates as dates rows=[] for n in [15,20,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,50]: run=2 if n==30 else 1;folder=a.results/f'capacity-shared-{n}-human-delay-run{run}' m=json.loads((folder/'run.json').read_text()) assert m['exit_code']==0 and m['think_min_ms']==500 and m['think_mean_ms']==1000 with (folder/'measured.csv').open() as f:samples=list(csv.DictReader(f)) rows.append({'threads':n,'run':folder.name,'cpu_percent':m['server_metrics']['192.168.1.125 CPU combined']['mean'],'mean_response_ms':statistics.mean(int(r['elapsed']) for r in samples),'requests_per_second':m['measured_http_requests_per_second'],'power_watts':m['power_energy']['average_watts'],'failed_requests':m['measured_failed_http_samples']}) with (a.output/'calibration.csv').open('w') as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows) def cpu_trace(name,filename): folder=a.results/name;m=json.loads((folder/'run.json').read_text()) with (folder/'perfmon.csv').open() as f:trace=[{'timestamp_ms':int(r['timeStamp']),'cpu_percent':float(r['elapsed'])/1000} for r in csv.DictReader(f) if r['label'].endswith(' CPU combined') and r['success']=='true' and m['measurement_start_ms']<=int(r['timeStamp'])=95 for p in selected_trace),'selected_samples_ge98':sum(p['cpu_percent']>=98 for p in selected_trace),'idle_samples':len(idle_trace),'idle_samples_ge5':sum(p['cpu_percent']>=5 for p in idle_trace),'idle_samples_ge10':sum(p['cpu_percent']>=10 for p in idle_trace),'idle_power_watts':idle['power_energy']['average_watts'],'selected_power_watts':selected['power_energy']['average_watts'],'long_run_protocol':{'threads':26,'warmup_seconds':1800,'measurement_seconds':14400,'sampling_interval_ms':1000,'think_min_ms':500,'think_mean_ms':1000,'think_parent_gaussian_sd_ms':250,'think_max_ms':1500,'session_pause_ms':0},'qualification':'Observed idle peak is a planning reserve, not an independently measured incremental disturbance or guaranteed bound.'} (a.output/'evidence-summary.json').write_text(json.dumps(summary,indent=2)) def save(fig,name): fig.savefig(a.output/(name+'.png'),dpi=170);fig.savefig(a.output/(name+'.svg'));plt.close(fig) fig,axes=plt.subplots(1,2,figsize=(13,5),layout='constrained') for ax,xfield,xlabel in [(axes[0],'threads','Concurrent threads'),(axes[1],'cpu_percent','Mean whole-machine CPU utilisation (%)')]: ax.plot([r[xfield] for r in rows],[r['mean_response_ms'] for r in rows],'o-',markersize=4,label='Measured mean response time') choice=next(r for r in rows if r['threads']==26);ax.scatter([choice[xfield]],[choice['mean_response_ms']],s=110,color='#b34416',zorder=4,label='Selected: 26 threads') for n in [26,35,40,50]: r=next(r for r in rows if r['threads']==n);ax.annotate(str(n)+' threads',(r[xfield],r['mean_response_ms']),xytext=(-5,10),textcoords='offset points',ha='right',fontsize=8) ax.set_xlabel(xlabel);ax.set_ylabel('Mean response time (ms)');ax.set_ylim(bottom=0);ax.grid(alpha=.25);ax.legend(loc='upper left',fontsize=8) axes[1].set_xlim(45,100) fig.suptitle('Selected workload is below the observed steep-rise region\nMatched request pacing and shared data; ten-minute calibration trials') save(fig,'mean-response-knee') fig,ax=plt.subplots(figsize=(10,5),layout='constrained') ax.plot([r['threads'] for r in rows],[r['cpu_percent'] for r in rows],'o-',markersize=4,label='Measured mean CPU') ax.axhline(95,color='#ad3828',linestyle='--',label='95% planning limit') ax.axhline(ceiling,color='#86671d',linestyle='--',label=f'Planning ceiling: 95 − {reserve:.3f} = {ceiling:.3f}%') choice=next(r for r in rows if r['threads']==26);ax.scatter([26],[choice['cpu_percent']],s=120,color='#217a52',zorder=4);ax.annotate(f'26 threads: {choice["cpu_percent"]:.1f}%',(26,choice['cpu_percent']),xytext=(-45,-32),textcoords='offset points',arrowprops={'arrowstyle':'->'}) ax.set_xlabel('Concurrent threads');ax.set_ylabel('Mean CPU utilisation (%)');ax.set_ylim(40,102);ax.grid(alpha=.25);ax.legend(loc='lower right',fontsize=8);ax.set_title('Headroom rule applied to average CPU — not a per-second guarantee') save(fig,'cpu-headroom') fig,ax=plt.subplots(figsize=(12,4),layout='constrained') x=[dt.datetime.fromtimestamp(r['timestamp_ms']/1000,dt.timezone.utc) for r in idle_trace] ax.plot(x,[r['cpu_percent'] for r in idle_trace],linewidth=.7) peak=max(idle_trace,key=lambda r:r['cpu_percent']);instant=dt.datetime.fromtimestamp(peak['timestamp_ms']/1000,dt.timezone.utc) ax.annotate(f'Observed maximum: {reserve:.3f}%',(instant,reserve),xytext=(20,-25),textcoords='offset points',arrowprops={'arrowstyle':'->'}) ax.xaxis.set_major_formatter(dates.DateFormatter('%H:%M',tz=dt.timezone.utc));ax.set_xlabel('UTC time on 2026-10-08');ax.set_ylabel('CPU utilisation (%)');ax.set_ylim(0,13);ax.grid(alpha=.25);ax.set_title('Four-hour idle baseline: zero application requests; monitoring active') save(fig,'idle-cpu-spikes') fig,ax=plt.subplots(figsize=(12,4),layout='constrained') x=[(r['timestamp_ms']-selected['measurement_start_ms'])/1000 for r in selected_trace] ax.plot(x,[r['cpu_percent'] for r in selected_trace],linewidth=.8,label='One-second CPU readings') ax.axhline(choice['cpu_percent'],color='#217a52',label=f'Mean: {choice["cpu_percent"]:.1f}%') ax.axhline(95,color='#ad3828',linestyle='--',label='95% reference') ax.set_xlabel('Seconds into the ten-minute measured window');ax.set_ylabel('CPU utilisation (%)');ax.set_ylim(40,102);ax.grid(alpha=.25);ax.legend(loc='lower right',fontsize=8);ax.set_title('26 threads: transient saturation remains possible (25 / 600 samples ≥95%)') save(fig,'selected-cpu-trace') print('Exported four figures, calibration table, CPU traces and evidence summary:',a.output)