luoke-bench / scan /make_sets.py
jason926's picture
luoke-bench (4745f55dec)
e39a6b5
Raw History Blame Contribute Delete
7.37 kB
#!/usr/bin/env python3
"""Make the question sets of scan/: how close a model's judgement comes to luoke-scan's rules.
python3 scan/make_sets.py --scan <luoke-scan checkout, or a built luoke-scan> --seed 1 --out scan/sets/
[--scan-commit <commit>] needed when --scan is not a git checkout
[--set posture,process] which sets (default: all there are)
[--work <dir>] [--keep] where the fake Macs are built (default: a temporary folder); --keep leaves them there
Each question is a fake Mac: a folder (home/, tmp/, ...) and a fakes.json that says what the Mac's own state is
(processes, the answers of system commands), the layout luoke-scan's `--fixture` mode reads. luoke-scan looks at it
with its clock stopped (`scan --fixture <dir> --clock <time> --json`), each question in a folder of its own, and what
its rules find is the answer. The same facts are written out as text for the model, with nothing of what the rules
said. So the answers are never written by hand: they are whatever the rules of the recorded commit say.
Only macOS: the rules read the real file system (does a process's program still exist), and the processes of "this
user" are the ones with the uid that runs this script. Stdlib only; nothing is imported from luoke-scan.
"""
from __future__ import annotations
import argparse
import json
import os
import platform
import random
import shutil
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from fakemac import T0, Fixture, iso # noqa: E402
VERSION = 1
USERS = ["linwei", "meilin", "haoran", "yuki", "tomas", "anika", "soren", "dalia", "ruben", "ines"]
class Scanner:
"""The luoke-scan whose rules give the answers."""
def __init__(self, path: str, commit: str | None, work: str):
self.work = work
if os.path.isdir(path):
got = subprocess.run(["git", "-C", path, "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip()
dirty = subprocess.run(["git", "-C", path, "status", "--porcelain", "--untracked-files=no"], capture_output=True, text=True).stdout.strip()
if got and dirty:
raise SystemExit(f"{path} has uncommitted changes: the answers would not be those of a commit")
commit = commit or got
self.binary = os.path.join(work, "luoke-scan")
subprocess.run(["go", "build", "-o", self.binary, "./cmd/luoke-scan"], cwd=path, check=True)
else:
self.binary = os.path.abspath(path)
if not commit:
raise SystemExit("--scan is not a git checkout: say which commit it is with --scan-commit")
self.commit = commit
self.home = os.path.join(work, "not-home") # what the scanner gets for HOME: an empty folder, never the real one
os.makedirs(self.home, exist_ok=True)
self.env = {"PATH": "/usr/bin:/bin:/usr/sbin:/sbin", "TZ": "Asia/Shanghai", "HOME": self.home}
self.version = subprocess.run([self.binary, "version"], env=self.env, capture_output=True, text=True, check=True).stdout.strip()
def scan(self, fx: Fixture) -> dict:
r = subprocess.run([self.binary, "scan", "--fixture", fx.root, "--clock", iso(T0), "--json"], env=self.env, cwd=self.work,
capture_output=True, text=True, timeout=600)
if r.returncode != 0:
raise SystemExit(f"luoke-scan left with {r.returncode} on {fx.root}: {r.stderr.strip()[:500]}")
return json.loads(r.stdout)
def make(name: str, scanner: Scanner, seed: int, work: str, keep: bool) -> dict:
import sets_posture
import sets_process
maker = {"posture": sets_posture, "process": sets_process}[name]
rng = random.Random(f"{name}:{seed}") # a str seed: the same on every Python
items, surprises, ignored, skipped = [], [], set(), set()
recipes = maker.recipes(rng)
for n, recipe in enumerate(recipes, 1):
ident = f"{name}-{n:03d}"
fx = Fixture(os.path.join(work, ident), rng.choice(USERS), rng)
made = maker.build(fx, recipe, rng)
fx.save()
report = scanner.scan(fx)
answer, others = maker.answer(fx, report, made)
ignored |= others
for s in report.get("skipped") or []:
skipped.add(s.get("rule", "?"))
if s.get("rule") in maker.RULES:
raise SystemExit(f"{ident}: the rule {s['rule']} did not run ({s.get('reason')}); there is no answer to record")
item = {"id": ident, "group": recipe["group"], "facts": fx.shown(made["facts"]), "answer": answer,
"planted": recipe["plant"], "near": recipe["near"]}
if made.get("boundary"):
item["boundary"] = sorted(made["boundary"])
got, meant = sorted({a["kind"] for a in answer}), sorted(set(made["expected"]))
if got != meant:
surprises.append({"id": ident, "planted": recipe["plant"], "near": recipe["near"], "meant": meant, "rules": got})
items.append(item)
if not keep:
shutil.rmtree(fx.root)
print(f"{ident} {recipe['group']:7s} {','.join(got) or '-'}", flush=True)
return {"set": name, "version": VERSION, "seed": seed, "clock": iso(T0),
"scan": {"commit": scanner.commit, "version": scanner.version},
"made_on": {"macos": platform.mac_ver()[0]},
"kinds": maker.KINDS, "rules": sorted(maker.RULES),
"other_rules_seen": sorted(ignored), "rules_skipped": sorted(skipped),
"surprises": surprises, "items": items}
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--scan", required=True, help="a luoke-scan checkout (built here with go) or a built luoke-scan")
ap.add_argument("--scan-commit", default=None, help="the commit of --scan when it is not a git checkout")
ap.add_argument("--seed", type=int, required=True)
ap.add_argument("--out", default=os.path.join(HERE, "sets"))
ap.add_argument("--set", default="posture,process")
ap.add_argument("--work", default=None)
ap.add_argument("--keep", action="store_true")
a = ap.parse_args()
if sys.platform != "darwin":
raise SystemExit("only on macOS: the rules read the Mac's own file system")
work = os.path.realpath(a.work) if a.work else tempfile.mkdtemp(prefix="luoke-bench-scan-")
os.makedirs(work, exist_ok=True)
scanner = Scanner(a.scan, a.scan_commit, work)
os.makedirs(a.out, exist_ok=True)
for name in a.set.split(","):
made = make(name, scanner, a.seed, work, a.keep)
path = os.path.join(a.out, name + ".json")
with open(path, "w", encoding="utf-8") as f:
json.dump(made, f, ensure_ascii=False, indent=1)
f.write("\n")
n = sum(1 for i in made["items"] if i["answer"])
print(f"{path}: {len(made['items'])} questions, {n} with something to report, {len(made['surprises'])} where the rules "
f"said something else than the question was built for", flush=True)
for s in made["surprises"]:
print(" ", json.dumps(s, ensure_ascii=False), flush=True)
if not a.work and not a.keep:
shutil.rmtree(work, ignore_errors=True)
if __name__ == "__main__":
main()