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 dataclasses
180import importlib
181import json
182import math
183import os
184import sys
185import time
186
187BIG = 2 ** 53
188
189
190def enc(v, stack=()):
191    if v is None or isinstance(v, (bool, str)):
192        return v
193    if isinstance(v, int):
194        return v if -BIG <= v <= BIG else {"$int": str(v)}
195    if isinstance(v, float):
196        if math.isnan(v):
197            return {"$num": "NaN"}
198        if math.isinf(v):
199            return {"$num": "Infinity" if v > 0 else "-Infinity"}
200        if v == 0 and math.copysign(1, v) < 0:
201            return {"$num": "-0"}
202        # 1.0 and 1 are different Python values: keep floats distinguishable.
203        return {"$float": repr(v)} if v.is_integer() else v
204    if any(v is s for s in stack):
205        return {"$cycle": True}
206    stack = stack + (v,)
207    if isinstance(v, list):
208        return [enc(x, stack) for x in v]
209    if isinstance(v, tuple):
210        return {"$tuple": [enc(x, stack) for x in v]}
211    if isinstance(v, (set, frozenset)):
212        return {"$set": sorted((enc(x, stack) for x in v), key=json.dumps)}
213    if isinstance(v, (bytes, bytearray)):
214        return {"$bytes": list(v)}
215    if isinstance(v, dict):
216        if all(isinstance(k, str) for k in v):
217            return {k: enc(x, stack) for k, x in v.items()}
218        return {"$dict": [[enc(k, stack), enc(x, stack)] for k, x in v.items()]}
219    if hasattr(v, "__dict__"):
220        return {"$object": type(v).__name__, "attrs": enc(vars(v), stack)}
221    return {"$repr": type(v).__name__}
222
223
224def dec(v):
225    if isinstance(v, list):
226        return [dec(x) for x in v]
227    if not isinstance(v, dict):
228        return v
229    if len(v) == 1:
230        (key, inner), = v.items()
231        if key == "$undefined":
232            return None
233        if key == "$num":
234            return {"NaN": math.nan, "Infinity": math.inf, "-Infinity": -math.inf, "-0": -0.0}[inner]
235        if key == "$float":
236            return float(inner)
237        if key == "$int":
238            return int(inner)
239        if key == "$tuple":
240            return tuple(dec(x) for x in inner)
241        if key == "$set":
242            return {dec(x) for x in inner}
243        if key == "$bytes":
244            return bytes(inner)
245        if key == "$dict":
246            return {dec(k): dec(x) for k, x in inner}
247    if set(v) == {"$object", "attrs"} and isinstance(v["attrs"], dict):
248        cls = dataclass_named(v["$object"])
249        if cls is not None:
250            return cls(**{k: dec(x) for k, x in v["attrs"].items()})
251    return {k: dec(x) for k, x in v.items()}
252
253
254def dataclass_named(name):
255    """A dataclass the loaded modules define, for building a recorded `$object` argument."""
256    for module in list(sys.modules.values()):
257        cls = getattr(module, name, None)
258        if isinstance(cls, type) and dataclasses.is_dataclass(cls):
259            return cls
260    return None
261
262
263def canon(v, sort):
264    return json.dumps(v, sort_keys=sort, ensure_ascii=False)
265
266
267def load(path):
268    """Imports a source file with its package context, so relative imports work."""
269    path = os.path.abspath(path)
270    directory, filename = os.path.split(path)
271    parts = [os.path.splitext(filename)[0]]
272    while os.path.exists(os.path.join(directory, "__init__.py")):
273        directory, package = os.path.split(directory)
274        parts.insert(0, package)
275    if parts[-1] == "__init__":
276        parts.pop()
277    if directory not in sys.path:
278        sys.path.insert(0, directory)
279    return importlib.import_module(".".join(parts))
280
281
282def error_text(e):
283    return f"{type(e).__name__}: {e}"
284
285
286def call_args(args):
287    """Trailing `undefined` arguments are omitted, so Python defaults apply."""
288    args = list(args)
289    while args and args[-1] == {"$undefined": True}:
290        args.pop()
291    return [dec(a) for a in args]
292
293
294def run_case(mod, c):
295    if c.get("class"):
296        cls = getattr(mod, c["class"])
297        results = []
298        try:
299            instance = cls(*call_args(c["ctor"]))
300            results.append({"ok": True})
301        except (KeyboardInterrupt, SystemExit):
302            raise
303        except BaseException as e:  # noqa: BLE001
304            results.append({"error": error_text(e)})
305            return {"results": results}
306        for call in c["calls"]:
307            try:
308                results.append({"ok": enc(getattr(instance, call["method"])(*call_args(call["args"])))})
309            except (KeyboardInterrupt, SystemExit):
310                raise
311            except BaseException as e:  # noqa: BLE001
312                results.append({"error": error_text(e)})
313        return {"results": results}
314    kwargs = {k: dec(v) for k, v in c.get("kwargs", {}).items()}
315    try:
316        return {"ok": enc(getattr(mod, c["fn"])(*call_args(c["args"]), **kwargs))}
317    except (KeyboardInterrupt, SystemExit):
318        raise
319    except BaseException as e:  # noqa: BLE001
320        return {"error": error_text(e)}
321
322
323def record(inputs_path, out_path):
324    cases = json.load(open(inputs_path, encoding="utf-8"))
325    modules = {}
326    with open(out_path, "w", encoding="utf-8") as out:
327        for c in cases:
328            if c["module"] not in modules:
329                modules[c["module"]] = load(c["module"])
330            result = run_case(modules[c["module"]], c)
331            line = {k: c[k] for k in ("fn", "class", "ctor", "calls", "args", "kwargs") if k in c}
332            line.update(result)
333            out.write(json.dumps(line, ensure_ascii=False) + "\n")
334
335
336def native(package_dir, name):
337    sys.path.insert(0, package_dir)
338    return importlib.import_module(name)
339
340
341def error_type(text):
342    return text.split(":", 1)[0]
343
344
345def same(expected, actual, sort):
346    """Exception types are part of a Python contract and must match; a Rust `TypeError` means
347    the bindings rejected the arguments, which agrees with any error from the original."""
348    if "error" in expected or "error" in actual:
349        if not ("error" in expected and "error" in actual):
350            return False
351        return error_type(actual["error"]) in (error_type(expected["error"]), "TypeError")
352    return canon(expected.get("ok"), sort) == canon(actual.get("ok"), sort)
353
354
355def diff(cases_path, out_path, package_dir, name, key_order):
356    mod = native(package_dir, name)
357    sort = key_order == "sort"
358    summary = {"total": 0, "passed": 0, "failed": 0, "missing": [], "mismatches": []}
359    for line in open(cases_path, encoding="utf-8"):
360        if not line.strip():
361            continue
362        c = json.loads(line)
363        summary["total"] += 1
364        name_ = c.get("class") or c["fn"]
365        if not hasattr(mod, name_):
366            if name_ not in summary["missing"]:
367                summary["missing"].append(name_)
368            summary["failed"] += 1
369            continue
370        got = run_case(mod, c)
371        if c.get("class"):
372            want, have = c["results"], got["results"]
373            ok = len(want) == len(have) and all(same(w, h, sort) for w, h in zip(want, have))
374            expected, actual = want, have
375        else:
376            expected = {"error": c["error"]} if "error" in c else {"ok": c.get("ok")}
377            ok = same(expected, got, sort)
378            actual = got
379        if ok:
380            summary["passed"] += 1
381        else:
382            summary["failed"] += 1
383            summary["mismatches"].append({"fn": name_, "args": c.get("args", [c.get("ctor"), c.get("calls")]), "expected": expected, "actual": actual})
384    json.dump(summary, open(out_path, "w", encoding="utf-8"), ensure_ascii=False)
385
386
387def bench(cases_path, out_path, package_dir, name, modules_path, min_ms):
388    new = native(package_dir, name)
389    sources = json.load(open(modules_path, encoding="utf-8"))
390    groups = {}
391    for line in open(cases_path, encoding="utf-8"):
392        if line.strip():
393            c = json.loads(line)
394            groups.setdefault(c.get("class") or c["fn"], []).append(c)
395    rows = []
396    for key, cases in groups.items():
397        if key not in sources or not hasattr(new, key):
398            continue
399        old = load(sources[key])
400
401        def timed(mod):
402            if cases[0].get("class"):
403                def once():
404                    for c in cases:
405                        run_case(mod, c)
406            else:
407                # Arguments are decoded once: only the calls are timed.
408                fn = getattr(mod, key)
409                prepared = [(call_args(c["args"]), {k: dec(v) for k, v in c.get("kwargs", {}).items()}) for c in cases]
410
411                def once():
412                    for args, kwargs in prepared:
413                        try:
414                            fn(*args, **kwargs)
415                        except (KeyboardInterrupt, SystemExit):
416                            raise
417                        except BaseException:  # noqa: BLE001
418                            pass
419            once()
420            passes, start = 0, time.perf_counter()
421            while True:
422                once()
423                passes += 1
424                elapsed = time.perf_counter() - start
425                if elapsed * 1000 >= min_ms:
426                    return elapsed * 1e9 / (passes * len(cases))
427        original_ns, rust_ns = timed(old), timed(new)
428        label = f"class {key}" if cases[0].get("class") else key
429        rows.append({"fn": label, "cases": len(cases), "original_ns": original_ns, "rust_ns": rust_ns, "speedup": original_ns / rust_ns})
430    json.dump(rows, open(out_path, "w", encoding="utf-8"))
431
432
433if __name__ == "__main__":
434    mode, *rest = sys.argv[1:]
435    if mode == "record":
436        record(*rest)
437    elif mode == "diff":
438        diff(*rest)
439    elif mode == "bench":
440        bench(rest[0], rest[1], rest[2], rest[3], rest[4], int(rest[5]))
441"#;