#!/usr/bin/env python3 """Aggregate saved measurements; optional charts require matplotlib.""" import argparse import csv import json import re import statistics from pathlib import Path def aggregate(directory): summary = json.loads((directory / 'summary.json').read_text()) rows = [] for index, run in enumerate(summary['runs'], 1): samples = [json.loads(line) for line in (directory / ('%02d-%s' % (index, run['name'])) / 'samples.jsonl').read_text().splitlines()] cpu = {service: [] for service in ('api', 'postgres', 'lb', 'redis')} memory = {service: [] for service in cpu} connections, locks, io_wait = [], [], [] for sample in samples: totals = {service: 0 for service in cpu} mem_totals = {service: 0 for service in cpu} for item in sample.get('docker_stats', []): for service in cpu: if '-%s-' % service in item['Name']: totals[service] += float(item['CPUPerc'].strip('%')) match = re.match(r'([\d.]+)([A-Za-z]+)', item['MemUsage']) if match: factors = {'B':1/1048576, 'KiB':1/1024, 'MiB':1, 'GiB':1024, 'kB':1000/1048576, 'MB':1000000/1048576, 'GB':1000000000/1048576} mem_totals[service] += float(match[1])*factors.get(match[2],1) if sample.get('docker_stats'): for service in cpu: cpu[service].append(totals[service]) memory[service].append(mem_totals[service]) db = sample.get('postgres_activity', {}) connections.append(db.get('connections', 0)) locks.append(db.get('lock_wait', 0)) io_wait.append(db.get('io_wait', 0)) load = run['load'] row = {key: run.get(key) for key in ('name', 'phase', 'replicas', 'api_total_cpus', 'api_total_memory_mib', 'postgres_cpus', 'pool_max_conns_per_replica', 'commit_delay_us', 'diagnostic_async_commit', 'rate')} row.update(source=str(directory), successful_rps=load['successful_rps_wall'], scheduled_window_rps=load['successful_rps_window'], wall_rps=load['successful_rps_wall'], success_ratio=load['success_ratio'], p50_ms=load['success_latency_ms']['p50'], p95_ms=load['success_latency_ms']['p95'], p99_ms=load['success_latency_ms']['p99'], schedule_p99_ms=load['schedule_lag_ms']['p99'], completed_full_p99_ms=load.get('completed_full_latency_ms',{}).get('p99'), failures=json.dumps(load['failure_counts'], sort_keys=True), messages_added=run['messages_added'], confirmed=load['successful_requests'], samples=len(samples), db_connections_max=max(connections, default=0), lock_wait_max=max(locks, default=0), io_wait_max=max(io_wait, default=0)) for service, values in cpu.items(): row[service + '_cpu_mean_pct'] = round(statistics.mean(values), 2) if values else None row[service + '_cpu_max_pct'] = round(max(values), 2) if values else None row[service + '_memory_max_mib'] = round(max(memory[service]),2) if memory[service] else None diagnostics = directory / ('%02d-%s' % (index, run['name'])) if (diagnostics/'pool-stats.json').exists(): pools=json.loads((diagnostics/'pool-stats.json').read_text()) acquired, wait_ns, canceled, full, points = 0, 0, 0, 0, 0 for values in pools.values(): counters=[value['counters'] for value in values if value.get('counters')] if len(counters)>1: acquired+=counters[-1]['acquire_count']-counters[0]['acquire_count'] wait_ns+=counters[-1]['empty_wait_ns']-counters[0]['empty_wait_ns'] canceled+=counters[-1]['canceled_count']-counters[0]['canceled_count'] full+=sum(value['acquired']==value['max_conns'] for value in counters) points+=len(counters) row['pool_wait_per_acquire_ms']=round(wait_ns/acquired/1e6,3) if acquired else None row['pool_canceled_acquires']=canceled row['pool_full_sample_ratio']=round(full/points,4) if points else None row['pool_sample_points']=points if (diagnostics/'diagnostics-before.json').exists(): before=json.loads((diagnostics/'diagnostics-before.json').read_text()) after=json.loads((diagnostics/'diagnostics-after.json').read_text()) for service in cpu: ids=[key for key,value in before['cgroups'].items() if value['service']==service] row[service+'_throttled_usec']=sum(after['cgroups'][key].get('throttled_usec',0)-before['cgroups'][key].get('throttled_usec',0) for key in ids) for key in ('wal_bytes','wal_buffers_full'): row[key+'_delta']=float(after['wal'][key])-float(before['wal'][key]) for key in ('write_time','fsync_time','writes','fsyncs'): row['wal_'+key+'_delta']=sum(float(x.get(key) or 0) for x in after['wal_io'])-sum(float(x.get(key) or 0) for x in before['wal_io']) rows.append(row) return rows def charts(rows, output): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 10, 'axes.grid': True, 'grid.alpha': .25}) for phase in sorted({row['phase'] for row in rows}): selected = [row for row in rows if row['phase'] == phase] if phase not in ('fixed_pool32', 'resource_growth', 'pool_improvement'): continue group_key = {'fixed_pool32': 'replicas', 'resource_growth': 'api_total_cpus', 'pool_improvement': 'pool_max_conns_per_replica'}[phase] fig, axes = plt.subplots(1, 3, figsize=(13, 3.6)) for group in sorted({str(row[group_key]) for row in selected}): points = sorted([row for row in selected if str(row[group_key]) == group], key=lambda x: x['rate']) label = '%s=%s' % (group_key, group) for ax, metric in zip(axes, ('successful_rps', 'p99_ms', 'success_ratio')): ax.plot([p['rate'] for p in points], [p[metric] for p in points], 'o-', label=label) axes[0].set_ylabel('Successful POST/s') axes[1].set_ylabel('p99 successful requests, ms') axes[2].set_ylabel('Success / scheduled requests') for ax in axes: ax.set_xlabel('Scheduled POST/s') axes[0].legend(fontsize=8) fig.suptitle(phase + ' — 100,000 seed messages; fixed-rate workload') fig.tight_layout() fig.savefig(output / (phase + '.svg')) fig.savefig(output / (phase + '.png'), dpi=150) plt.close(fig) selected = [row for row in rows if row['phase'] == 'wal_ablation'] if selected: fig, axes = plt.subplots(1, 2, figsize=(9, 3.5)) labels = ['ON (before)', 'OFF (diagnostic)', 'ON (after)'] for ax, metric, ylabel in zip(axes, ('successful_rps','pool_wait_per_acquire_ms'), ('Completed POST/s (wall)', 'Pool wait / acquire, ms')): ax.bar(range(len(selected)), [row[metric] for row in selected], color=['#64748b','#b45309','#64748b']) ax.set_xticks(range(len(selected)),labels,rotation=10) ax.set_ylabel(ylabel) fig.suptitle('Causal WAL diagnostic: OFF weakens durability and is not a deployment option') fig.tight_layout() fig.savefig(output/'wal-ablation.png',dpi=150) fig.savefig(output/'wal-ablation.svg') plt.close(fig) selected = [row for row in rows if row['phase'] == 'db_cpu_causal'] if selected: fig, axes = plt.subplots(1, 3, figsize=(13, 4)) labels = ['%d API / PG %s' % (row['replicas'],row['postgres_cpus']) for row in selected] colors = ['#64748b' if row['postgres_cpus']==.5 else '#0f766e' for row in selected] for ax, metric, ylabel in zip(axes, ('successful_rps','postgres_cpu_mean_pct','pool_wait_per_acquire_ms'), ('Completed POST/s (wall)', 'PostgreSQL CPU, 100%=one core', 'Pool wait / acquire, ms')): ax.bar(range(len(selected)), [row[metric] for row in selected], color=colors) ax.set_xticks(range(len(selected)),labels,rotation=40,ha='right') ax.set_ylabel(ylabel) axes[1].plot(range(len(selected)),[row['postgres_cpus']*100 for row in selected], 'k--', label='CPU quota') axes[1].legend() fig.suptitle('Controlled database CPU budget; 2000 scheduled POST/s, fixed total API budget and pool') fig.tight_layout() fig.savefig(output/'db-cpu-causal.png',dpi=150) fig.savefig(output/'db-cpu-causal.svg') plt.close(fig) selected = [row for row in rows if row['phase'] == 'wal_group_commit'] if selected: groups = sorted({row['commit_delay_us'] for row in selected}) fig, axes = plt.subplots(1, 3, figsize=(12, 3.6)) for ax, metric, label in zip(axes, ('successful_rps', 'p99_ms', 'wal_fsyncs_delta'), ('Completed POST/s (wall time)', 'p99 HTTP 201, ms', 'WAL fsync count')): for index, group in enumerate(groups): values = [row[metric] for row in selected if row['commit_delay_us'] == group] ax.bar(index, statistics.median(values), color=('#64748b', '#0f766e')[index % 2], alpha=.65) ax.scatter([index]*len(values), values, color='black', s=25, zorder=3) ax.set_xticks(range(len(groups)), [str(group) + ' us' for group in groups]) ax.set_ylabel(label) fig.suptitle('Group commit: median bars and three raw repeats; 3000 scheduled POST/s') fig.tight_layout() fig.savefig(output / 'group-commit.svg') fig.savefig(output / 'group-commit.png', dpi=150) plt.close(fig) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('directories', nargs='+', type=Path) parser.add_argument('--output', required=True, type=Path) parser.add_argument('--charts', action='store_true') args = parser.parse_args() rows = [row for directory in args.directories for row in aggregate(directory)] args.output.mkdir(parents=True, exist_ok=True) (args.output / 'results.json').write_text(json.dumps(rows, indent=2) + '\n') with (args.output / 'results.csv').open('w', newline='') as stream: writer = csv.DictWriter(stream, fieldnames=list(dict.fromkeys(key for row in rows for key in row))) writer.writeheader() writer.writerows(rows) if args.charts: charts(rows, args.output) for row in rows: print('%-30s %7.1f RPS %6.2f%% p99=%7.1f ms CPU api/pg/lb=%5.1f/%5.1f/%5.1f' % (row['name'], row['successful_rps'], row['success_ratio']*100, row['p99_ms'], row['api_cpu_mean_pct'], row['postgres_cpu_mean_pct'], row['lb_cpu_mean_pct'])) if __name__ == '__main__': main()