Files
nvdriver/tools/ioctl_capture/replay_diff.py
LIghtJUNction ac4c31c12d tools: ioctl capture/replay workflow with normalized 620.73.04 golden transcripts (#120)
LD_PRELOAD ioctl recorder, replay_diff.py, capture_stock.sh, replay_live.sh,
golden stock 620.73.04 transcript + known-gaps, and an offline control test.
Stock swap is opt-in via NV_RS_CAPTURE_BDF. No HANDOFF.md/AGENTS.md changes.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-12-01 13:06:44 -05:00

138 lines
5.0 KiB
Python

#!/usr/bin/env python3
"""Normalise, summarise and diff NVIDIA ioctl captures made by nv_ioctl_capture.so.
replay_diff.py golden RAW.jsonl [RAW2.jsonl ...] -o captures/golden/stock-620.73.04.json
Reduce raw captures of the stock driver to a handle-free, committed golden transcript.
replay_diff.py diff GOLDEN.json CANDIDATE.jsonl [--baseline captures/baseline-ours.json] [--update-baseline]
Compare a candidate capture (nvidia_rs) with the golden transcript, per workload step.
Exit 1 on a divergence that is not in the baseline (regression gate).
A step is (kind, key, status): RM_CONTROL keyed by command and params size, RM_ALLOC by class
and params size, RM_FREE, and every other ioctl keyed by node kind and request number.
Opaque handles, addresses and pids are never compared.
"""
import argparse
import difflib
import json
import struct
import sys
NODE = {
"nvidiactl": "ctl", "nvidia-rs-rmapi-ctl": "ctl",
"nvidia0": "gpu", "nvidia-rs-rmapi-gpu0": "gpu",
"nvidia-uvm": "uvm", "nvidia-rs-uvm": "uvm",
"nvidia-uvm-tools": "uvmtools",
}
def node_kind(dev):
return NODE.get(dev.rsplit("/", 1)[-1], dev.rsplit("/", 1)[-1])
def u32(b, off):
return struct.unpack_from("<I", b, off)[0] if len(b) >= off + 4 else None
def step_of(rec):
top = bytes.fromhex(rec["out"])
nr = int(rec["nr"], 16)
kind = node_kind(rec["dev"])
if rec["rc"] < 0:
return {"kind": "ioctl", "node": kind, "nr": nr, "status": f"errno{rec['errno']}"}
if kind in ("ctl", "gpu") and int(rec["request"], 16) >> 8 & 0xFF == 0x46:
if nr == 0x2A:
return {"kind": "control", "cmd": u32(top, 8), "size": u32(top, 24), "status": u32(top, 28)}
if nr == 0x2B:
sz_off, st_off = (32, 40) if len(top) >= 48 else (24, 28)
return {"kind": "alloc", "class": u32(top, 12), "size": u32(top, sz_off), "status": u32(top, st_off)}
if nr == 0x29:
return {"kind": "free", "status": u32(top, 12)}
return {"kind": "ioctl", "node": kind, "nr": nr, "status": "ok"}
def key(step):
k = [step["kind"]]
for f in ("node", "nr", "cmd", "class"):
if f in step:
k.append(f"{f}={step[f]:#x}" if isinstance(step[f], int) and f in ("cmd", "class") else f"{f}={step[f]}")
return " ".join(k)
def load_raw(path):
with open(path) as f:
return [step_of(json.loads(line)) for line in f if line.strip()]
def cmd_golden(a):
workloads = {}
for p in a.raw:
name = p.rsplit("/", 1)[-1].removesuffix(".jsonl")
workloads[name] = load_raw(p)
json.dump({"driver": a.driver, "workloads": workloads}, open(a.output, "w"), indent=0)
print(a.output, {k: len(v) for k, v in workloads.items()})
def sig(step):
return key(step) + f" status={step['status']}"
def diff_workload(name, gold, cand):
gk = [key(s) for s in gold]
ck = [key(s) for s in cand]
sm = difflib.SequenceMatcher(None, gk, ck, autojunk=False)
issues = []
for op, g0, g1, c0, c1 in sm.get_opcodes():
if op == "equal":
for gs, cs in zip(gold[g0:g1], cand[c0:c1]):
if gs["status"] != cs["status"] or gs.get("size") != cs.get("size"):
issues.append(f"{name}: {key(gs)}: stock status={gs['status']} size={gs.get('size')} "
f"ours status={cs['status']} size={cs.get('size')}")
else:
for gs in gold[g0:g1]:
issues.append(f"{name}: missing in ours: {sig(gs)}")
for cs in cand[c0:c1]:
issues.append(f"{name}: extra in ours: {sig(cs)}")
return issues
def cmd_diff(a):
golden = json.load(open(a.golden))["workloads"]
name = a.workload
cand = load_raw(a.candidate)
issues = diff_workload(name, golden[name], cand)
baseline = set(json.load(open(a.baseline))) if a.baseline and not a.update_baseline else set()
new = [i for i in issues if i not in baseline]
fixed = baseline - set(issues)
print(f"{name}: stock {len(golden[name])} steps, ours {len(cand)}, divergences {len(issues)} "
f"(new {len(new)}, fixed {len(fixed)})")
for i in new[: a.limit]:
print(" NEW", i)
if a.update_baseline:
json.dump(sorted(issues), open(a.baseline, "w"), indent=0)
print("baseline written", a.baseline)
return 0
return 1 if new else 0
def main():
ap = argparse.ArgumentParser()
sub = ap.add_subparsers(dest="cmd", required=True)
g = sub.add_parser("golden")
g.add_argument("raw", nargs="+")
g.add_argument("-o", "--output", required=True)
g.add_argument("--driver", default="stock 620.73.04 (open modules, kernel 7.3.6, RTX 4060 Laptop)")
g.set_defaults(fn=cmd_golden)
d = sub.add_parser("diff")
d.add_argument("golden")
d.add_argument("workload")
d.add_argument("candidate")
d.add_argument("--baseline")
d.add_argument("--update-baseline", action="store_true")
d.add_argument("--limit", type=int, default=40)
d.set_defaults(fn=cmd_diff)
a = ap.parse_args()
sys.exit(a.fn(a) or 0)
main()