Skip to content
TKTail

Purpose-built scripts and the TKTail workflow - the source

scripts/run.py

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

#!/usr/bin/env python3
"""competitive-bench-v1 - the orchestrator: checks, then measures, TKTail and the PowerShell, C# and Python baselines on
the same synthetic logs. It starts each implementation as published (it never changes one) and writes every measurement.

    python scripts/run.py --tktail <TKTail.exe> --data <dataset folder> --out <results folder> [--size 1gb|100mb]
                          [--only <scenario>...] [--skip <implementation>...] [--repetitions 5]

Order of work (docs: methodology/METHODOLOGY.md):
 1. environment - the machine, the runtimes, the TKTail exe (version, SHA-256); never a computer or user name.
 2. datasets   - each log's SHA-256 against the expected manifest datasets/generate.py wrote with it.
 3. build      - the C# baseline (dotnet build -c Release).
 4. correctness - every implementation x scenario once, compared with the generator's ground truth; a wrong answer is
                  FAILED CORRECTNESS and is never timed.
 5. cold       - one process per run (start, read, answer, exit); TKTail: start the window with the file, ask over MCP,
                  exit. A warm-up run first (not counted), then N runs, the implementations' order rotated every run.
 6. warm       - the same question repeated in one running process (TKTail: the file open and indexed, one MCP session).
 7. payload    - what an AI client receives: counts, projected result pages, the aggregation (TKTail over MCP).
 8. session    - an investigation: five questions one after another.
Results: <out>/<UTC time>-competitive-bench-v1/ - environment.json, correctness.json, raw.jsonl, summary.json,
summary.csv, summary.md.
"""
import argparse
import datetime
import hashlib
import json
import os
import platform
import shutil
import statistics
import subprocess
import sys
import tempfile
import time

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
sys.path.insert(0, os.path.join(ROOT, 'tktail'))
sys.path.insert(0, HERE)
from scenarios import SCENARIOS, SESSION, expected_of, normalize_script, normalize_tktail  # noqa: E402
from suite_digest import digest as suite_digest  # noqa: E402
from tktail_driver import TKTail, process_cpu_ms, process_peak_ws  # noqa: E402

SUITE_VERSION = 'competitive-bench-v1'
TIMEOUT_S = 1800
SLOW_MS = 60_000           # a run longer than this: 3 measured runs instead of N
IDIOMATIC = {'literal-error', 'elapsed-ge-1000', 'count-5xx', 'top-ip-5xx', 'per-minute-5xx'}
PAYLOAD_SCENARIO = 'top-ip-503-post'


def log(text):
    print(f'{datetime.datetime.now():%H:%M:%S} {text}', flush=True)


def sha256(path):
    h = hashlib.sha256()
    with open(path, 'rb') as f:
        while chunk := f.read(8 << 20):
            h.update(chunk)
    return h.hexdigest()


def capture(cmd):
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=120).stdout.strip()
    except Exception as e:  # a runtime that is not installed is recorded as such
        return f'unavailable: {type(e).__name__}'


# ---------------------------------------------------------------- the implementations

