Skip to content
TKTail

Purpose-built scripts and the TKTail workflow - the source

scripts/summarize.py

SHA-256 (LF line endings, as in the source ZIP): c95be9a3b998311bf1435c1043cfeb57df1b43ddbb528d2616f8e591208f22e6 · MIT license (the benchmark suite only)

#!/usr/bin/env python3
"""competitive-bench-v1 - summaries of a run, computed from its raw measurements only (raw.jsonl): per phase, scenario and
implementation the median, minimum and maximum time, the spread, throughput, CPU and peak working set; the ratios to
TKTail; the payload and session tables. Never edited by hand - every published number is one of these.

    python summarize.py <results folder>    -> summary.json, summary.csv, summary.md beside raw.jsonl
"""
import csv
import json
import os
import statistics
import sys

MB = 1_000_000


def load(folder):
    rows = []
    with open(os.path.join(folder, 'raw.jsonl'), encoding='utf-8') as f:
        for line in f:
            rows.append(json.loads(line))
    return rows


def stats(rows):
    times = [r['wallMs'] for r in rows if r.get('status') == 'ok']
    if not times:
        return None
    med = statistics.median(times)
    cpu = [r['cpuMs'] for r in rows if r.get('cpuMs') is not None]
    peak = [r['peakWorkingSetBytes'] for r in rows if r.get('peakWorkingSetBytes')]
    size = rows[0].get('datasetBytes')
    return {'runs': len(times), 'medianMs': round(med, 1), 'minMs': round(min(times), 1), 'maxMs': round(max(times), 1),
            'spreadPct': round((max(times) - min(times)) / med * 100, 1) if med else None,
            'throughputMBps': round(size / MB / (med / 1000), 1) if size and med else None,
            'cpuMsMedian': round(statistics.median(cpu), 1) if cpu else None,
            'peakWorkingSetMB': round(max(peak) / 1048576, 1) if peak else None,
            'answerBytesMedian': round(statistics.median([r['answerBytes'] for r in rows if r.get('answerBytes')])) if any(r.get('answerBytes') for r in rows) else None}


