Files
aji/tools/litmus/differential.py
dev 4242132b2a Phase 5: atomics through every layer (RFC 0015)
AIR: linear atomic<T> (AtomicScalar), atomic.new/take/load/store/RMW/
cmpxchg (two results)/fence with explicit orderings; feature atomics
published. Verifier: ordering tables (E4201), ordinary access (E4202),
effects [atomic] / [atomic, atomic.weak], linearity, take while lent
(E4101, also for mutex.take). Interpreter: timestamped message machine
(src/interp/weak.zig); views travel through spawn/join, channels, mutexes,
close and cancel; seq_cst reads the latest message and programs without
weak reads make no extra draw (existing records unchanged). aji explore:
exhaustive exploration that branches only before visible operations.
Litmus: 20/20 tests give exactly the oracle's sets; differential test
(1500 random programs) found no unsound outcome. .aji layer 10, Quick
Reference atomics, source coverage 67/67, audit report atomic_operations.
AIR bundle +5.9 %, QUICK.md +0.5k.
2026-10-06 08:05:01 +03:00

116 lines
4.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Differential soundness test of the interpreter against the oracle
(spec 04 §20.5: for every program, observed ⊆ allowed).
Generates small random litmus programs (2–3 tasks, 1–3 operations each, valid
orderings only), computes the allowed outcomes with the independent oracle
(tools/litmus/enumerate.py) and the interpreter's outcomes with
`aji explore`, and fails if the interpreter produces an outcome the oracle
does not allow. Exact equality is reported, not required: the interpreter is
only required to be complete on the normative corpus.
Usage: python3 tools/litmus/differential.py [--seed N] [--count N] [--aji PATH]
"""
import json
import os
import random
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
sys.path.insert(0, HERE)
import enumerate as oracle # noqa: E402
import to_air # noqa: E402
LOADS = ["rlx", "acq", "sc"]
STORES = ["rlx", "rel", "sc"]
RMWS = ["rlx", "acq", "rel", "ar", "sc"]
FENCES = ["acq", "rel", "ar", "sc"]
CAS = {"rlx": ["rlx"], "acq": ["rlx", "acq"], "rel": ["rlx"], "ar": ["rlx", "acq"], "sc": ["rlx", "acq", "sc"]}
def program(rng, n):
locs = ["x", "y"][: rng.choice([1, 2, 2])]
tasks = []
reg = 0
observe = []
for t in range(rng.choice([2, 2, 3])):
ops = []
for _ in range(rng.randint(1, 3)):
kind = rng.choice(["store", "store", "load", "load", "rmw", "cas", "fence"])
loc = rng.choice(locs)
if kind == "store":
ops.append(f"store {loc} {rng.randint(1, 2)} {rng.choice(STORES)}")
elif kind == "fence":
ops.append(f"fence {rng.choice(FENCES)}")
else:
r = f"r{reg}"
reg += 1
observe.append(f"T{t}.{r}")
if kind == "load":
ops.append(f"{r} = load {loc} {rng.choice(LOADS)}")
elif kind == "rmw":
ops.append(f"{r} = rmw {rng.choice(['add', 'xchg'])} {loc} {rng.randint(1, 2)} {rng.choice(RMWS)}")
else:
s = rng.choice(list(CAS))
ops.append(f"{r} = cas {loc} {rng.randint(0, 2)} {rng.randint(1, 3)} {s} {rng.choice(CAS[s])}")
tasks.append(ops)
# Keep the oracle's brute force small: at most six operations in all and
# four writes per location (it enumerates every modification order).
if sum(len(ops) for ops in tasks) > 6 or any(
sum(1 for ops in tasks for o in ops if (o.startswith(f"store {l}") or f" {l} " in o and ("rmw" in o or "cas" in o))) > 4 for l in locs
):
return program(rng, n)
observe += [f"final {l}" for l in locs]
lines = [f"name: diff{n}", "init: " + " ".join(f"{l}=0" for l in locs)]
for t, ops in enumerate(tasks):
lines.append(f"T{t}:")
lines += [f" {o}" for o in ops]
lines.append("observe: " + " ".join(observe))
return "\n".join(lines) + "\n"
def main(argv):
seed, count = 1, 200
aji = os.path.join(ROOT, "zig-out", "bin", "aji")
while argv:
if argv[0] == "--seed":
seed = int(argv[1])
elif argv[0] == "--count":
count = int(argv[1])
elif argv[0] == "--aji":
aji = argv[1]
else:
raise SystemExit(__doc__)
argv = argv[2:]
rng = random.Random(seed)
unsound = exact = 0
with tempfile.TemporaryDirectory() as tmp:
for n in range(count):
text = program(rng, n)
allowed = {tuple(o) for o in oracle.enumerate_program(oracle.parse(text))[0]}
prog = to_air.parse(text)
air = os.path.join(tmp, f"d{n}.air")
open(air, "w").write(to_air.translate(text))
r = subprocess.run([aji, "explore", "--grant", "heap=mem.alloc:65536", air], capture_output=True, text=True)
res = next((json.loads(l) for l in r.stdout.splitlines() if l.strip().startswith('{"runs"')), None)
if res is None:
print(f"ERROR program {n}:\n{text}{r.stdout[:500]}{r.stderr[:500]}")
return 1
observed = {tuple(o["outcome"]["value"][f"o{i}"] for i in range(len(prog["observe"]))) for o in res["outcomes"]}
if observed - allowed:
unsound += 1
print(f"UNSOUND program {n} (seed {seed}): interpreter produced {sorted(observed - allowed)}\n{text}")
elif observed == allowed and res["complete"]:
exact += 1
print(f"{count} programs: {count - unsound} sound ({exact} exact), {unsound} unsound")
return 1 if unsound else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))