rca-umb's picture
Five Desks Code: tasks, calibration and source
e042d72 verified
Raw History Blame Contribute Delete
13 kB
"""Build the bug catalog for Five Desks Code: single-token mutants of real libraries that their own tests detect.
Runs inside the builder container (no network), never on the host:
docker run --rm --network none -v $PWD/sdists:/sdists:ro -v $PWD/out:/out -v $PWD:/build:ro \
codedesk-builder python /build/catalog.py [--per-lib 80]
For each library: run its test suite once (baseline), enumerate mutation sites inside function bodies (comparison,
arithmetic, boolean and constant changes), apply each one alone, run the tests again and keep mutants that 1 to 8
previously passing tests catch. Writes /out/<lib>/ (the pristine source tree) and /out/catalog.json.
"""
import argparse
import ast
import io
import json
import os
import random
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import tokenize
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
# name: (sdist stem, package path inside the sdist, tests path, domain, test runner timeout s)
LIBS = {
"croniter": ("croniter-6.2.4", "src/croniter", "src/croniter/tests", "office-white-collar", 120),
"isodate": ("isodate-0.7.2", "src/isodate", "tests", "office-white-collar", 60),
"humanize": ("humanize-4.16.0", "src/humanize", "tests", "office-white-collar", 60),
"numpy_financial": ("numpy-financial-1.0.0", "numpy_financial", "numpy_financial/tests", "finance-economics", 60),
"uncertainties": ("uncertainties-3.2.3", "uncertainties", "tests", "natural-science", 120),
"simple_pid": ("simple_pid-2.0.1", "simple_pid", "tests", "industrial-physical-systems", 60),
"srt": ("srt-3.5.3", "srt.py", "tests", "media-content-production", 180),
"webvtt": ("webvtt-py-0.5.1", "webvtt", "tests", "media-content-production", 60),
"slugify": ("python_slugify-9.1.3", "slugify", "tests", "media-content-production", 60),
"itsdangerous": ("itsdangerous-2.2.0", "src/itsdangerous", "tests", "cybersecurity", 60),
"jwt": ("pyjwt-2.15.1", "jwt", "tests", "cybersecurity", 60),
"toolz": ("toolz-1.2.0", "toolz", "toolz/tests", "software-engineering", 60),
"tabulate": ("tabulate-0.10.0", "tabulate", "test", "software-engineering", 60),
"inflection": ("inflection-0.5.1", "inflection", "test_inflection.py", "software-engineering", 60),
"more_itertools": ("more_itertools-11.1.0", "more_itertools", "tests", "mathematics-or-formal-reasoning", 240),
"semver": ("semver-3.1.0", "src/semver", "tests", "software-engineering", 60),
"fluids": ("fluids-1.3.1", "fluids", "tests", "industrial-physical-systems", 120),
}
# libraries whose catalog uses only some modules and the test files that cover them
SUBSET = {
"fluids": {m: f"tests/test_{m}.py" for m in ["pump", "control_valve", "friction", "fittings", "core", "compressible",
"safety_valve", "piping", "flow_meter", "separator", "two_phase",
"open_flow", "jet_pump", "packed_bed", "drag", "mixing"]},
}
# tests that never finish on their own (real-time simulation); they are also removed from the shipped copies
DESELECT = ["--deselect", "tests/test_pid.py::test_converge_system"]
SWAPS = {ast.Lt: "<=", ast.LtE: "<", ast.Gt: ">=", ast.GtE: ">", ast.Eq: "!=", ast.NotEq: "==",
ast.Add: "-", ast.Sub: "+", ast.Mult: "/", ast.Div: "*", ast.FloorDiv: "/", ast.Mod: "//",
ast.And: "or", ast.Or: "and"}
OP_TEXT = {ast.Lt: "<", ast.LtE: "<=", ast.Gt: ">", ast.GtE: ">=", ast.Eq: "==", ast.NotEq: "!=", ast.Add: "+",
ast.Sub: "-", ast.Mult: "*", ast.Div: "/", ast.FloorDiv: "//", ast.Mod: "%", ast.And: "and", ast.Or: "or"}
def sites(src: str):
"""Yield (line, col, old, new, kind, function) for single-token mutations inside function bodies."""
tree = ast.parse(src)
toks = [t for t in tokenize.generate_tokens(io.StringIO(src).readline) if t.type in (tokenize.OP, tokenize.NAME)]
def token_between(a, b, text):
for t in toks:
if a <= t.start and t.end <= b and t.string == text:
return t
return None
def walk(node, func):
for child in ast.iter_child_nodes(node):
name = child.name if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)) else func
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
# skip decorators and defaults: mutate the body only
for stmt in child.body:
if not (isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant)): # docstrings
yield from walk_stmt(stmt, name)
continue
if isinstance(child, ast.ClassDef):
yield from walk(child, func)
def walk_stmt(stmt, func):
for n in ast.walk(stmt):
if isinstance(n, ast.Compare):
left = n.left
for op, right in zip(n.ops, n.comparators):
if type(op) in SWAPS:
t = token_between((left.end_lineno, left.end_col_offset), (right.lineno, right.col_offset),
OP_TEXT[type(op)])
if t:
yield t.start[0], t.start[1], t.string, SWAPS[type(op)], "compare", func
left = right
elif isinstance(n, ast.BinOp) and type(n.op) in SWAPS:
if isinstance(n.left, ast.Constant) and isinstance(n.left.value, str):
continue # string formatting with %, concatenation
t = token_between((n.left.end_lineno, n.left.end_col_offset), (n.right.lineno, n.right.col_offset),
OP_TEXT[type(n.op)])
if t:
yield t.start[0], t.start[1], t.string, SWAPS[type(n.op)], "arith", func
elif isinstance(n, ast.BoolOp) and type(n.op) in SWAPS:
for a, b in zip(n.values, n.values[1:]):
t = token_between((a.end_lineno, a.end_col_offset), (b.lineno, b.col_offset), OP_TEXT[type(n.op)])
if t:
yield t.start[0], t.start[1], t.string, SWAPS[type(n.op)], "bool", func
elif isinstance(n, ast.UnaryOp) and isinstance(n.op, ast.Not):
yield n.lineno, n.col_offset, "not ", "", "not", func
elif (isinstance(n, ast.Constant) and type(n.value) is int and 0 <= n.value <= 64
and n.end_lineno == n.lineno and n.end_col_offset - n.col_offset == len(str(n.value))):
yield n.lineno, n.col_offset, str(n.value), str(n.value + 1 if n.value != 1 else 0), "const", func
yield from walk(tree, None)
def apply(src: str, line: int, col: int, old: str, new: str) -> str:
lines = src.splitlines(keepends=True)
text = lines[line - 1]
assert text[col:col + len(old)] == old, (text, col, old)
lines[line - 1] = text[:col] + new + text[col + len(old):]
return "".join(lines)
def run_tests(root: Path, tests: str, timeout: int, select=None):
"""Run pytest; return ({nodeid: outcome}, output) or (None, output) on a crash or timeout."""
with tempfile.TemporaryDirectory() as tmp:
xml = Path(tmp) / "r.xml"
cmd = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "-p", "no:randomly", "--tb=no",
"--hypothesis-seed=0", f"--junitxml={xml}", "-o", "junit_family=xunit1", *DESELECT,
*(select or [tests])]
env = {**os.environ, "PYTHONPATH": f"{root}:{root}/src", "PYTHONDONTWRITEBYTECODE": "1"}
try:
proc = subprocess.run(cmd, cwd=root, env=env, capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired:
return None, "timeout"
if not xml.exists():
return None, proc.stdout[-2000:] + proc.stderr[-2000:]
results = {}
for case in ET.parse(xml).getroot().iter("testcase"):
nodeid = f"{case.get('file') or case.get('classname')}::{case.get('name')}"
kids = {c.tag for c in case}
results[nodeid] = ("failed" if kids & {"failure", "error"} else "skipped" if "skipped" in kids else "passed")
return results, proc.stdout[-4000:]
def failure_text(root: Path, nodeid: str, timeout: int) -> str:
file_part, _, name = nodeid.partition("::")
env = {**os.environ, "PYTHONPATH": f"{root}:{root}/src", "PYTHONDONTWRITEBYTECODE": "1"}
cmd = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "--tb=short", "-x", "--hypothesis-seed=0",
*DESELECT, "-k", name.split("[")[0]]
path = file_part.replace(".", "/") + ".py" if not file_part.endswith(".py") else file_part
if (root / path).exists():
cmd.append(path)
try:
out = subprocess.run(cmd, cwd=root, env=env, capture_output=True, text=True, timeout=timeout).stdout
except subprocess.TimeoutExpired:
return ""
return out[-3000:]
def build_lib(name, spec, per_lib, out_dir, workers):
stem, pkg, tests, domain, timeout = spec
pristine = out_dir / name
if pristine.exists():
shutil.rmtree(pristine)
with tarfile.open(f"/sdists/{stem}.tar.gz") as tf:
tf.extractall(out_dir / "_extract", filter="data")
shutil.move(str(out_dir / "_extract" / stem), str(pristine))
import time
subset = SUBSET.get(name)
select = sorted(set(subset.values())) if subset else None
t0 = time.monotonic()
base, out = run_tests(pristine, tests, timeout * 2, select)
timeout = max(15, int(5 * (time.monotonic() - t0))) # mutants that loop forever are cut off early
if base is None:
print(f"{name}: baseline failed: {out[-300:]}", flush=True)
return []
passing = {k for k, v in base.items() if v == "passed"}
(out_dir / f"{name}.baseline.json").write_text(json.dumps(base, indent=0))
files = [pristine / pkg] if pkg.endswith(".py") else sorted((pristine / pkg).rglob("*.py"))
files = [f for f in files if "test" not in f.relative_to(pristine).as_posix().split("/")[-1]
and "/tests/" not in f.relative_to(pristine).as_posix()]
if subset:
files = [f for f in files if f.stem in subset and f.parent == pristine / pkg]
cands = []
for f in files:
src = f.read_text()
try:
for s in sites(src):
cands.append((f.relative_to(pristine).as_posix(), *s))
except (SyntaxError, tokenize.TokenError):
continue
rng = random.Random(f"catalog:{name}")
rng.shuffle(cands)
cands = cands[:per_lib * 3]
print(f"{name}: {len(passing)} passing tests, {len(cands)} candidate sites", flush=True)
def try_one(c):
rel, line, col, old, new, kind, func = c
work = Path(tempfile.mkdtemp())
try:
shutil.copytree(pristine, work / "lib")
path = work / "lib" / rel
mutated = apply(path.read_text(), line, col, old, new)
try:
ast.parse(mutated)
except SyntaxError:
return None
path.write_text(mutated)
res, _ = run_tests(work / "lib", tests, timeout, [subset[Path(rel).stem]] if subset else None)
if res is None:
return None
killed = sorted(k for k in passing if res.get(k) == "failed")
if not 1 <= len(killed) <= 8:
return None
fail = failure_text(work / "lib", killed[0], timeout)
return {"lib": name, "domain": domain, "file": rel, "line": line, "col": col, "old": old, "new": new,
"kind": kind, "function": func, "killed": killed, "failure": fail,
"tests_root": tests}
finally:
shutil.rmtree(work, ignore_errors=True)
kept = []
with ThreadPoolExecutor(workers) as pool:
for m in pool.map(try_one, cands):
if m and len(kept) < per_lib:
kept.append(m)
print(f"{name}: kept {len(kept)} mutants", flush=True)
return kept
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--per-lib", type=int, default=40)
ap.add_argument("--libs", default="")
ap.add_argument("--workers", type=int, default=4)
args = ap.parse_args()
out_dir = Path("/out")
out_dir.mkdir(exist_ok=True)
catalog_path = out_dir / "catalog.json"
catalog = json.loads(catalog_path.read_text()) if catalog_path.exists() else []
names = [n for n in LIBS if not args.libs or n in args.libs.split(",")]
catalog = [m for m in catalog if m["lib"] not in names]
for name in names:
catalog += build_lib(name, LIBS[name], args.per_lib, out_dir, args.workers)
catalog_path.write_text(json.dumps(catalog, indent=1))
shutil.rmtree(out_dir / "_extract", ignore_errors=True)
print("total mutants:", len(catalog))
if __name__ == "__main__":
main()