def main():
    folder = sys.argv[1]
    rows = load(folder)
    with open(os.path.join(folder, 'environment.json'), encoding='utf-8') as f:
        env = json.load(f)
    correctness = json.load(open(os.path.join(folder, 'correctness.json'), encoding='utf-8')) if os.path.exists(os.path.join(folder, 'correctness.json')) else {}
    groups = {}
    for r in rows:
        if r.get('phase') in ('cold', 'warm'):
            groups.setdefault((r['phase'], r['scenario'], r['implementation']), []).append(r)
    table = []
    for (phase, scenario, impl), rs in sorted(groups.items()):
        s = stats(rs)
        if s:
            table.append({'phase': phase, 'scenario': scenario, 'dataset': rs[0].get('dataset'), 'implementation': impl, **s})
    # Ratios to TKTail of the same phase and scenario: > 1 means the other implementation took longer.
    tk = {(t['phase'], t['scenario']): t for t in table if t['implementation'] == 'tktail'}
    for t in table:
        base = tk.get((t['phase'], t['scenario']))
        if base and t['implementation'] != 'tktail':
            t['timeVsTktail'] = round(t['medianMs'] / base['medianMs'], 2)
            if t.get('peakWorkingSetMB') and base.get('peakWorkingSetMB'):
                t['peakMemoryVsTktail'] = round(t['peakWorkingSetMB'] / base['peakWorkingSetMB'], 2)
    sessions = {}
    for r in rows:
        if r.get('phase') == 'session-total':
            sessions.setdefault((r['implementation'], r.get('mode')), []).append(r)
    session_table = []
    for (impl, mode), rs in sorted(sessions.items()):
        times = [r['wallMs'] for r in rs]
        session_table.append({'implementation': impl, 'mode': mode, 'sessions': len(times), 'medianMs': round(statistics.median(times), 1),
                              'minMs': min(times), 'maxMs': max(times),
                              'peakWorkingSetMB': round(max(r.get('peakWorkingSetBytes') or 0 for r in rs) / 1048576, 1)})
    payload = next((r for r in rows if r.get('phase') == 'payload'), None)
    summary = {'suiteVersion': env.get('suiteVersion'), 'tktail': env.get('tktail'), 'machine': env.get('machine'), 'runtimes': env.get('runtimes'),
               'implementations': env.get('implementations'), 'correctness': correctness, 'measurements': table, 'session': session_table,
               'payload': payload}
    with open(os.path.join(folder, 'summary.json'), 'w', encoding='utf-8', newline='\n') as f:
        json.dump(summary, f, indent=1)
    with open(os.path.join(folder, 'summary.csv'), 'w', encoding='utf-8', newline='') as f:
        fields = ['phase', 'scenario', 'dataset', 'implementation', 'runs', 'medianMs', 'minMs', 'maxMs', 'spreadPct', 'throughputMBps',
                  'cpuMsMedian', 'peakWorkingSetMB', 'answerBytesMedian', 'timeVsTktail', 'peakMemoryVsTktail']
        w = csv.DictWriter(f, fieldnames=fields, extrasaction='ignore')
        w.writeheader()
        w.writerows(table)
    lines = [f'# {env.get("suiteVersion")} - results', '',
             f'TKTail: {" / ".join(env["tktail"]["version"][:2])}, exe SHA-256 {env["tktail"]["sha256"]}', '',
             f'Machine: {env["machine"]["cpu"]} ({env["machine"]["cores"]} cores / {env["machine"]["logical"]} logical), {env["machine"]["ramGB"]} GB RAM, '
             f'{env["machine"]["os"]} build {env["machine"]["build"]}, {env["machine"]["disk"]} ({env["machine"]["bus"]}, {env["machine"]["filesystem"]}), '
             f'security software: {env["machine"]["antivirus"] or "none reported"}', '', '## Correctness', '',
             '| Scenario | Dataset | ' + ' | '.join(sorted({n for c in correctness.values() for n in c['implementations']})) + ' |']
    names = sorted({n for c in correctness.values() for n in c['implementations']})
    lines.append('|---|---|' + '---|' * len(names))
    for scenario, c in correctness.items():
        lines.append(f'| {scenario} | {c["dataset"]} | ' + ' | '.join(c['implementations'].get(n, {}).get('state', '-') for n in names) + ' |')
    for phase in ('cold', 'warm'):
        lines += ['', f'## {phase.capitalize()}', '', '| Scenario | Implementation | Median ms | Min - max ms | MB/s | CPU ms | Peak MB | x TKTail |',
                  '|---|---|---|---|---|---|---|---|']
        for t in (t for t in table if t['phase'] == phase):
            lines.append(f'| {t["scenario"]} | {t["implementation"]} | {t["medianMs"]:,} | {t["minMs"]:,} - {t["maxMs"]:,} | {t["throughputMBps"]} | '
                         f'{t["cpuMsMedian"]} | {t["peakWorkingSetMB"]} | {t.get("timeVsTktail", "")} |')
    if session_table:
        lines += ['', '## Investigation session (5 questions)', '', '| Implementation | Mode | Sessions | Median ms | Min - max ms | Peak MB |', '|---|---|---|---|---|---|']
        for s in session_table:
            lines.append(f'| {s["implementation"]} | {s["mode"]} | {s["sessions"]} | {s["medianMs"]:,} | {s["minMs"]:,} - {s["maxMs"]:,} | {s["peakWorkingSetMB"]} |')
    if payload:
        lines += ['', f'## Payload - the top 10 clients of {payload["matches"]:,} matches ({payload["dataset"]})', '',
                  '| What the AI client receives | Bytes | MCP calls |', '|---|---|---|']
        for key in ('fullRecords', 'projectedPages', 'aggregation', 'countOnly'):
            if key in payload:
                lines.append(f'| {key} | {payload[key]["answerBytes"]:,} | {payload[key]["mcpCalls"]} |')
    with open(os.path.join(folder, 'summary.md'), 'w', encoding='utf-8', newline='\n') as f:
        f.write('\n'.join(lines) + '\n')
    print(f'summary: {len(table)} measurement groups, {len(session_table)} session rows')


if __name__ == '__main__':
    main()