Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/heimdall

runtime/graph-events/benchmark-idle.py

#!/usr/bin/env python3
# SPDX-License-Identifier: AGPL-3.0-only
"""Paired cost with the follower attached to a different, empty cgroup."""
import hashlib
import json
import os
from pathlib import Path
import platform
import statistics
import subprocess
import time

assert os.environ.get('HEIMDALL_TEST_VM') == '1', 'disposable VM only'
out = Path('cost')
out.mkdir(exist_ok=False)
cpu = min(os.sched_getaffinity(0))
os.sched_setaffinity(0, {cpu})
env = dict(os.environ, HEIMDALL_FIXTURE_CGROUP='1')
env.pop('HEIMDALL_FIXTURE_WRONG_CGROUP', None)
graph_pin = '2ede0b97d80e5a0f93b6c18c1678cbbbba07752cb24940bbc7078ee640d14f7e'
binary_pin = 'd97d86d81f93be0ea941b46741c76698123c6452bec21bec0bcd82e1ab69f8ac'
common = ['./object.bpf', './abcdf.exec.nodes.arrow', './abcdf.exec.edges.arrow', graph_pin, './abcdf', binary_pin]
args = ['round'] * 20000
audit = out / 'audit.json'
subprocess.run(['./gate', '--fixture-audit', *common, str(audit), *args], env=env, check=True, timeout=120)
r = json.loads(audit.read_text())
assert r['complete'] and r['decisions'] > 0 and r['violations'] == 0
assert r['cgroup_id'] == r['selected_cgroup_id'] and r['cgroup_id'] > 0
counts = dict(r['counts'])
assert all(counts[nr] == 20003 for nr in [108, 102, 104])
calls = sum(counts.values())
assert calls > 60000
# Both timed variants create the same two cgroups and use the same static floor
# and clone guard. Only the idle variant loads and attaches the follower.
env['HEIMDALL_FIXTURE_WRONG_CGROUP'] = '1'
samples = []
floor = None
for index in range(32):
    order = ['static', 'idle'] if index % 2 == 0 else ['idle', 'static']
    pair = dict(order=order)
    for mode in order:
        report = out / f'{index:02}-{mode}.json'
        command = ['./gate', '--fixture-' + ('static' if mode == 'static' else 'enforce'),
                   *common, str(report), str(audit), *args]
        result = subprocess.run(command, env=env, timeout=120, capture_output=True, text=True)
        (out / f'{index:02}-{mode}.stdout').write_text(result.stdout)
        (out / f'{index:02}-{mode}.stderr').write_text(result.stderr)
        value = json.loads(report.read_text())
        assert value['process_exit'] == 0 and value['process_signal'] is None and value['kills'] == 0, value
        assert value['cgroup_id'] > 0 and value['selected_cgroup_id'] > 0
        assert value['cgroup_id'] != value['selected_cgroup_id']
        assert value['observations_enabled'] is False
        assert value['clone_guard_sha256'] == r['clone_guard_sha256']
        assert value['audited_calls'] == calls
        assert value['arguments'] == r['arguments'] and value['environment'] == r['environment']
        assert value['follower_attached'] == (mode == 'idle')
        if mode == 'idle':
            # Zero decisions is the desired exclusion control. The fixture gate
            # correctly refuses to label this an Enforce-complete run.
            assert result.returncode == 1 and value['complete'] is False
            assert value['decisions'] == 0 and value['violations'] == 0
            assert value['first_failure'] is None
            assert 'fixture did not pass; see report' in result.stderr
        else:
            assert result.returncode == 0 and value['complete'] is True
            assert value['decisions'] is None and value['violations'] is None
        if floor is None:
            floor = value['floor_sha256']
        assert value['floor_sha256'] == floor and floor is not None
        pair[mode] = value['elapsed_ns']
    pair['delta_ns_per_audited_call'] = (pair['idle'] - pair['static']) / calls
    if index:
        samples.append(pair)

summary = dict(
    format='heimdall.fixture-idle-cost/1', finished_unix=time.time(),
    kernel=platform.release(), boot_id=Path('/proc/sys/kernel/random/boot_id').read_text().strip(), cpu=cpu,
    cpu_model=next(line.split(':', 1)[1].strip() for line in Path('/proc/cpuinfo').read_text().splitlines() if line.startswith('model name')),
    samples=samples, warmup_pairs=1, audited_calls_per_run=calls,
    median_added_ns_per_audited_call=statistics.median(s['delta_ns_per_audited_call'] for s in samples),
    range_added_ns_per_audited_call=[min(s['delta_ns_per_audited_call'] for s in samples), max(s['delta_ns_per_audited_call'] for s in samples)],
    median_static_elapsed_ns=statistics.median(s['static'] for s in samples),
    median_idle_elapsed_ns=statistics.median(s['idle'] for s in samples),
    graph_sha256=graph_pin, executable_sha256=binary_pin, floor_sha256=floor,
    file_sha256={name: hashlib.sha256(Path(name).read_bytes()).hexdigest() for name in ['gate', 'object.bpf', 'abcdf', 'abcdf.exec.nodes.arrow', 'abcdf.exec.edges.arrow', 'benchmark-idle.py', 'guest-cost.sh']},
    method='One guest CPU, 31 alternating static/idle pairs after one discarded warmup pair. Actual workload cgroup differs from the selected empty cgroup in both variants. Same floor and clone guard. Timer spans detach through child completion and group-empty wait; graph setup and teardown excluded. Idle graph has zero decisions/violations; gate deliberately refuses Enforce-complete status.',
    limits='Fixture estimate for one attached follower on an unselected workload, not general host idle cost or production latency. Denominator comes from a separate selected Audit run and excludes base calls; timed call counts are inferred from the identical fixture. No per-call tracing in timed runs; guest scheduler and cgroup wait remain in the timing. No graph protection is claimed for the unselected workload.')
(out / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n')
print(json.dumps({k: summary[k] for k in ['audited_calls_per_run', 'median_added_ns_per_audited_call', 'range_added_ns_per_audited_call']}, indent=2))