Skip to content

Qwen3-0.6B inference (12 KB), bare-metal bootable OS (22 KB), and from-scratch Mini-GPT trainer with live Braille TUI (32 KB) in 100% pure x86-64 NASM assembly. Zero C, zero libc, zero dependencies.

7.7 KB
Raw Blame
"""Guest-only, isolated cgroup workloads. Both listener endpoints are on loopback."""
import ast
import csv
import errno
import hashlib
import json
import os
import platform
import signal
import socket
import subprocess as sp
import sys
import time
from pathlib import Path

CG = Path("/sys/fs/cgroup/jev/cgroup.procs")
SECRET = Path("/tmp/ebpf-jev-test/dummy_secret.env")
OUT = Path("runs")
MODEL = Path("ml/out/ebpf_jev_model.bin")
MODES = ["noop", "rule_fsm", "oblivious_gbdt", "stateless_mlp", "recurrent_jev"]


def join():
    CG.write_text(str(os.getpid()))


def connect(port):
    with socket.socket() as s:
        s.settimeout(1)
        return s.connect_ex(("127.0.0.1", port))


def workload():
    join()
    print("allowed", os.getpid(), connect(19998), flush=True)
    with SECRET.open("rb") as f:
        assert f.read() == b""
    pid = os.fork()
    if pid == 0:
        e = connect(19999)
        print("denied", os.getpid(), e, flush=True)
        os._exit(int(e != errno.EPERM))
    assert os.waitpid(pid, 0)[1] == 0


def listen(port):
    s = socket.socket()
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(("127.0.0.1", port))
    s.listen()
    s.settimeout(.2)
    return s


def smoke():
    with listen(19998) as benign, listen(19999) as denied:
        capture = sp.Popen(["tcpdump", "-U", "-n", "-i", "lo", "-w", "/tmp/jev.pcap",
                            "tcp and (dst port 19998 or dst port 19999)"],
                           stderr=sp.PIPE, text=True)
        try:
            while True:
                line = capture.stderr.readline()
                if "listening on" in line:
                    break
                if not line:
                    raise RuntimeError("tcpdump failed to start")
            lines = sp.check_output([sys.executable, __file__, "smoke-child"], text=True).splitlines()
            clean, child = [line.split() for line in lines]
            assert clean[2] == "0" and child[2] == str(errno.EPERM), lines
            benign.accept()[0].close()
            try:
                denied.accept()[0].close()
                raise AssertionError("denied connection reached listener")
            except TimeoutError:
                pass
            time.sleep(1.2)
        finally:
            capture.send_signal(signal.SIGINT)
            capture.communicate(timeout=3)
        packets = sp.check_output(["tcpdump","-nn","-r","/tmp/jev.pcap"],text=True,stderr=sp.DEVNULL)
        good = [line for line in packets.splitlines() if " > 127.0.0.1.19998:" in line]
        bad = [line for line in packets.splitlines() if " > 127.0.0.1.19999:" in line]
        assert good and not bad, packets
        return dict(clean_pid=int(clean[1]), child_pid=int(child[1]), allowed_packets=len(good),
                    denied_packets=len(bad), denied_errno=errno.EPERM)