class Implementations:
    def __init__(self, args):
        self.csharp_exe = os.path.join(ROOT, 'csharp', 'bin', 'Release', 'net10.0', 'win-x64', 'CompetitiveBench.exe')
        ps = os.path.join(ROOT, 'powershell')
        self.table = {
            'csharp': {'label': 'C# - .NET 10, Release x64, streaming byte spans (csharp/Program.cs)',
                       'cmd': lambda s, i, r, o: [self.csharp_exe, '--scenario', s, '--input', i, '--repeat', str(r)] + (['--output', o] if o else [])},
            'python': {'label': 'Python - CPython, standard library, streaming (python/bench.py)',
                       'cmd': lambda s, i, r, o: [sys.executable, os.path.join(ROOT, 'python', 'bench.py'), '--scenario', s, '--input', i,
                                                  '--repeat', str(r)] + (['--output', o] if o else [])},
            'pwsh7': {'label': 'PowerShell 7 - optimized streaming (powershell/bench.ps1)',
                      'cmd': lambda s, i, r, o: ['pwsh', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File',
                                                 os.path.join(ps, 'bench.ps1'), '-Scenario', s, '-InputPath', i, '-Repeat', str(r)] + (['-Output', o] if o else [])},
            'ps51': {'label': 'Windows PowerShell 5.1 - optimized streaming (powershell/bench.ps1)',
                     'cmd': lambda s, i, r, o: ['powershell', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File',
                                                os.path.join(ps, 'bench.ps1'), '-Scenario', s, '-InputPath', i, '-Repeat', str(r)] + (['-Output', o] if o else [])},
            'pwsh7-idiomatic': {'label': 'PowerShell 7 - idiomatic pipeline, a convenience baseline (powershell/idiomatic.ps1)',
                                'cmd': lambda s, i, r, o: ['pwsh', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File',
                                                           os.path.join(ps, 'idiomatic.ps1'), '-Scenario', s, '-InputPath', i],
                                'scenarios': IDIOMATIC, 'noRepeat': True},
        }
        for name in args.skip or []:
            self.table.pop(name, None)

    def names(self, scenario):
        return [n for n, v in self.table.items() if scenario in v.get('scenarios', SCENARIOS)]


def run_process(cmd, timeout=TIMEOUT_S):
    """One process to its end: wall, CPU and peak working set measured from outside, its JSON report."""
    started = time.perf_counter()
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    try:
        out, err = p.communicate(timeout=timeout)
    except subprocess.TimeoutExpired:
        p.kill()
        p.communicate()
        return {'status': 'timeout', 'wallMs': timeout * 1000}
    wall = (time.perf_counter() - started) * 1000
    cpu = process_cpu_ms(p._handle)
    peak = process_peak_ws(p._handle)
    if p.returncode != 0:
        return {'status': 'failed', 'error': err.decode('utf-8', 'replace')[-600:], 'wallMs': wall}
    report = json.loads(out.decode('utf-8').strip().splitlines()[-1])
    return {'status': 'ok', 'wallMs': round(wall, 1), 'cpuMs': round(cpu, 1), 'peakWorkingSetBytes': peak, 'report': report}


# ---------------------------------------------------------------- TKTail

def tktail_definition(scenario, path):
    sc = SCENARIOS[scenario]['tktail']
    return dict(sc['definition'], sources=[{'kind': 'source', 'path': path}]), sc.get('aggregate')


class TKTailRuns:
    def __init__(self, exe, work):
        self.exe = exe
        self.work = work
        self.counter = 0

    def instance(self):
        self.counter += 1
        folder = os.path.join(self.work, f'tktail-{self.counter}')
        shutil.rmtree(folder, ignore_errors=True)
        return TKTail(self.exe, folder)

    def cold(self, scenario, path):
        try:
            return self._cold(scenario, path)
        except Exception as e:  # recorded, never a crash of the whole run
            return {'status': 'failed', 'error': f'{type(e).__name__}: {e}'[:600]}

    def _cold(self, scenario, path):
        t = self.instance()
        try:
            definition, aggregate = tktail_definition(scenario, path)
            started = time.perf_counter()
            t.start([path])
            t.wait_source(os.path.basename(path))
            answer, answer_bytes, calls = t.search(definition, aggregate)
            wall = (time.perf_counter() - started) * 1000
            return {'status': 'ok', 'wallMs': round(wall, 1), 'cpuMs': round(t.cpu_ms(), 1), 'peakWorkingSetBytes': t.peak_ws(),
                    'answerBytes': answer_bytes, 'mcpCalls': calls, 'result': normalize_tktail(scenario, answer)}
        finally:
            t.exit()

    def open_warm(self, paths):
        t = self.instance()
        t.start(paths)
        for p in paths:
            t.wait_source(os.path.basename(p))
        t.wait_idle()  # its own background work on the new files (the line index) has finished
        return t

    @staticmethod
    def warm(t, scenario, path):
        definition, aggregate = tktail_definition(scenario, path)
        cpu = t.cpu_ms()
        started = time.perf_counter()
        try:
            answer, answer_bytes, calls = t.search(definition, aggregate)
        except Exception as e:  # recorded, never a crash of the whole run
            return {'status': 'failed', 'error': f'{type(e).__name__}: {e}'[:600]}
        wall = (time.perf_counter() - started) * 1000
        return {'status': 'ok', 'wallMs': round(wall, 1), 'cpuMs': round(t.cpu_ms() - cpu, 1), 'peakWorkingSetBytes': t.peak_ws(),
                'answerBytes': answer_bytes, 'mcpCalls': calls, 'result': normalize_tktail(scenario, answer)}


