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.
This commit is contained in:
1 parent
cfee89ff19
commit
f8d2a99249
28 files changed
+1278
-5
No files matched your search
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the axiomatic oracle with the stated outcome sets of the litmus corpus.
|
||||
|
||||
Usage: python3 tools/litmus/check.py [tests/litmus/*.lit]
|
||||
|
||||
For every test the oracle's allowed set (tools/litmus/enumerate.py) MUST equal the
|
||||
stated `allowed:` set, and no stated `forbidden:` outcome may be allowed
|
||||
(spec 04 §20.5). A mismatch is a finding to diagnose, never a reason to edit
|
||||
the stated set to match (docs/reference/concurrency-litmus.md).
|
||||
"""
|
||||
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(os.path.dirname(HERE))
|
||||
|
||||
|
||||
def outcomes(line):
|
||||
return {tuple(int(v) for v in m.split(",")) for m in re.findall(r"\(([^)]*)\)", line)}
|
||||
|
||||
|
||||
def stated(path):
|
||||
allowed, forbidden = set(), set()
|
||||
for line in open(path):
|
||||
line = line.split("#", 1)[0].strip()
|
||||
if line.startswith("allowed:"):
|
||||
allowed |= outcomes(line)
|
||||
elif line.startswith("forbidden:"):
|
||||
forbidden |= outcomes(line)
|
||||
return allowed, forbidden
|
||||
|
||||
|
||||
def main(argv):
|
||||
files = argv or sorted(glob.glob(os.path.join(ROOT, "tests", "litmus", "*.lit")))
|
||||
out = subprocess.run([sys.executable, os.path.join(HERE, "enumerate.py"), *files], capture_output=True, text=True, check=True).stdout
|
||||
computed = {}
|
||||
for line in out.splitlines():
|
||||
if line.strip():
|
||||
r = json.loads(line)
|
||||
computed[os.path.abspath(r["file"])] = {tuple(o) for o in r["allowed"]}
|
||||
failures = 0
|
||||
for f in files:
|
||||
allowed, forbidden = stated(f)
|
||||
got = computed.get(os.path.abspath(f))
|
||||
name = os.path.relpath(f, ROOT)
|
||||
problems = []
|
||||
if allowed & forbidden:
|
||||
problems.append(f"stated sets overlap: {sorted(allowed & forbidden)}")
|
||||
if got is None:
|
||||
problems.append("no oracle result")
|
||||
else:
|
||||
if got - allowed:
|
||||
problems.append(f"oracle allows unstated {sorted(got - allowed)}")
|
||||
if allowed - got:
|
||||
problems.append(f"oracle forbids stated-allowed {sorted(allowed - got)}")
|
||||
if got & forbidden:
|
||||
problems.append(f"oracle allows stated-forbidden {sorted(got & forbidden)}")
|
||||
if problems:
|
||||
failures += 1
|
||||
print(f"MISMATCH {name}: " + "; ".join(problems))
|
||||
else:
|
||||
print(f"ok {name}")
|
||||
print(f"\n{len(files) - failures} agree, {failures} disagree")
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,610 @@
|
||||
#!/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:]))
|
||||
@@ -0,0 +1,291 @@
|
||||
"""Self-tests of the axiomatic oracle (tools/litmus/enumerate.py).
|
||||
|
||||
python3 -m unittest tools/litmus/test_enumerate.py
|
||||
|
||||
None of these tests uses the expected sets of the litmus corpus. Every
|
||||
expected value is derived by hand from spec 04 §20.2-§20.4; the derivation is
|
||||
in the comment next to it.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import enumerate as E # noqa: E402
|
||||
|
||||
AXIOMS = ('coherence', 'atomicity', 'sc', 'no-thin-air')
|
||||
|
||||
|
||||
def allowed(src):
|
||||
return {tuple(o) for o in E.enumerate_program(E.parse(src))[0]}
|
||||
|
||||
|
||||
def W(task, loc, o='relaxed'):
|
||||
return E.Event('W', task, loc, o)
|
||||
|
||||
|
||||
def R(task, loc, o='relaxed'):
|
||||
return E.Event('R', task, loc, o)
|
||||
|
||||
|
||||
def INIT(loc):
|
||||
return E.Event('W', None, loc)
|
||||
|
||||
|
||||
def init_sb(events):
|
||||
"""RC11 convention used by the oracle: init writes sb-before all events."""
|
||||
inits = [i for i, e in enumerate(events) if e.task is None]
|
||||
return [(i, j) for i in inits for j in range(len(events)) if j not in inits]
|
||||
|
||||
|
||||
def failing(ex):
|
||||
return {k for k, ok in E.axioms(ex).items() if not ok}
|
||||
|
||||
|
||||
class SingleTask(unittest.TestCase):
|
||||
"""With one task, hb ⊇ sb and coherence alone forces SC behaviour."""
|
||||
|
||||
def test_reads_own_store(self):
|
||||
# Reading init would give fr(load, store) with sb(store, load):
|
||||
# hb;eco reflexive, coherence violated. So only 1.
|
||||
self.assertEqual(allowed('init: x=0\nT0:\n store x 1 rlx\n r0 = load x rlx\n'
|
||||
'observe: T0.r0\n'), {(1,)})
|
||||
|
||||
def test_last_store_is_final(self):
|
||||
# mo(2-store, 1-store) with sb(1-store, 2-store) is hb;mo reflexive.
|
||||
self.assertEqual(allowed('init: x=0\nT0:\n store x 1 rlx\n store x 2 rlx\n'
|
||||
'observe: final x\n'), {(2,)})
|
||||
|
||||
def test_load_before_store_reads_init(self):
|
||||
# Reading the sb-later store is an sb ∪ rf cycle (no-thin-air) and
|
||||
# also hb;rf reflexive (coherence). So only 0.
|
||||
self.assertEqual(allowed('init: x=0\nT0:\n r0 = load x rlx\n store x 1 rlx\n'
|
||||
'observe: T0.r0 final x\n'), {(0, 1)})
|
||||
|
||||
def test_rmw_chain(self):
|
||||
# Each add reads its sb-predecessor's write (coherence), wrapping 2^64
|
||||
# for sub; xchg returns the old value.
|
||||
src = ('init: x=5\nT0:\n r0 = rmw add x 3 rlx\n r1 = rmw sub x 10 rlx\n'
|
||||
' r2 = rmw xchg x 7 sc\n r3 = load x acq\nobserve: T0.r0 T0.r1 T0.r2 T0.r3 final x\n')
|
||||
self.assertEqual(allowed(src), {(5, 8, (8 - 10) % 2**64, 7, 7)})
|
||||
|
||||
def test_cas_success_and_failure(self):
|
||||
# First cas reads 0 = EXP, writes 1; second reads 1 ≠ 0, fails.
|
||||
src = ('init: x=0\nT0:\n r0 = cas x 0 1 rlx rlx\n r1 = cas x 0 2 sc sc\n'
|
||||
'observe: T0.r0 T0.r1 final x\n')
|
||||
self.assertEqual(allowed(src), {(0, 1, 1)})
|
||||
|
||||
def test_stated_sets_are_ignored(self):
|
||||
# The parser skips allowed:/forbidden: lines, even false ones.
|
||||
src = ('init: x=0\nT0:\n store x 1 rlx\n r0 = load x rlx\nobserve: T0.r0\n'
|
||||
'allowed: (0) (7)\nforbidden: (1)\n')
|
||||
self.assertEqual(allowed(src), {(1,)})
|
||||
|
||||
|
||||
class HandBuiltAxioms(unittest.TestCase):
|
||||
"""One hand-built execution per axiom: it violates exactly that axiom."""
|
||||
|
||||
def test_coherence_corr(self):
|
||||
# 0 init x; 1 T0: W x=1; 2,3 T1: R x, R x.
|
||||
# rf: 1→2 and 0→3; mo: 0→1. fr(3,1) since 0 mo 1. sb(2,3).
|
||||
# hb(2,3) ; eco(3,2) = fr(3,1);rf(1,2): coherence violated.
|
||||
# Atomicity: no rmw. SC: no sc event. sb ∪ rf: 0→*, 1→2→3: acyclic.
|
||||
ev = [INIT('x'), W('T0', 'x'), R('T1', 'x'), R('T1', 'x')]
|
||||
ex = E.make_execution(ev, init_sb(ev) + [(2, 3)], [(1, 2), (0, 3)], [(0, 1)])
|
||||
self.assertEqual(failing(ex), {'coherence'})
|
||||
|
||||
def test_atomicity(self):
|
||||
# 0 init x; 1,2 T0 RMW (R,W); 3,4 T1 RMW (R,W); both reads read init.
|
||||
# mo: 0→2→4. fr(3,2) (rf(0,3), mo(0,2)); mo(2,4): (3,4) ∈ fr;mo ∩ rmw.
|
||||
# Coherence: hb = sb; eco never leads back to an sb-earlier event of
|
||||
# the same task (T0's events precede 4 only via eco). sb ∪ rf acyclic.
|
||||
ev = [INIT('x'), R('T0', 'x'), W('T0', 'x'), R('T1', 'x'), W('T1', 'x')]
|
||||
ex = E.make_execution(ev, init_sb(ev) + [(1, 2), (3, 4)], [(0, 1), (0, 3)],
|
||||
[(0, 2), (0, 4), (2, 4)], rmw=[(1, 2), (3, 4)])
|
||||
self.assertEqual(failing(ex), {'atomicity'})
|
||||
|
||||
def test_no_thin_air_lb(self):
|
||||
# 0 init x, 1 init y; T0: 2 R x, 3 W y=1; T1: 4 R y, 5 W x=1.
|
||||
# rf 5→2, 3→4: sb(2,3) rf(3,4) sb(4,5) rf(5,2) is an sb ∪ rf cycle.
|
||||
# All relaxed: sw = ∅, hb = sb. eco relates only same-location
|
||||
# events; hb;eco would need hb into a write, then back: 2 hb 3 but
|
||||
# eco from 3 (y) only reaches 4, not 2. Coherence holds. No rmw, no sc.
|
||||
ev = [INIT('x'), INIT('y'), R('T0', 'x'), W('T0', 'y'), R('T1', 'y'), W('T1', 'x')]
|
||||
ex = E.make_execution(ev, init_sb(ev) + [(2, 3), (4, 5)], [(5, 2), (3, 4)],
|
||||
[(0, 5), (1, 3)])
|
||||
self.assertEqual(failing(ex), {'no-thin-air'})
|
||||
|
||||
def _sb_execution(self, o):
|
||||
# 0 init x, 1 init y; T0: 2 W x=1, 3 R y; T1: 4 W y=1, 5 R x.
|
||||
# Both reads read init: fr(3,4), fr(5,2).
|
||||
ev = [INIT('x'), INIT('y'), W('T0', 'x', o), R('T0', 'y', o),
|
||||
W('T1', 'y', o), R('T1', 'x', o)]
|
||||
return E.make_execution(ev, init_sb(ev) + [(2, 3), (4, 5)], [(1, 3), (0, 5)],
|
||||
[(0, 2), (1, 4)])
|
||||
|
||||
def test_psc_cycle_sb_sc(self):
|
||||
# All seq_cst: psc ⊇ sb(2,3), fr(3,4), sb(4,5), fr(5,2): a cycle.
|
||||
# Reads read the non-release init: no sw, hb = sb; coherence holds
|
||||
# (eco never returns to the same task). sb ∪ rf acyclic.
|
||||
self.assertEqual(failing(self._sb_execution('seq_cst')), {'sc'})
|
||||
|
||||
def test_sb_relaxed_consistent(self):
|
||||
# Same execution, relaxed: psc is empty; nothing else changes.
|
||||
self.assertEqual(failing(self._sb_execution('relaxed')), set())
|
||||
|
||||
def test_psc_fences(self):
|
||||
# SB with relaxed accesses separated by seq_cst fences, both reads
|
||||
# reading init. 0 init x, 1 init y; T0: 2 W x, 3 F sc, 4 R y;
|
||||
# T1: 5 W y, 6 F sc, 7 R x. psc_b: [F_sc];hb?;scb;hb?;[F_sc]:
|
||||
# 3 sb 4 fr 5 sb 6 gives 3 → 6 (scb ∋ fr, hb? = sb on each side), and
|
||||
# symmetrically 6 → 3. psc cycle; other axioms hold.
|
||||
ev = [INIT('x'), INIT('y'), W('T0', 'x'), E.Event('F', 'T0', None, 'seq_cst'),
|
||||
R('T0', 'y'), W('T1', 'y'), E.Event('F', 'T1', None, 'seq_cst'), R('T1', 'x')]
|
||||
sb = init_sb(ev) + [(2, 3), (2, 4), (3, 4), (5, 6), (5, 7), (6, 7)]
|
||||
ex = E.make_execution(ev, sb, [(1, 4), (0, 7)], [(0, 2), (1, 5)])
|
||||
self.assertEqual(failing(ex), {'sc'})
|
||||
|
||||
def test_release_acquire_sw(self):
|
||||
# MP: T0: 2 W x=1 rlx, 3 W y=1 rel; T1: 4 R y acq (reads 3), 5 R x.
|
||||
# sw(3,4) by [E⊒rel];rs;rf;[R];[E⊒acq], hence hb(2,5).
|
||||
# If 5 reads init: fr(5,2) and hb(2,5): coherence violated.
|
||||
ev = [INIT('x'), INIT('y'), W('T0', 'x'), W('T0', 'y', 'release'),
|
||||
R('T1', 'y', 'acquire'), R('T1', 'x')]
|
||||
sb = init_sb(ev) + [(2, 3), (4, 5)]
|
||||
ex = E.make_execution(ev, sb, [(3, 4), (0, 5)], [(0, 2), (1, 3)])
|
||||
d = E.derive(ex)
|
||||
self.assertTrue(d['sw'].has(3, 4))
|
||||
self.assertTrue(d['hb'].has(2, 5))
|
||||
self.assertEqual(failing(ex), {'coherence'})
|
||||
# Relaxed load of y instead: no sw, and the same rf is consistent.
|
||||
ev[4] = R('T1', 'y')
|
||||
ex = E.make_execution(ev, sb, [(3, 4), (0, 5)], [(0, 2), (1, 3)])
|
||||
self.assertFalse(E.derive(ex)['sw'].has(3, 4))
|
||||
self.assertEqual(failing(ex), set())
|
||||
|
||||
def test_release_sequence_through_rmw(self):
|
||||
# 0 init f; T0: 1 W f rel; T1: 2,3 relaxed RMW reading 1;
|
||||
# T2: 4 R f acq reading 3. rs ∋ (1,3) = rf(1,2);rmw(2,3), so sw(1,4).
|
||||
ev = [INIT('f'), W('T0', 'f', 'release'), R('T1', 'f'), W('T1', 'f'),
|
||||
R('T2', 'f', 'acquire')]
|
||||
ex = E.make_execution(ev, init_sb(ev) + [(2, 3)], [(1, 2), (3, 4)],
|
||||
[(0, 1), (0, 3), (1, 3)], rmw=[(2, 3)])
|
||||
d = E.derive(ex)
|
||||
self.assertTrue(d['rs'].has(1, 3))
|
||||
self.assertTrue(d['sw'].has(1, 4))
|
||||
self.assertEqual(failing(ex), set())
|
||||
|
||||
|
||||
class Programs(unittest.TestCase):
|
||||
"""Small programs (not from the corpus), outcomes derived by hand."""
|
||||
|
||||
def test_mutex_two_loads(self):
|
||||
# T0 stores x in a critical section; T1 loads x twice in one.
|
||||
# Lock order T1 first: unlock(T1) sw lock(T0), so T1's loads hb the
|
||||
# store; reading it is hb;rf reflexive → (0,0). T0 first: store hb
|
||||
# both loads; reading init gives fr(load, store) with hb(store, load)
|
||||
# → (1,1). Without the mutex (0,1) would be allowed (CoRR permits it).
|
||||
src = ('init: x=0\nT0:\n lock m\n store x 1 rlx\n unlock m\n'
|
||||
'T1:\n lock m\n r0 = load x rlx\n r1 = load x rlx\n unlock m\n'
|
||||
'observe: T1.r0 T1.r1\n')
|
||||
self.assertEqual(allowed(src), {(0, 0), (1, 1)})
|
||||
|
||||
def test_channel_fifo(self):
|
||||
# FIFO: the first recv gets the first send, the second the second.
|
||||
# After recv #1, store x=1 is hb, x=2 may or may not be seen: r0 ∈ {1,2}.
|
||||
# After recv #2, store x=2 is hb and mo-last: r1 = 2.
|
||||
src = ('init: x=0\nT0:\n store x 1 rlx\n send c\n store x 2 rlx\n send c\n'
|
||||
'T1:\n recv c\n r0 = load x rlx\n recv c\n r1 = load x rlx\n'
|
||||
'observe: T1.r0 T1.r1\n')
|
||||
self.assertEqual(allowed(src), {(1, 2), (2, 2)})
|
||||
|
||||
def test_spawn_sees_parent_and_join_sees_child(self):
|
||||
# The parent's store is hb the child's load (spawn → first event);
|
||||
# the child's store is hb the parent's load (last event → join).
|
||||
src = ('init: x=0 y=0\nT0:\n store x 1 rlx\n spawn T1\n join T1\n'
|
||||
' r1 = load y rlx\nT1 (spawned):\n r0 = load x rlx\n store y 1 rlx\n'
|
||||
'observe: T1.r0 T0.r1\n')
|
||||
self.assertEqual(allowed(src), {(1, 1)})
|
||||
|
||||
def test_unspawned_task_does_not_run(self):
|
||||
src = ('init: x=0\nT0:\n r0 = load x rlx\nT1 (spawned):\n store x 1 rlx\n'
|
||||
'observe: T0.r0 final x\n')
|
||||
self.assertEqual(allowed(src), {(0, 0)})
|
||||
|
||||
def test_three_relaxed_increments(self):
|
||||
# Atomicity: every RMW reads its immediate mo-predecessor, so the
|
||||
# values read are a permutation of 0,1,2 and the final value is 3.
|
||||
src = ('init: x=0\nT0:\n r0 = rmw add x 1 rlx\nT1:\n r1 = rmw add x 1 rlx\n'
|
||||
'T2:\n r2 = rmw add x 1 rlx\nobserve: T0.r0 T1.r1 T2.r2 final x\n')
|
||||
perms = {(a, b, c, 3) for a in range(3) for b in range(3) for c in range(3)
|
||||
if len({a, b, c}) == 3}
|
||||
self.assertEqual(allowed(src), perms)
|
||||
|
||||
def test_invalid_orderings_rejected(self):
|
||||
for op in ('store x 1 acq', 'r0 = load x rel', 'fence rlx',
|
||||
'r0 = cas x 0 1 rel acq', 'r0 = cas x 0 1 acq sc'):
|
||||
with self.assertRaises(ValueError, msg=op):
|
||||
E.parse(f'init: x=0\nT0:\n {op}\nobserve: final x\n')
|
||||
|
||||
|
||||
class WellFormedness(unittest.TestCase):
|
||||
"""Every consistent execution has well-formed rf and mo (§20.2)."""
|
||||
|
||||
SOURCES = [
|
||||
'init: x=0 y=0\nT0:\n store x 1 rel\n r0 = rmw xchg y 2 ar\nT1:\n'
|
||||
' r1 = cas y 0 3 sc acq\n store x 2 sc\nobserve: T0.r0 T1.r1 final x final y\n',
|
||||
'init: x=0\nT0:\n r0 = rmw add x 1 rlx\n store x 9 rel\nT1:\n'
|
||||
' r1 = load x acq\n r2 = rmw sub x 1 rlx\nobserve: T1.r1 T1.r2\n',
|
||||
]
|
||||
|
||||
def test_rf_mo_well_formed(self):
|
||||
for src in self.SOURCES:
|
||||
n_cons = 0
|
||||
for ex, val, _ in E.candidates(E.parse(src)):
|
||||
if not E.consistent(ex):
|
||||
continue
|
||||
n_cons += 1
|
||||
ev = ex.events
|
||||
writes = {}
|
||||
for i, e in enumerate(ev):
|
||||
if e.kind == 'W':
|
||||
writes.setdefault(e.loc, []).append(i)
|
||||
rf = ex.rf.pairs()
|
||||
for i, e in enumerate(ev):
|
||||
srcs = [w for w, r in rf if r == i]
|
||||
if e.kind == 'R':
|
||||
# exactly one source, a write to the same location,
|
||||
# whose value the read returns
|
||||
self.assertEqual(len(srcs), 1)
|
||||
self.assertEqual(ev[srcs[0]].kind, 'W')
|
||||
self.assertEqual(ev[srcs[0]].loc, e.loc)
|
||||
self.assertEqual(val[i], val[srcs[0]])
|
||||
else:
|
||||
self.assertEqual(srcs, [])
|
||||
mo = ex.mo.pairs()
|
||||
for a, b in mo:
|
||||
self.assertEqual(ev[a].kind, 'W')
|
||||
self.assertEqual(ev[a].loc, ev[b].loc)
|
||||
for loc, ws in writes.items():
|
||||
init = [w for w in ws if ev[w].task is None]
|
||||
self.assertEqual(len(init), 1)
|
||||
for a in ws:
|
||||
self.assertNotIn((a, a), mo) # strict
|
||||
if a != init[0]:
|
||||
self.assertIn((init[0], a), mo) # init first
|
||||
for b in ws:
|
||||
if a != b: # total
|
||||
self.assertTrue((a, b) in mo or (b, a) in mo)
|
||||
# every rmw read part reads the immediate mo-predecessor of
|
||||
# its write part (consequence of atomicity + coherence)
|
||||
for r, w in ex.rmw.pairs():
|
||||
src_w = next(s for s, x in rf if x == r)
|
||||
between = [c for c in writes[ev[w].loc]
|
||||
if (src_w, c) in mo and (c, w) in mo]
|
||||
self.assertTrue((src_w, w) in mo and not between)
|
||||
self.assertGreater(n_cons, 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user