Skip to main content

rust_anything/
harness_py.rs

1//! The Python side of record, build, diff and bench: same cases, same markers, run by a
2//! Python driver instead of Node.
3
4use std::path::{Path, PathBuf};
5use std::process::Command;
6
7use anyhow::{Context, Result, bail};
8use serde_json::Value;
9
10use crate::bridge::Manifest;
11use crate::harness::{BenchRow, CASES, DiffOutcome};
12
13const WORK_DIR: &str = ".rust-anything";
14
15fn python() -> &'static str {
16    if Command::new("python3").arg("--version").output().is_ok() {
17        "python3"
18    } else {
19        "python"
20    }
21}
22
23fn run(cmd: &mut Command) -> Result<()> {
24    let output = cmd.output().context("running python")?;
25    if !output.status.success() {
26        let stderr = String::from_utf8_lossy(&output.stderr);
27        let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
28        bail!(
29            "python failed ({}):\n{}",
30            output.status,
31            tail.into_iter().rev().collect::<Vec<_>>().join("\n")
32        );
33    }
34    Ok(())
35}
36
37fn driver(crate_dir: &Path) -> Result<PathBuf> {
38    let work = crate_dir.join(WORK_DIR);
39    std::fs::create_dir_all(&work)?;
40    let path = work.join("driver.py");
41    std::fs::write(&path, DRIVER_PY)?;
42    Ok(path)
43}
44
45/// The folder the wrapper package lives in, and the package name.
46pub fn package(crate_dir: &Path, manifest: &Manifest) -> (PathBuf, String) {
47    (crate_dir.join("python"), manifest.lib_name())
48}
49
50pub fn record(crate_dir: &Path, cases: &[Value]) -> Result<PathBuf> {
51    let driver = driver(crate_dir)?;
52    let inputs = crate_dir.join(WORK_DIR).join("inputs.json");
53    std::fs::write(&inputs, serde_json::to_string(cases)?)?;
54    let out = crate_dir.join(CASES);
55    run(Command::new(python())
56        .arg(&driver)
57        .arg("record")
58        .arg(&inputs)
59        .arg(&out)
60        .env("PYTHONHASHSEED", "0")
61        // Recording must not leave `__pycache__` folders in the source tree.
62        .env("PYTHONDONTWRITEBYTECODE", "1"))?;
63    Ok(out)
64}
65
66pub fn build(crate_dir: &Path, manifest: &Manifest) -> Result<PathBuf> {
67    let target = crate_dir.join("target");
68    let output = Command::new("cargo")
69        .args(["build", "--release", "--manifest-path"])
70        .arg(crate_dir.join("Cargo.toml"))
71        .env("CARGO_TARGET_DIR", &target)
72        .output()
73        .context("running cargo build")?;
74    if !output.status.success() {
75        bail!(
76            "cargo build failed:\n{}",
77            String::from_utf8_lossy(&output.stderr)
78        );
79    }
80    let lib = manifest.lib_name();
81    let release = target.join("release");
82    let built = [
83        format!("lib{lib}.so"),
84        format!("lib{lib}.dylib"),
85        format!("{lib}.dll"),
86    ]
87    .iter()
88    .map(|n| release.join(n))
89    .find(|p| p.exists())
90    .with_context(|| format!("no extension module for `{lib}` in {}", release.display()))?;
91    let (dir, name) = package(crate_dir, manifest);
92    let package_dir = dir.join(&name);
93    std::fs::create_dir_all(&package_dir)?;
94    crate::harness::install(&built, &native_file(crate_dir, manifest))?;
95    Ok(package_dir)
96}
97
98/// The built extension module inside the Python package.
99pub(crate) fn native_file(crate_dir: &Path, manifest: &Manifest) -> PathBuf {
100    let (dir, name) = package(crate_dir, manifest);
101    dir.join(name).join(if cfg!(windows) {
102        "_native.pyd"
103    } else {
104        "_native.abi3.so"
105    })
106}
107
108pub fn diff(crate_dir: &Path, manifest: &Manifest, ignore_key_order: bool) -> Result<DiffOutcome> {
109    let cases = crate_dir.join(CASES);
110    if !cases.exists() {
111        bail!(
112            "no {CASES} in {} (run `rust-anything record` first)",
113            crate_dir.display()
114        );
115    }
116    let driver = driver(crate_dir)?;
117    let (dir, name) = package(crate_dir, manifest);
118    let out = crate_dir.join(WORK_DIR).join("diff.json");
119    run(Command::new(python())
120        .arg(&driver)
121        .arg("diff")
122        .arg(&cases)
123        .arg(&out)
124        .arg(dir)
125        .arg(name)
126        .arg(if ignore_key_order { "sort" } else { "keep" })
127        .env("PYTHONHASHSEED", "0")
128        // Recording must not leave `__pycache__` folders in the source tree.
129        .env("PYTHONDONTWRITEBYTECODE", "1"))?;
130    Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
131}
132
133pub fn bench(crate_dir: &Path, manifest: &Manifest, min_ms: u64) -> Result<Vec<BenchRow>> {
134    let cases = crate_dir.join(CASES);
135    if !cases.exists() {
136        bail!(
137            "no {CASES} in {} (run `rust-anything record` first)",
138            crate_dir.display()
139        );
140    }
141    let driver = driver(crate_dir)?;
142    let (dir, name) = package(crate_dir, manifest);
143    let modules: serde_json::Map<String, Value> = manifest
144        .exports
145        .iter()
146        .map(|f| {
147            (
148                f.name.clone(),
149                Value::String(manifest.root.join(&f.file).to_string_lossy().into_owned()),
150            )
151        })
152        .chain(manifest.classes.iter().map(|c| {
153            (
154                c.name.clone(),
155                Value::String(manifest.root.join(&c.file).to_string_lossy().into_owned()),
156            )
157        }))
158        .collect();
159    let modules_path = crate_dir.join(WORK_DIR).join("bench-modules.json");
160    std::fs::write(&modules_path, serde_json::to_string(&modules)?)?;
161    let out = crate_dir.join(WORK_DIR).join("bench.json");
162    run(Command::new(python())
163        .arg(&driver)
164        .arg("bench")
165        .arg(&cases)
166        .arg(&out)
167        .arg(dir)
168        .arg(name)
169        .arg(&modules_path)
170        .arg(min_ms.to_string())
171        .env("PYTHONHASHSEED", "0")
172        // Recording must not leave `__pycache__` folders in the source tree.
173        .env("PYTHONDONTWRITEBYTECODE", "1"))?;
174    Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
175}
176
177/// record / diff / bench for Python. Cases and markers match the Node scripts.
178pub const DRIVER_PY: &str = r#"
179import importlib
180import json
181import math
182import os
183import sys
184import time
185
186BIG = 2 ** 53
187
188
189def enc(v, stack=()):
190    if v is None or isinstance(v, (bool, str)):
191        return v
192    if isinstance(v, int):
193        return v if -BIG <= v <= BIG else {"$int": str(v)}
194    if isinstance(v, float):
195        if math.isnan(v):
196            return {"$num": "NaN"}
197        if math.isinf(v):
198            return {"$num": "Infinity" if v > 0 else "-Infinity"}
199        if v == 0 and math.copysign(1, v) < 0:
200            return {"$num": "-0"}
201        # 1.0 and 1 are different Python values: keep floats distinguishable.
202        return {"$float": repr(v)} if v.is_integer() else v
203    if any(v is s for s in stack):
204        return {"$cycle": True}
205    stack = stack + (v,)
206    if isinstance(v, list):
207        return [enc(x, stack) for x in v]
208    if isinstance(v, tuple):
209        return {"$tuple": [enc(x, stack) for x in v]}
210    if isinstance(v, (set, frozenset)):
211        return {"$set": sorted((enc(x, stack) for x in v), key=json.dumps)}
212    if isinstance(v, (bytes, bytearray)):
213        return {"$bytes": list(v)}
214    if isinstance(v, dict):
215        if all(isinstance(k, str) for k in v):
216            return {k: enc(x, stack) for k, x in v.items()}
217        return {"$dict": [[enc(k, stack), enc(x, stack)] for k, x in v.items()]}
218    if hasattr(v, "__dict__"):
219        return {"$object": type(v).__name__, "attrs": enc(vars(v), stack)}
220    return {"$repr": type(v).__name__}
221
222
223def dec(v):
224    if isinstance(v, list):
225        return [dec(x) for x in v]
226    if not isinstance(v, dict):
227        return v
228    if len(v) == 1:
229        (key, inner), = v.items()
230        if key == "$undefined":
231            return None
232        if key == "$num":
233            return {"NaN": math.nan, "Infinity": math.inf, "-Infinity": -math.inf, "-0": -0.0}[inner]
234        if key == "$float":
235            return float(inner)
236        if key == "$int":
237            return int(inner)
238        if key == "$tuple":
239            return tuple(dec(x) for x in inner)
240        if key == "$set":
241            return {dec(x) for x in inner}
242        if key == "$bytes":
243            return bytes(inner)
244        if key == "$dict":
245            return {dec(k): dec(x) for k, x in inner}
246    return {k: dec(x) for k, x in v.items()}
247
248
249def canon(v, sort):
250    return json.dumps(v, sort_keys=sort, ensure_ascii=False)
251
252
253def load(path):
254    """Imports a source file with its package context, so relative imports work."""
255    path = os.path.abspath(path)
256    directory, filename = os.path.split(path)
257    parts = [os.path.splitext(filename)[0]]
258    while os.path.exists(os.path.join(directory, "__init__.py")):
259        directory, package = os.path.split(directory)
260        parts.insert(0, package)
261    if parts[-1] == "__init__":
262        parts.pop()
263    if directory not in sys.path:
264        sys.path.insert(0, directory)
265    return importlib.import_module(".".join(parts))
266
267
268def error_text(e):
269    return f"{type(e).__name__}: {e}"
270
271
272def call_args(args):
273    """Trailing `undefined` arguments are omitted, so Python defaults apply."""
274    args = list(args)
275    while args and args[-1] == {"$undefined": True}:
276        args.pop()
277    return [dec(a) for a in args]
278
279
280def run_case(mod, c):
281    if c.get("class"):
282        cls = getattr(mod, c["class"])
283        results = []
284        try:
285            instance = cls(*call_args(c["ctor"]))
286            results.append({"ok": True})
287        except (KeyboardInterrupt, SystemExit):
288            raise
289        except BaseException as e:  # noqa: BLE001
290            results.append({"error": error_text(e)})
291            return {"results": results}
292        for call in c["calls"]:
293            try:
294                results.append({"ok": enc(getattr(instance, call["method"])(*call_args(call["args"])))})
295            except (KeyboardInterrupt, SystemExit):
296                raise
297            except BaseException as e:  # noqa: BLE001
298                results.append({"error": error_text(e)})
299        return {"results": results}
300    kwargs = {k: dec(v) for k, v in c.get("kwargs", {}).items()}
301    try:
302        return {"ok": enc(getattr(mod, c["fn"])(*call_args(c["args"]), **kwargs))}
303    except (KeyboardInterrupt, SystemExit):
304        raise
305    except BaseException as e:  # noqa: BLE001
306        return {"error": error_text(e)}
307
308
309def record(inputs_path, out_path):
310    cases = json.load(open(inputs_path, encoding="utf-8"))
311    modules = {}
312    with open(out_path, "w", encoding="utf-8") as out:
313        for c in cases:
314            if c["module"] not in modules:
315                modules[c["module"]] = load(c["module"])
316            result = run_case(modules[c["module"]], c)
317            line = {k: c[k] for k in ("fn", "class", "ctor", "calls", "args", "kwargs") if k in c}
318            line.update(result)
319            out.write(json.dumps(line, ensure_ascii=False) + "\n")
320
321
322def native(package_dir, name):
323    sys.path.insert(0, package_dir)
324    return importlib.import_module(name)
325
326
327def error_type(text):
328    return text.split(":", 1)[0]
329
330
331def same(expected, actual, sort):
332    """Exception types are part of a Python contract and must match; a Rust `TypeError` means
333    the bindings rejected the arguments, which agrees with any error from the original."""
334    if "error" in expected or "error" in actual:
335        if not ("error" in expected and "error" in actual):
336            return False
337        return error_type(actual["error"]) in (error_type(expected["error"]), "TypeError")
338    return canon(expected.get("ok"), sort) == canon(actual.get("ok"), sort)
339
340
341def diff(cases_path, out_path, package_dir, name, key_order):
342    mod = native(package_dir, name)
343    sort = key_order == "sort"
344    summary = {"total": 0, "passed": 0, "failed": 0, "missing": [], "mismatches": []}
345    for line in open(cases_path, encoding="utf-8"):
346        if not line.strip():
347            continue
348        c = json.loads(line)
349        summary["total"] += 1
350        name_ = c.get("class") or c["fn"]
351        if not hasattr(mod, name_):
352            if name_ not in summary["missing"]:
353                summary["missing"].append(name_)
354            summary["failed"] += 1
355            continue
356        got = run_case(mod, c)
357        if c.get("class"):
358            want, have = c["results"], got["results"]
359            ok = len(want) == len(have) and all(same(w, h, sort) for w, h in zip(want, have))
360            expected, actual = want, have
361        else:
362            expected = {"error": c["error"]} if "error" in c else {"ok": c.get("ok")}
363            ok = same(expected, got, sort)
364            actual = got
365        if ok:
366            summary["passed"] += 1
367        else:
368            summary["failed"] += 1
369            summary["mismatches"].append({"fn": name_, "args": c.get("args", [c.get("ctor"), c.get("calls")]), "expected": expected, "actual": actual})
370    json.dump(summary, open(out_path, "w", encoding="utf-8"), ensure_ascii=False)
371
372
373def bench(cases_path, out_path, package_dir, name, modules_path, min_ms):
374    new = native(package_dir, name)
375    sources = json.load(open(modules_path, encoding="utf-8"))
376    groups = {}
377    for line in open(cases_path, encoding="utf-8"):
378        if line.strip():
379            c = json.loads(line)
380            groups.setdefault(c.get("class") or c["fn"], []).append(c)
381    rows = []
382    for key, cases in groups.items():
383        if key not in sources or not hasattr(new, key):
384            continue
385        old = load(sources[key])
386
387        def timed(mod):
388            if cases[0].get("class"):
389                def once():
390                    for c in cases:
391                        run_case(mod, c)
392            else:
393                # Arguments are decoded once: only the calls are timed.
394                fn = getattr(mod, key)
395                prepared = [(call_args(c["args"]), {k: dec(v) for k, v in c.get("kwargs", {}).items()}) for c in cases]
396
397                def once():
398                    for args, kwargs in prepared:
399                        try:
400                            fn(*args, **kwargs)
401                        except (KeyboardInterrupt, SystemExit):
402                            raise
403                        except BaseException:  # noqa: BLE001
404                            pass
405            once()
406            passes, start = 0, time.perf_counter()
407            while True:
408                once()
409                passes += 1
410                elapsed = time.perf_counter() - start
411                if elapsed * 1000 >= min_ms:
412                    return elapsed * 1e9 / (passes * len(cases))
413        original_ns, rust_ns = timed(old), timed(new)
414        label = f"class {key}" if cases[0].get("class") else key
415        rows.append({"fn": label, "cases": len(cases), "original_ns": original_ns, "rust_ns": rust_ns, "speedup": original_ns / rust_ns})
416    json.dump(rows, open(out_path, "w", encoding="utf-8"))
417
418
419if __name__ == "__main__":
420    mode, *rest = sys.argv[1:]
421    if mode == "record":
422        record(*rest)
423    elif mode == "diff":
424        diff(*rest)
425    elif mode == "bench":
426        bench(rest[0], rest[1], rest[2], rest[3], rest[4], int(rest[5]))
427"#;