# ---------------------------------------------------------------- the run

class Run:
    def __init__(self, args):
        self.args = args
        stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
        self.out = os.path.join(args.out, f'{stamp}-{SUITE_VERSION}')
        os.makedirs(self.out, exist_ok=True)
        self.work = tempfile.mkdtemp(prefix='tktail-bench-', dir=args.work)
        self.impl = Implementations(args)
        self.tk = TKTailRuns(args.tktail, self.work)
        self.raw = open(os.path.join(self.out, 'raw.jsonl'), 'w', encoding='utf-8', newline='\n')
        self.datasets = {}
        self.correct = {}

    def record(self, **row):
        row = {'suite': SUITE_VERSION, 'time': datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds'), **row}
        row.pop('report', None)
        self.raw.write(json.dumps(row) + '\n')
        self.raw.flush()

    def dataset(self, kind):
        return self.datasets[kind]

    # 1. environment
    def environment(self):
        ps = ('$c = Get-CimInstance Win32_Processor | Select-Object -First 1; $o = Get-CimInstance Win32_OperatingSystem; '
              '$d = Get-Partition -DriveLetter (Split-Path -Qualifier $env:BENCH_DATA).TrimEnd(":") | Get-Disk; '
              '$v = Get-Volume -DriveLetter (Split-Path -Qualifier $env:BENCH_DATA).TrimEnd(":"); '
              '$av = (Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntiVirusProduct -ErrorAction SilentlyContinue | ForEach-Object displayName) -join ", "; '
              '[ordered]@{cpu=$c.Name.Trim(); cores=$c.NumberOfCores; logical=$c.NumberOfLogicalProcessors; '
              'ramGB=[math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory/1GB,1); os=$o.Caption; build=$o.BuildNumber; '
              'disk=$d.FriendlyName; bus=[string]$d.BusType; filesystem=$v.FileSystem; antivirus=$av} | ConvertTo-Json -Compress')
        env = dict(os.environ, BENCH_DATA=os.path.abspath(self.args.data))
        machine = json.loads(subprocess.run(['powershell', '-NoProfile', '-Command', ps], capture_output=True, text=True, env=env).stdout)
        version = capture([self.args.tktail, 'version', '-v'])
        source_digest, files = suite_digest()
        info = {
            'suiteVersion': SUITE_VERSION,
            'sourceDigest': source_digest,  # scripts/suite_digest.py: the files that produced this run
            'sourceFiles': len(files),
            'machine': machine,
            'tktail': {'exe': os.path.basename(self.args.tktail), 'sha256': sha256(self.args.tktail), 'bytes': os.path.getsize(self.args.tktail),
                       'version': version.splitlines()},
            'runtimes': {'dotnetSdk': capture(['dotnet', '--version']), 'python': sys.version.split()[0] + ' (' + platform.python_implementation() + ')',
                         'pwsh7': capture(['pwsh', '-NoProfile', '-Command', '$PSVersionTable.PSVersion.ToString()']),
                         'ps51': capture(['powershell', '-NoProfile', '-Command', '$PSVersionTable.PSVersion.ToString()'])},
            'implementations': {k: v['label'] for k, v in self.impl.table.items()},
            'timeoutSeconds': TIMEOUT_S, 'repetitions': self.args.repetitions,
            'fileCache': 'warm: every dataset was read just before the measured runs (a warm-up run); the OS file cache is not cleared',
        }
        with open(os.path.join(self.out, 'environment.json'), 'w', encoding='utf-8', newline='\n') as f:
            json.dump(info, f, indent=1)
        log(f'TKTail {info["tktail"]["version"][0] if info["tktail"]["version"] else "?"} sha256 {info["tktail"]["sha256"][:16]}')
        return info

    # 2. datasets
    def check_datasets(self):
        for kind in ('applog', 'iis'):
            name = f'{kind}-{self.args.size}'
            path = os.path.join(self.args.data, name + '.log')
            with open(os.path.join(self.args.data, name + '.expected.json'), encoding='utf-8') as f:
                manifest = json.load(f)
            digest = sha256(path)
            if digest != manifest['sha256']:
                raise SystemExit(f'{name}: SHA-256 {digest} is not the generated {manifest["sha256"]} - generate it again')
            self.datasets[kind] = {'name': name, 'path': path, 'bytes': os.path.getsize(path), 'sha256': digest, 'manifest': manifest}
            log(f'{name}: {self.datasets[kind]["bytes"]:,} bytes, sha256 ok')
        payload = os.path.join(self.args.data, 'iis-100mb')
        if os.path.exists(payload + '.log'):
            with open(payload + '.expected.json', encoding='utf-8') as f:
                manifest = json.load(f)
            self.datasets['payload'] = {'name': 'iis-100mb', 'path': payload + '.log', 'bytes': os.path.getsize(payload + '.log'),
                                        'sha256': manifest['sha256'], 'manifest': manifest}

    # 3. build
    def build(self):
        r = subprocess.run(['dotnet', 'build', '-c', 'Release', '-nologo', '-v', 'q'], cwd=os.path.join(ROOT, 'csharp'), capture_output=True, text=True)
        if r.returncode != 0:
            raise SystemExit('the C# baseline did not build:\n' + r.stdout[-2000:])
        log('C# baseline built (Release)')

    def scenarios(self):
        return [s for s in SCENARIOS if not self.args.only or s in self.args.only]

    # 4. correctness
    def correctness(self):
        results = {}
        for scenario in self.scenarios():
            ds = self.dataset(SCENARIOS[scenario]['dataset'])
            want = expected_of(scenario, ds['manifest'])
            row = {}
            for name in ['tktail'] + self.impl.names(scenario):
                if name == 'tktail':
                    r = self.tk.cold(scenario, ds['path'])
                    got = r.get('result')
                else:
                    r = run_process(self.impl.table[name]['cmd'](scenario, ds['path'], 1, None))
                    got = normalize_script(scenario, r['report']['result']) if r['status'] == 'ok' else None
                state = 'TIMEOUT' if r['status'] == 'timeout' else 'FAILED' if r['status'] != 'ok' else 'OK' if got == want else 'FAILED CORRECTNESS'
                row[name] = {'state': state, 'wallMs': r.get('wallMs')}
                if state != 'OK':
                    row[name]['detail'] = r.get('error') or (str(got)[:300] if got is not None else None)
                self.record(phase='correctness', scenario=scenario, dataset=ds['name'], implementation=name, state=state, wallMs=r.get('wallMs'))
                log(f'correctness {scenario:16} {name:16} {state} ({r.get("wallMs", 0) / 1000:.1f} s)')
            results[scenario] = {'dataset': ds['name'], 'task': SCENARIOS[scenario]['task'], 'expected': SCENARIOS[scenario]['expected'],
                                 'implementations': row}
        self.correct = results
        with open(os.path.join(self.out, 'correctness.json'), 'w', encoding='utf-8', newline='\n') as f:
            json.dump(results, f, indent=1)

    def ok(self, scenario, name):
        return self.correct.get(scenario, {}).get('implementations', {}).get(name, {}).get('state') == 'OK'

    def measured_count(self, first_ms):
        return 3 if first_ms and first_ms > SLOW_MS else self.args.repetitions

    # 5. cold
    def cold(self):
        for scenario in self.scenarios():
            ds = self.dataset(SCENARIOS[scenario]['dataset'])
            names = [n for n in ['tktail'] + self.impl.names(scenario) if self.ok(scenario, n)]
            counts = {}
            # Warm-up run (OS file cache, disk) - not counted; its time decides 5 or 3 measured runs.
            for name in names:
                r = self.one_cold(scenario, ds, name)
                counts[name] = self.measured_count(r.get('wallMs'))
            for rep in range(max(counts.values(), default=0)):
                order = names[rep % len(names):] + names[:rep % len(names)]
                for name in order:
                    if rep < counts[name]:
                        r = self.one_cold(scenario, ds, name)
                        self.record(phase='cold', scenario=scenario, dataset=ds['name'], datasetBytes=ds['bytes'], implementation=name, rep=rep, **r)
                log(f'cold {scenario} run {rep + 1}')

    def one_cold(self, scenario, ds, name):
        if name == 'tktail':
            return self.tk.cold(scenario, ds['path'])
        r = run_process(self.impl.table[name]['cmd'](scenario, ds['path'], 1, None))
        if r['status'] == 'ok':
            r['result'] = normalize_script(scenario, r['report']['result'])
        return r

    # 6. warm
    def warm(self):
        scenarios = self.scenarios()
        t = self.tk.open_warm([self.dataset('applog')['path'], self.dataset('iis')['path']])
        try:
            for scenario in scenarios:
                if not self.ok(scenario, 'tktail'):
                    continue
                ds = self.dataset(SCENARIOS[scenario]['dataset'])
                self.tk.warm(t, scenario, ds['path'])  # warm-up
                for rep in range(self.args.repetitions):
                    r = self.tk.warm(t, scenario, ds['path'])
                    self.record(phase='warm', scenario=scenario, dataset=ds['name'], datasetBytes=ds['bytes'], implementation='tktail', rep=rep, **r)
                log(f'warm {scenario} tktail')
        finally:
            t.exit()
        for scenario in scenarios:
            ds = self.dataset(SCENARIOS[scenario]['dataset'])
            for name in self.impl.names(scenario):
                spec = self.impl.table[name]
                if spec.get('noRepeat') or not self.ok(scenario, name):
                    continue
                first = self.correct[scenario]['implementations'][name]['wallMs']
                n = self.measured_count(first)
                r = run_process(spec['cmd'](scenario, ds['path'], n + 1, None))
                if r['status'] != 'ok':
                    self.record(phase='warm', scenario=scenario, dataset=ds['name'], implementation=name, status=r['status'])
                    continue
                runs = r['report']['runsMs'][1:]  # the first repetition warms the JIT / interpreter
                for rep, ms in enumerate(runs):
                    self.record(phase='warm', scenario=scenario, dataset=ds['name'], datasetBytes=ds['bytes'], implementation=name, rep=rep,
                                status='ok', wallMs=ms, cpuMs=round(r['report']['cpuMs'] / (n + 1), 1),
                                peakWorkingSetBytes=r['report']['peakWorkingSetBytes'])
                log(f'warm {scenario} {name}')

    # 7. payload: what an AI client receives for "the top 10 clients of 503 POST requests"
    def payload(self):
        ds = self.datasets.get('payload')
        if not ds or PAYLOAD_SCENARIO not in SCENARIOS:
            return
        exp = ds['manifest']['expected']
        t = self.tk.open_warm([ds['path']])
        out = {'dataset': ds['name'], 'matches': exp['count503Post']}
        try:
            definition, aggregate = tktail_definition(PAYLOAD_SCENARIO, ds['path'])
            # (a) the count
            started = time.perf_counter()
            answer, size, calls = t.search(definition)
            out['countOnly'] = {'answerBytes': size, 'mcpCalls': calls, 'wallMs': round((time.perf_counter() - started) * 1000, 1)}
            # (b) TKTail aggregates
            started = time.perf_counter()
            answer, size, calls = t.search(definition, aggregate)
            out['aggregation'] = {'answerBytes': size, 'mcpCalls': calls, 'wallMs': round((time.perf_counter() - started) * 1000, 1),
                                  'correct': normalize_tktail(PAYLOAD_SCENARIO, answer) == expected_of(PAYLOAD_SCENARIO, ds['manifest'])}
            def pages_of(extra):
                answer, size, calls = t.search(definition)
                pages, offset, total = [], 0, size
                while True:
                    page, b, _ = t.mcp.tool('tktail_get_search_results', {'searchId': answer['searchId'], 'offset': offset, 'maxResults': 100, **extra})
                    pages.append(page)
                    total += b
                    calls += 1
                    if not page.get('hasMore'):
                        return pages, total, calls
                    offset = page['nextOffset']

            def count_client_side(doc, received, calls, started):
                # The AI client saves what it received and runs a script that counts the clients itself.
                saved = os.path.join(self.work, 'saved.json')
                with open(saved, 'w', encoding='utf-8') as f:
                    json.dump(doc, f)
                started_script = time.perf_counter()
                r = subprocess.run([sys.executable, os.path.join(HERE, 'top_from_pages.py'), saved], capture_output=True, text=True)
                script_ms = (time.perf_counter() - started_script) * 1000
                top = json.loads(r.stdout)['top'] if r.returncode == 0 else None
                return {'answerBytes': received, 'mcpCalls': calls, 'intermediateBytes': os.path.getsize(saved), 'processLaunches': 1,
                        'scriptMs': round(script_ms, 1), 'wallMs': round((time.perf_counter() - started) * 1000, 1),
                        'correct': top == exp['top10ClientIp503Post']}

            # A. every record read whole (what 1.0.2 offered: result pages, whose first fields do not include c-ip, then
            #    each record by its evidenceRef), counted client-side
            started = time.perf_counter()
            pages, received, calls = pages_of({})
            records = []
            for page in pages:
                for result in page['results']:
                    rec, b, _ = t.mcp.tool('tktail_get_record', {'evidenceRef': result['evidenceRef'], 'maxTextBytes': 0, 'maxFields': 64})
                    records.append(rec)
                    received += b
                    calls += 1
            out['fullRecords'] = count_client_side({'kind': 'records', 'records': records}, received, calls, started)
            # B. projected result pages (fields: c-ip, no preview), counted client-side
            started = time.perf_counter()
            pages, received, calls = pages_of({'fields': ['c-ip'], 'preview': False})
            out['projectedPages'] = count_client_side({'kind': 'projectedPages', 'pages': pages}, received, calls, started)
            out['projectedPages']['results'] = sum(len(p['results']) for p in pages)
            # C. TKTail aggregates (above): no client-side step
            out['aggregation'].update({'intermediateBytes': 0, 'processLaunches': 0})
        finally:
            t.exit()
        # For comparison: every matching record exported as JSON lines by the baselines (all 16 fields / 3 fields).
        for name in ('csharp', 'python'):
            if name not in self.impl.table:
                continue
            for variant in ('full', 'projected'):
                target = os.path.join(self.work, f'records-{name}-{variant}.jsonl')
                r = run_process(self.impl.table[name]['cmd'](f'records-503-post-{variant}', ds['path'], 1, target))
                if r['status'] == 'ok':
                    out.setdefault('scriptExports', {})[f'{name}-{variant}'] = {'bytes': r['report']['result']['bytes'],
                                                                                 'records': r['report']['result']['count']}
        self.record(phase='payload', **out)
        with open(os.path.join(self.out, 'payload.json'), 'w', encoding='utf-8', newline='\n') as f:
            json.dump(out, f, indent=1)
        log(f'payload: count {out["countOnly"]["answerBytes"]} B, aggregation {out["aggregation"]["answerBytes"]} B, '
            f'projected pages {out["projectedPages"]["answerBytes"]} B, full records {out["fullRecords"]["answerBytes"]} B')

    # 8. session: five questions of one incident, one after another
    def session(self, sessions=3):
        ds = self.dataset('iis')
        for s in range(sessions):
            # TKTail, warm: the window has the log open (the user is investigating) - one MCP session.
            t = self.tk.open_warm([ds['path']])
            try:
                total = 0
                for scenario in SESSION:
                    r = self.tk.warm(t, scenario, ds['path'])
                    total += r.get('wallMs', 0)
                    self.record(phase='session', session=s, scenario=scenario, dataset=ds['name'], implementation='tktail', mode='warm', **r)
                self.record(phase='session-total', session=s, dataset=ds['name'], implementation='tktail', mode='warm', wallMs=round(total, 1),
                            peakWorkingSetBytes=t.peak_ws())
            finally:
                t.exit()
            # The baselines: one script run per question (as an investigation runs them).
            names = [n for n in self.impl.names('count-5xx') if all(self.ok(q, n) for q in SESSION) and not self.impl.table[n].get('noRepeat')]
            order = names[s % len(names):] + names[:s % len(names)] if names else []
            for name in order:
                total, peak = 0, 0
                for scenario in SESSION:
                    r = run_process(self.impl.table[name]['cmd'](scenario, ds['path'], 1, None))
                    total += r.get('wallMs', 0)
                    peak = max(peak, r.get('peakWorkingSetBytes') or 0)
                    self.record(phase='session', session=s, scenario=scenario, dataset=ds['name'], implementation=name, mode='cold', **r)
                self.record(phase='session-total', session=s, dataset=ds['name'], implementation=name, mode='cold', wallMs=round(total, 1),
                            peakWorkingSetBytes=peak)
            log(f'session {s + 1}')

    def close(self):
        self.raw.close()
        shutil.rmtree(self.work, ignore_errors=True)


def main():
    ap = argparse.ArgumentParser(description='competitive-bench-v1 orchestrator')
    ap.add_argument('--tktail', required=True, help='the TKTail.exe to measure (a copy of it runs; never your own TKTail)')
    ap.add_argument('--data', required=True, help='the folder generate.py wrote the datasets to')
    ap.add_argument('--out', required=True, help='results are written to a new folder below this one')
    ap.add_argument('--work', default=None, help='scratch folder for TKTail copies and exports (default: the system temp folder)')
    ap.add_argument('--size', default='1gb', choices=['100mb', '1gb'])
    ap.add_argument('--only', nargs='*')
    ap.add_argument('--skip', nargs='*', help='implementations to leave out (e.g. ps51)')
    ap.add_argument('--repetitions', type=int, default=5)
    ap.add_argument('--phases', nargs='*', default=['correctness', 'cold', 'warm', 'payload', 'session'])
    args = ap.parse_args()
    run = Run(args)
    try:
        run.environment()
        run.check_datasets()
        run.build()
        run.correctness()
        if 'cold' in args.phases:
            run.cold()
        if 'warm' in args.phases:
            run.warm()
        if 'payload' in args.phases:
            run.payload()
        if 'session' in args.phases:
            run.session()
    finally:
        run.close()
    subprocess.run([sys.executable, os.path.join(HERE, 'summarize.py'), run.out])
    log(f'results: {run.out}')


if __name__ == '__main__':
    main()