import json, os, subprocess, sys

def read(name):
    return open('/proc/self/' + name).read().strip()

def allocate(mib):
    data = bytearray(mib * 1024 * 1024)
    for i in range(0, len(data), 4096): data[i] = 1
    return data

def sample(label):
    status = read('status')
    rss = next(line.split(':')[1].strip() for line in status.splitlines() if line.startswith('VmRSS:'))
    return dict(role=label, oom_score_adj=int(read('oom_score_adj')), oom_score=int(read('oom_score')), rss=rss, cgroup=read('cgroup'))

if len(sys.argv) > 1 and sys.argv[1] == 'job':
    data = allocate(3072)
    print(json.dumps(sample('detached job (3072 MiB touched)')), flush=True)
    input()
else:
    print('Original reproduction:', flush=True)
    subprocess.run(['sh', '-c', "echo self=$(cat /proc/self/oom_score_adj); systemd-run --user --wait --pipe --quiet sh -c 'echo detached=$(cat /proc/self/oom_score_adj); cat /proc/self/cgroup'"], check=True)
    available = int(next(l.split()[1] for l in open('/proc/meminfo') if l.startswith('MemAvailable:')))
    if available < 6 * 1024 * 1024: raise RuntimeError('Less than 6 GiB available; refusing allocation')
    data = allocate(70)
    job = subprocess.Popen(['systemd-run', '--user', '--wait', '--pipe', '--quiet', '--collect', sys.executable, os.path.abspath(__file__), 'job'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
    try:
        line = job.stdout.readline()
        if not line: raise RuntimeError('Detached job did not report')
        detached = json.loads(line)
        agent = sample('agent tool (70 MiB touched)')
        print(json.dumps(agent), flush=True)
        print(json.dumps(detached), flush=True)
        print('Higher kernel oom_score: ' + ('AGENT TOOL' if agent['oom_score'] > detached['oom_score'] else 'DETACHED JOB'), flush=True)
        print('No OOM was triggered. These are live kernel scores, not simulated kills.', flush=True)
    finally:
        job.stdin.write('done\n'); job.stdin.flush(); job.communicate(timeout=20)
        if job.returncode: raise RuntimeError('Detached job failed: ' + str(job.returncode))
