Files
aji/tools/litmus/enumerate.py
T
dev f8d2a99249 P5-1a: independent axiomatic oracle and the litmus corpus (20 tests agree)
tools/litmus/enumerate.py was written by an independent author from spec 04
§20 alone, with the programs blind (outcome sets removed). check.py compares
its allowed sets with tests/litmus/*.lit: 20/20 equal. 21 self-tests derived
from the axioms. Both run in CI. The author's spec findings are Q-024.
2026-10-06 00:40:09 +03:00

611 lines
23 KiB
Python
Raw 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
"""Axiomatic memory-model oracle for Aji litmus tests (spec 04 §20.5).
python3 tools/litmus/enumerate.py FILE.lit...
prints one JSON line per file:
{"file", "name", "observe", "allowed", "executions", "candidates"}
Derived only from spec 04 §20.1-§20.4 (the Aji RC11 profile), §24 and §42.
`allowed:` / `forbidden:` lines of a .lit file are skipped by the parser and
never used.
Method (brute force; the tests are tiny):
1. Events (§20.1). Every location gets an initializing write `init`
(ordering `na`: an ordinary, non-atomic write), first in `mo`. Following
RC11, the init writes are `sb`-before every other event (the litmus format
places `init:` outside the tasks). Each task contributes its operations in
program order (`sb`, §20.2). An RMW (`rmw`, successful `cas`) is two events,
a read part and a write part, related by `rmw` and immediately `sb`-ordered
(§20.2 "rmw relates the read part of each U to its write part"); both parts
carry the RMW's ordering, so the read part is `⊒ acq` iff the ordering is
acquire/acq_rel/seq_cst and the write part `⊒ rel` iff it is
release/acq_rel/seq_cst (§20.2). A failed `cas` is a single read with the
failure ordering (§24.1, §42). Whether each `cas` succeeds is enumerated and
then checked against the value it reads (it succeeds iff the value read
equals EXP).
2. Candidates. For every choice of cas outcomes, every `rf` (each read reads
any write to its location, the init write included), every `mo` (init
first, the other writes in any order) and every admissible total order of
the operations of each mutex and channel (see "Primitives" below). Values
follow from `rf`: a read reads its source's value; an RMW write part writes
f(value read). A candidate whose `sb ∪ rf` is cyclic has no well-defined
values; it is still counted as a candidate and rejected by NO-THIN-AIR. A
candidate whose cas outcome contradicts the value read is not a candidate.
3. Derived relations exactly as §20.2 (fr, eco, rs, sw, hb) and §20.4 (psc),
and the four axioms of §20.4: coherence, atomicity, SC, no-thin-air.
Primitives (§20.3). They are events in `sb` with no location; they take part
in the model only through `sw_prim` and per-object total orders:
- spawn/join: `spawn Tn` → first event of Tn; last event of Tn → `join Tn`
(an empty Tn: `spawn Tn` → `join Tn`). A `(spawned)` task executes only if
some executed task spawns it. No choice is enumerated.
- mutex M: a total order of all `lock M`/`unlock M` events is enumerated. It
must be a lock protocol: lock, unlock by the same task, lock, unlock, ...
(so critical sections do not overlap). `sw_prim`: each unlock → the next
lock in the order.
- channel C: a total order of all `send C`/`recv C` events is enumerated. It
must be a FIFO-queue history with an unbounded buffer: a recv dequeues the
oldest message not yet received and never occurs on an empty queue. So each
recv receives exactly one send and each send is received at most once.
`sw_prim`: send → the recv that receives it.
- "consistent with hb" (§20.3): no `hb` edge between two operations of one
object may point backwards in that object's order. This is checked as a
well-formedness condition next to the four axioms.
Values have no type in the litmus format; RMW arithmetic is modulo 2^64.
"""
import itertools
import json
import re
import sys
from dataclasses import dataclass, field
# --------------------------------------------------------------------------
# Orderings (§24)
ORDS = {'rlx': 'relaxed', 'acq': 'acquire', 'rel': 'release',
'ar': 'acq_rel', 'sc': 'seq_cst'}
REL_ORDS = {'release', 'acq_rel', 'seq_cst'} # E ⊒ rel (§20.2)
ACQ_ORDS = {'acquire', 'acq_rel', 'seq_cst'} # E ⊒ acq (§20.2)
ALLOWED_ORDS = {
'load': {'relaxed', 'acquire', 'seq_cst'},
'store': {'relaxed', 'release', 'seq_cst'},
'rmw': {'relaxed', 'acquire', 'release', 'acq_rel', 'seq_cst'},
'fence': {'acquire', 'release', 'acq_rel', 'seq_cst'},
}
CAS_FAILURE = { # §24.1
'relaxed': {'relaxed'},
'acquire': {'relaxed', 'acquire'},
'release': {'relaxed'},
'acq_rel': {'relaxed', 'acquire'},
'seq_cst': {'relaxed', 'acquire', 'seq_cst'},
}
MASK = (1 << 64) - 1
RMW_OPS = {
'xchg': lambda old, v: v,
'add': lambda old, v: (old + v) & MASK,
'sub': lambda old, v: (old - v) & MASK,
'and': lambda old, v: old & v,
'or': lambda old, v: old | v,
'xor': lambda old, v: old ^ v,
}
# --------------------------------------------------------------------------
# Relations over events 0..n-1, as one bitmask row per event.
class Rel:
__slots__ = ('n', 'rows')
def __init__(self, n, rows=None):
self.n = n
self.rows = list(rows) if rows is not None else [0] * n
@classmethod
def of(cls, n, pairs):
r = cls(n)
for a, b in pairs:
r.rows[a] |= 1 << b
return r
@classmethod
def ident(cls, n, members=None):
"""[X]: the identity on the events in `members` (all if None)."""
r = cls(n)
for i in range(n):
if members is None or i in members:
r.rows[i] = 1 << i
return r
def pairs(self):
return {(i, j) for i in range(self.n) for j in range(self.n)
if self.rows[i] >> j & 1}
def has(self, a, b):
return bool(self.rows[a] >> b & 1)
def __or__(self, o):
return Rel(self.n, [a | b for a, b in zip(self.rows, o.rows)])
def __and__(self, o):
return Rel(self.n, [a & b for a, b in zip(self.rows, o.rows)])
def __sub__(self, o):
return Rel(self.n, [a & ~b for a, b in zip(self.rows, o.rows)])
def seq(self, o):
"""self ; o"""
out = []
for row in self.rows:
acc = 0
j = 0
while row:
if row & 1:
acc |= o.rows[j]
row >>= 1
j += 1
out.append(acc)
return Rel(self.n, out)
def inv(self):
return Rel.of(self.n, ((b, a) for a, b in self.pairs()))
def plus(self):
"""R⁺ (Warshall)."""
rows = list(self.rows)
for k in range(self.n):
bit, rk = 1 << k, rows[k]
for i in range(self.n):
if rows[i] & bit:
rows[i] |= rk
return Rel(self.n, rows)
def opt(self):
"""R? = R ∪ id"""
return self | Rel.ident(self.n)
def star(self):
return self.plus().opt()
def irreflexive(self):
return all(not (row >> i & 1) for i, row in enumerate(self.rows))
def acyclic(self):
return self.plus().irreflexive()
def empty(self):
return not any(self.rows)
# --------------------------------------------------------------------------
# Events and executions
@dataclass
class Event:
kind: str # 'W', 'R', 'F' or 'P' (primitive)
task: str = None # None for init writes
loc: str = None
ord: str = 'na' # 'na' only for init writes
prim: str = None # lock unlock send recv spawn join
obj: str = None # mutex/channel/task name of a primitive
@dataclass
class Execution:
events: list
sb: Rel
rf: Rel
mo: Rel
rmw: Rel
sw_prim: Rel
prim_orders: list = field(default_factory=list) # lists of event ids
def make_execution(events, sb, rf, mo, rmw=(), sw_prim=(), prim_orders=()):
"""Build an execution from pair lists (used by the tests)."""
n = len(events)
return Execution(events, Rel.of(n, sb), Rel.of(n, rf), Rel.of(n, mo),
Rel.of(n, rmw), Rel.of(n, sw_prim), list(prim_orders))
def derive(ex):
"""The derived relations of §20.2 and psc of §20.4."""
ev, n = ex.events, len(ex.events)
idx = range(n)
def sel(pred):
return Rel.ident(n, {i for i in idx if pred(ev[i])})
W = sel(lambda e: e.kind == 'W')
R = sel(lambda e: e.kind == 'R')
F = sel(lambda e: e.kind == 'F')
E_rel = sel(lambda e: e.kind in ('W', 'F') and e.ord in REL_ORDS)
E_acq = sel(lambda e: e.kind in ('R', 'F') and e.ord in ACQ_ORDS)
E_sc = sel(lambda e: e.kind in ('R', 'W') and e.ord == 'seq_cst')
F_sc = sel(lambda e: e.kind == 'F' and e.ord == 'seq_cst')
ID = Rel.ident(n)
sb, rf, mo, rmw = ex.sb, ex.rf, ex.mo, ex.rmw
fr = rf.inv().seq(mo) # rf⁻¹ ; mo
eco = (rf | mo | fr).plus() # (rf ∪ mo ∪ fr)⁺
rs = W.seq(rf.seq(rmw).star()) # [W] ; (rf ; rmw)*
sw = (E_rel.seq(ID | F.seq(sb)) # [E⊒rel] ; ([F];sb)?
.seq(rs).seq(rf).seq(R) # ; rs ; rf ; [R]
.seq(ID | sb.seq(F)).seq(E_acq)) | ex.sw_prim # ; (sb;[F])? ; [E⊒acq]
hb = (sb | sw).plus() # (sb ∪ sw)⁺
loc = Rel.of(n, ((i, j) for i in idx for j in idx
if ev[i].loc is not None and ev[i].loc == ev[j].loc))
sb_neq = sb - loc # sb|≠loc
scb = sb | sb_neq.seq(hb).seq(sb_neq) | (hb & loc) | mo | fr
hb_opt = hb.opt()
psc_b = (E_sc | F_sc.seq(hb_opt)).seq(scb).seq(E_sc | hb_opt.seq(F_sc))
psc_F = F_sc.seq(hb | hb.seq(eco).seq(hb)).seq(F_sc)
psc = psc_b | psc_F
return dict(fr=fr, eco=eco, rs=rs, sw=sw, hb=hb, scb=scb, psc=psc)
def axioms(ex, d=None):
"""The four consistency axioms of §20.4, by name, plus the §20.3
requirement that each primitive object's total order is consistent
with hb ('prim-order')."""
d = d or derive(ex)
hb, eco = d['hb'], d['eco']
prim_ok = True
for order in ex.prim_orders:
pos = {e: k for k, e in enumerate(order)}
for a in order:
for b in order:
if pos[a] > pos[b] and hb.has(a, b):
prim_ok = False
return {
# 1. hb ; eco? irreflexive
'coherence': hb.seq(eco.opt()).irreflexive(),
# 2. rmw ∩ (fr ; mo) = ∅
'atomicity': (ex.rmw & d['fr'].seq(ex.mo)).empty(),
# 3. psc acyclic
'sc': d['psc'].acyclic(),
# 4. sb ∪ rf acyclic
'no-thin-air': (ex.sb | ex.rf).acyclic(),
'prim-order': prim_ok,
}
def consistent(ex):
return all(axioms(ex).values())
# --------------------------------------------------------------------------
# Parsing
@dataclass
class Program:
name: str
init: dict
tasks: dict # name -> list of ops (tuples)
spawned: set # names declared `(spawned)`
observe: list # ('reg', task, reg) | ('final', loc)
def parse(text):
name, init, tasks, spawned, observe = None, {}, {}, set(), []
current = None
for lineno, raw in enumerate(text.splitlines(), 1):
line = raw.split('#', 1)[0].rstrip()
if not line.strip():
continue
if line[0] in ' \t':
if current is None:
raise ValueError(f'line {lineno}: operation outside a task')
tasks[current].append(parse_op(line.split(), lineno))
continue
current = None
m = re.fullmatch(r'(\w+)\s*(\(spawned\))?\s*:', line.strip())
if m and m.group(1) not in ('name', 'init', 'observe', 'allowed',
'forbidden'):
current = m.group(1)
if current in tasks:
raise ValueError(f'line {lineno}: duplicate task {current}')
tasks[current] = []
if m.group(2):
spawned.add(current)
continue
key, _, rest = line.partition(':')
key, rest = key.strip(), rest.strip()
if key == 'name':
name = rest
elif key == 'init':
for item in rest.split():
loc, _, v = item.partition('=')
init[loc] = int(v)
elif key == 'observe':
toks = rest.split()
i = 0
while i < len(toks):
if toks[i] == 'final':
observe.append(('final', toks[i + 1]))
i += 2
else:
t, _, r = toks[i].partition('.')
observe.append(('reg', t, r))
i += 1
elif key in ('allowed', 'forbidden'):
pass # stated sets: never used by the oracle
else:
raise ValueError(f'line {lineno}: unknown key {key!r}')
return Program(name, init, tasks, spawned, observe)
def _ord(tok, kind, lineno):
o = ORDS.get(tok)
if o is None or o not in ALLOWED_ORDS[kind]:
raise ValueError(f'line {lineno}: ordering {tok!r} not allowed for {kind}')
return o
def parse_op(t, lineno):
if len(t) >= 3 and t[1] == '=':
reg, op, a = t[0], t[2], t[3:]
if op == 'load' and len(a) == 2:
return ('load', reg, a[0], _ord(a[1], 'load', lineno))
if op == 'rmw' and len(a) == 4 and a[0] in RMW_OPS:
return ('rmw', reg, a[0], a[1], int(a[2]), _ord(a[3], 'rmw', lineno))
if op == 'cas' and len(a) == 5:
s = _ord(a[3], 'rmw', lineno)
f = ORDS.get(a[4])
if f not in CAS_FAILURE[s]:
raise ValueError(f'line {lineno}: cas failure ordering {a[4]!r}')
return ('cas', reg, a[0], int(a[1]), int(a[2]), s, f)
elif t[0] == 'store' and len(t) == 4:
return ('store', t[1], int(t[2]), _ord(t[3], 'store', lineno))
elif t[0] == 'fence' and len(t) == 2:
return ('fence', _ord(t[1], 'fence', lineno))
elif t[0] in ('send', 'recv', 'lock', 'unlock', 'spawn', 'join') and len(t) == 2:
return (t[0], t[1])
raise ValueError(f'line {lineno}: cannot parse {" ".join(t)!r}')
# --------------------------------------------------------------------------
# Building the events of a program
def executed_tasks(prog):
run = [t for t in prog.tasks if t not in prog.spawned]
i = 0
while i < len(run):
for op in prog.tasks[run[i]]:
if op[0] == 'spawn':
if op[1] not in prog.tasks:
raise ValueError(f'spawn of unknown task {op[1]}')
if op[1] not in prog.spawned or op[1] in run:
raise ValueError(f'task {op[1]} is not spawnable once')
run.append(op[1])
i += 1
return run
class Skeleton:
"""The events of a program for one choice of cas outcomes."""
def __init__(self, prog, tasks, cas_ok):
self.events, sb, self.rmw = [], [], []
self.write_val = {} # write eid -> ('const', v) | (fn, read eid, v)
self.reg = {} # (task, reg) -> read eid
self.cas = [] # (read eid, expected, succeeded)
self.init = {}
for loc in sorted(prog.init):
self.init[loc] = self._add(Event('W', None, loc))
self.write_val[self.init[loc]] = ('const', prog.init[loc])
first, last, self.spawn, self.join = {}, {}, {}, {}
self.mutex, self.chan = {}, {}
k = 0
for t in tasks:
ids = []
for op in prog.tasks[t]:
kind = op[0]
if kind == 'store':
e = self._add(Event('W', t, op[1], op[3]))
self.write_val[e] = ('const', op[2])
ids.append(e)
elif kind == 'load':
e = self._add(Event('R', t, op[2], op[3]))
self.reg[(t, op[1])] = e
ids.append(e)
elif kind == 'rmw':
r = self._add(Event('R', t, op[3], op[5]))
w = self._add(Event('W', t, op[3], op[5]))
self.write_val[w] = (RMW_OPS[op[2]], r, op[4])
self.reg[(t, op[1])] = r
self.rmw.append((r, w))
ids += [r, w]
elif kind == 'cas':
_, reg, loc, exp, new, s, f = op
ok = cas_ok[k]
k += 1
r = self._add(Event('R', t, loc, s if ok else f))
self.reg[(t, reg)] = r
self.cas.append((r, exp, ok))
ids.append(r)
if ok:
w = self._add(Event('W', t, loc, s))
self.write_val[w] = ('const', new)
self.rmw.append((r, w))
ids.append(w)
elif kind == 'fence':
ids.append(self._add(Event('F', t, None, op[1])))
else:
e = self._add(Event('P', t, None, 'na', kind, op[1]))
ids.append(e)
if kind == 'spawn':
self.spawn[op[1]] = e
elif kind == 'join':
self.join.setdefault(op[1], []).append(e)
elif kind in ('lock', 'unlock'):
self.mutex.setdefault(op[1], []).append(e)
else:
self.chan.setdefault(op[1], []).append(e)
sb += [(a, b) for a, b in itertools.combinations(ids, 2)]
if ids:
first[t], last[t] = ids[0], ids[-1]
for i in self.init.values(): # RC11: init sb-before everything
sb += [(i, e) for e in range(len(self.events)) if e not in self.init.values()]
self.sb = sb
# spawn/join sw_prim (fixed)
self.sw_fixed = []
for t, s in self.spawn.items():
self.sw_fixed.append((s, first.get(t, s)))
for t, js in self.join.items():
if t not in tasks:
raise ValueError(f'join of a task that never runs: {t}')
for j in js:
src = last.get(t, self.spawn.get(t))
if src is not None:
self.sw_fixed.append((src, j))
self.reads = [i for i, e in enumerate(self.events) if e.kind == 'R']
self.writes = {}
for i, e in enumerate(self.events):
if e.kind == 'W':
self.writes.setdefault(e.loc, []).append(i)
for loc in {e.loc for e in self.events if e.loc}:
if loc not in self.init:
raise ValueError(f'location {loc} has no init value')
def _add(self, e):
self.events.append(e)
return len(self.events) - 1
def mutex_orders(self, ops):
"""Total orders of a mutex's operations obeying the lock protocol."""
for perm in itertools.permutations(ops):
holder, ok = None, True
for e in perm:
ev = self.events[e]
if ev.prim == 'lock':
ok = holder is None
holder = ev.task
else:
ok = holder == ev.task
holder = None
if not ok:
break
if ok:
yield list(perm), [(perm[i], perm[i + 1]) for i in range(len(perm) - 1)
if self.events[perm[i]].prim == 'unlock']
def channel_orders(self, ops):
"""Total orders of a channel's operations that are FIFO histories."""
for perm in itertools.permutations(ops):
queue, sw, ok = [], [], True
for e in perm:
if self.events[e].prim == 'send':
queue.append(e)
elif queue:
sw.append((queue.pop(0), e))
else:
ok = False
break
if ok:
yield list(perm), sw
def values(self, rf_of):
"""Value of every event given rf (read -> write), or None if the
values are not well-defined (a cycle through rf and rmw)."""
val, busy = {}, set()
def wval(w):
if w in val:
return val[w]
if w in busy:
raise RecursionError
busy.add(w)
spec = self.write_val[w]
if spec[0] == 'const':
v = spec[1]
else:
fn, r, operand = spec
v = fn(wval(rf_of[r]), operand)
val[w] = v
return v
try:
for w in self.write_val:
wval(w)
for r in self.reads:
val[r] = wval(rf_of[r])
except RecursionError:
return None
return val
def candidates(prog):
"""Yield (execution, values, outcome) for every candidate execution.
`values` is None (and `outcome` None) when sb ∪ rf is cyclic."""
tasks = executed_tasks(prog)
n_cas = sum(op[0] == 'cas' for t in tasks for op in prog.tasks[t])
for cas_ok in itertools.product((True, False), repeat=n_cas):
sk = Skeleton(prog, tasks, cas_ok)
rf_choices = [sk.writes[sk.events[r].loc] for r in sk.reads]
locs = sorted(sk.writes)
mo_choices = [[[sk.init[loc]] + list(p) for p in itertools.permutations(
[w for w in sk.writes[loc] if w != sk.init[loc]])] for loc in locs]
prim_choices = ([list(sk.mutex_orders(ops)) for ops in sk.mutex.values()]
+ [list(sk.channel_orders(ops)) for ops in sk.chan.values()])
for rf_srcs in itertools.product(*rf_choices):
rf_of = dict(zip(sk.reads, rf_srcs))
val = sk.values(rf_of)
if val is not None and any((val[r] == exp) != ok for r, exp, ok in sk.cas):
continue # the cas outcome contradicts the value read
rf = [(w, r) for r, w in rf_of.items()]
for mos in itertools.product(*mo_choices):
mo = [(a, b) for chain in mos for a, b in itertools.combinations(chain, 2)]
final = {loc: chain[-1] for loc, chain in zip(locs, mos)}
outcome = None if val is None else tuple(
val[sk.reg[(o[1], o[2])]] if o[0] == 'reg' else val[final[o[1]]]
for o in prog.observe)
for prims in itertools.product(*prim_choices):
sw_prim = sk.sw_fixed + [p for _, sw in prims for p in sw]
yield (make_execution(sk.events, sk.sb, rf, mo, sk.rmw, sw_prim,
[o for o, _ in prims]), val, outcome)
def enumerate_program(prog):
"""(sorted allowed outcomes, #consistent executions, #candidates)"""
allowed, n_cand, n_cons = set(), 0, 0
for ex, val, outcome in candidates(prog):
n_cand += 1
if consistent(ex):
assert val is not None # guaranteed by no-thin-air
n_cons += 1
allowed.add(outcome)
return sorted(list(t) for t in allowed), n_cons, n_cand
def run_file(path):
with open(path) as f:
prog = parse(f.read())
allowed, n_cons, n_cand = enumerate_program(prog)
obs = [f'{o[1]}.{o[2]}' if o[0] == 'reg' else f'final {o[1]}' for o in prog.observe]
return {'file': path, 'name': prog.name, 'observe': obs, 'allowed': allowed,
'executions': n_cons, 'candidates': n_cand}
def main(argv):
if not argv:
print(__doc__.split('\n\n')[1], file=sys.stderr)
return 2
for path in argv:
print(json.dumps(run_file(path)))
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))