def quantiles(values):
    ordered = sorted(values)
    assert len(ordered) == 10000, len(ordered)
    return {f"p{p}": ordered[len(ordered)*p//100-1] for p in [50,95,99]}


def main():
    sp.run(["cc","-O2","src/latency.c","-o","/tmp/jev-latency"],check=True)
    sp.run(["src/parity_check",MODEL,"ml/out/parity_vectors.json"],check=True)
    aux = Path("ml/out/gbdt_aux_leaves.npy").read_bytes()
    assert aux[:8] == b"\x93NUMPY\x01\x00"
    start = 10 + int.from_bytes(aux[8:10], "little")
    shape = ast.literal_eval(aux[10:start].decode("ascii").strip())
    assert shape == {"descr": "<i2", "fortran_order": False, "shape": (32,16,3)}
    assert len(aux)-start == 32*16*3*2
    Path("/tmp/jev-tree-heads.bin").write_bytes(aux[start:])
    result = dict(kernel=platform.release(), clock="CLOCK_MONOTONIC_RAW", unit="ns",
                  workload="10000 connected UDP connect(127.0.0.1:19998) calls per mode, no sends",
                  timing="hook entry through ring record population, before submission and return; syscall includes clock reads",
                  modes={})
    CG.parent.mkdir(exist_ok=True)
    reference=sp.check_output(["/tmp/jev-latency"],preexec_fn=join,text=True).splitlines()
    result["unattached_syscall_ns"]=quantiles(list(map(int,reference[1:])))
    for index, mode in [(-1, "bare_noop"), *enumerate(MODES)]:
        model = Path("ml/out/stateless_mlp.bin") if index==3 else MODEL
        args = ["src/warden","--mode",str(max(0,index)),"--csv","--weights",model,
                "--protected",SECRET,"--trees","ml/out/ebpf_jev_gbdt.bin","--tree-heads","/tmp/jev-tree-heads.bin"]
        if index==0:
            args.append("--instrument-noop")
        if index==4:
            args += ["--verifier-report",OUT/"verifier_report.txt"]
        with open("/tmp/jev-events.csv","w+") as records, open("/tmp/jev-loader.log","w+") as log:
            p=sp.Popen(args,stdout=records,stderr=log)
            try:
                for _ in range(1200):
                    if "READY" in Path(log.name).read_text():
                        break
                    if p.poll() is not None:
                        raise RuntimeError(Path(log.name).read_text()[-3000:])
                    time.sleep(.05)
                else:
                    raise TimeoutError(mode)
                if index==4:
                    proof=smoke()
                out=sp.check_output(["/tmp/jev-latency"],preexec_fn=join,text=True).splitlines()
                pid,denied=map(int,out[0].split())
                if index==4:
                    variant=bytearray(model.read_bytes())
                    variant[4:8]=(int.from_bytes(variant[4:8],"little")+1).to_bytes(4,"little")
                    Path("/tmp/jev-reload.bin").write_bytes(variant)
                    sp.run(["src/warden","--reload-weights","/tmp/jev-reload.bin"],check=True)
                    with listen(19998):
                        probe=sp.check_output([sys.executable,__file__,"reload-child"],text=True).split()
            finally:
                if p.poll() is None:
                    p.terminate()
                p.wait(timeout=5)
            assert p.returncode==0 and "dropped=0" in Path(log.name).read_text()
            records.seek(0)
            rows=list(csv.reader(records))
        hooks=[int(r[9]) for r in rows if int(r[0])==pid and r[3]=="127"]
        if index==-1:
            assert not hooks and denied==0
            result["bare_noop_syscall_ns"]=quantiles(list(map(int,out[1:])))
            continue
        result["modes"][mode]=dict(n=len(hooks),hook_ns=quantiles(hooks),
                                  syscall_ns=quantiles(list(map(int,out[1:]))),denied=denied,
                                  model_sha256=hashlib.sha256(model.read_bytes()).hexdigest())
        result["modes"][mode]["syscall_percentile_delta_vs_unattached_ns"]={
            k:v-result["unattached_syscall_ns"][k] for k,v in result["modes"][mode]["syscall_ns"].items()}
        if index==4:
            assert probe[1]=="0" and any(r[0]==probe[0] and r[3]=="127" and
                int(r[10])==int.from_bytes(variant[4:8],"little") for r in rows)
            for key in ("clean_pid","child_pid"):
                row=next(r for r in rows if int(r[0])==proof[key] and r[3]=="127")
                proof[key+"_event"]=row
            assert proof["clean_pid_event"][8]=="0"
            child=proof["child_pid_event"]
            assert child[8] in ("1","2") and child[11]=="127" and int(child[9])>0 and int(child[1])==proof["clean_pid"]
            proof["reload_generation"]=int.from_bytes(variant[4:8],"little")
            (OUT/"enforcement_smoke.json").write_text(json.dumps(proof,indent=2)+"\n")
        print(mode,result["modes"][mode],flush=True)
    (OUT/"latency_smoke.json").write_text(json.dumps(result,indent=2)+"\n")


if __name__=="__main__":
    if sys.argv[1:]==["smoke-child"]:
        workload()
    elif sys.argv[1:]==["reload-child"]:
        join()
        print(os.getpid(),connect(19998))
    else:
        main()