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