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 _scratch = crate::harness::scratch_cwd(cmd)?;
29    let output = cmd.output().context("running python")?;
30    if !output.status.success() {
31        let stderr = String::from_utf8_lossy(&output.stderr);
32        let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
33        bail!(
34            "python failed ({}):\n{}",
35            output.status,
36            tail.into_iter().rev().collect::<Vec<_>>().join("\n")
37        );
38    }
39    Ok(())
40}
41
42fn driver(crate_dir: &Path) -> Result<PathBuf> {
43    let work = crate_dir.join(WORK_DIR);
44    std::fs::create_dir_all(&work)?;
45    let path = work.join("driver.py");
46    std::fs::write(&path, DRIVER_PY)?;
47    Ok(path)
48}
49
50/// The unit's source files, written as a JSON list for the driver (a file, not an argument: any path
51/// survives, and a large unit cannot outgrow the command line): their packages stay importable during
52/// `diff`.
53fn source_files(crate_dir: &Path, manifest: &Manifest) -> Result<PathBuf> {
54    let files: std::collections::BTreeSet<&str> = manifest
55        .exports
56        .iter()
57        .map(|f| f.file.as_str())
58        .chain(manifest.classes.iter().map(|c| c.file.as_str()))
59        .collect();
60    let paths: Vec<String> = files
61        .into_iter()
62        .map(|f| manifest.root.join(f).to_string_lossy().into_owned())
63        .collect();
64    let path = crate_dir.join(WORK_DIR).join("diff-sources.json");
65    std::fs::write(&path, serde_json::to_string(&paths)?)?;
66    Ok(path)
67}
68
69/// The folder the wrapper package lives in, and the package name.
70pub fn package(crate_dir: &Path, manifest: &Manifest) -> (PathBuf, String) {
71    (crate_dir.join("python"), manifest.lib_name())
72}
73
74pub fn record(crate_dir: &Path, cases: &[Value]) -> Result<PathBuf> {
75    let driver = driver(crate_dir)?;
76    let out = crate_dir.join(CASES);
77    crate::harness::record_cases(
78        cases,
79        &crate_dir.join(WORK_DIR),
80        &out,
81        "python",
82        |inputs, part| {
83            let mut cmd = Command::new(python());
84            cmd.arg(&driver)
85                .arg("record")
86                .arg(inputs)
87                .arg(part)
88                .env("PYTHONHASHSEED", "0")
89                // Recording must not leave `__pycache__` folders in the source tree.
90                .env("PYTHONDONTWRITEBYTECODE", "1");
91            crate::pin::apply(&mut cmd, crate_dir)?;
92            crate::enable::original_only(&mut cmd, &Manifest::load(crate_dir)?);
93            Ok(cmd)
94        },
95    )?;
96    Ok(out)
97}
98
99pub fn build(crate_dir: &Path, manifest: &Manifest) -> Result<PathBuf> {
100    let target = crate::cache::target_for(crate_dir)?.dir;
101    let output = Command::new("cargo")
102        .args(["build", "--release", "--manifest-path"])
103        .arg(crate_dir.join("Cargo.toml"))
104        .env("CARGO_TARGET_DIR", &target)
105        .output()
106        .context("running cargo build")?;
107    if !output.status.success() {
108        bail!(
109            "cargo build failed:\n{}",
110            String::from_utf8_lossy(&output.stderr)
111        );
112    }
113    let lib = manifest.lib_name();
114    let release = target.join("release");
115    let built = [
116        format!("lib{lib}.so"),
117        format!("lib{lib}.dylib"),
118        format!("{lib}.dll"),
119    ]
120    .iter()
121    .map(|n| release.join(n))
122    .find(|p| p.exists())
123    .with_context(|| format!("no extension module for `{lib}` in {}", release.display()))?;
124    let (dir, name) = package(crate_dir, manifest);
125    let package_dir = dir.join(&name);
126    std::fs::create_dir_all(&package_dir)?;
127    crate::harness::install(&built, &native_file(crate_dir, manifest))?;
128    Ok(package_dir)
129}
130
131/// The built extension module inside the Python package.
132pub(crate) fn native_file(crate_dir: &Path, manifest: &Manifest) -> PathBuf {
133    let (dir, name) = package(crate_dir, manifest);
134    dir.join(name).join(if cfg!(windows) {
135        "_native.pyd"
136    } else {
137        "_native.abi3.so"
138    })
139}
140
141pub fn diff(crate_dir: &Path, manifest: &Manifest, ignore_key_order: bool) -> Result<DiffOutcome> {
142    let cases = crate_dir.join(CASES);
143    if !cases.exists() {
144        bail!(
145            "no {CASES} in {} (run `rust-anything record` first)",
146            crate_dir.display()
147        );
148    }
149    let driver = driver(crate_dir)?;
150    let (dir, name) = package(crate_dir, manifest);
151    let out = crate_dir.join(WORK_DIR).join("diff.json");
152    let mut cmd = Command::new(python());
153    cmd.arg(&driver)
154        .arg("diff")
155        .arg(&cases)
156        .arg(&out)
157        .arg(dir)
158        .arg(name)
159        .arg(if ignore_key_order { "sort" } else { "keep" })
160        .arg(source_files(crate_dir, manifest)?)
161        .env("PYTHONHASHSEED", "0")
162        // Recording must not leave `__pycache__` folders in the source tree.
163        .env("PYTHONDONTWRITEBYTECODE", "1");
164    crate::pin::apply(&mut cmd, crate_dir)?;
165    crate::enable::original_only(&mut cmd, &Manifest::load(crate_dir)?);
166    run(&mut cmd)?;
167    Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
168}
169
170pub fn bench(crate_dir: &Path, manifest: &Manifest, min_ms: u64) -> Result<Vec<BenchRow>> {
171    let cases = crate_dir.join(CASES);
172    if !cases.exists() {
173        bail!(
174            "no {CASES} in {} (run `rust-anything record` first)",
175            crate_dir.display()
176        );
177    }
178    let driver = driver(crate_dir)?;
179    let (dir, name) = package(crate_dir, manifest);
180    let modules: serde_json::Map<String, Value> = manifest
181        .exports
182        .iter()
183        .map(|f| {
184            (
185                f.name.clone(),
186                Value::String(manifest.root.join(&f.file).to_string_lossy().into_owned()),
187            )
188        })
189        .chain(manifest.classes.iter().map(|c| {
190            (
191                c.name.clone(),
192                Value::String(manifest.root.join(&c.file).to_string_lossy().into_owned()),
193            )
194        }))
195        .collect();
196    let modules_path = crate_dir.join(WORK_DIR).join("bench-modules.json");
197    std::fs::write(&modules_path, serde_json::to_string(&modules)?)?;
198    let out = crate_dir.join(WORK_DIR).join("bench.json");
199    let mut cmd = Command::new(python());
200    crate::enable::original_only(&mut cmd, manifest);
201    run(cmd
202        .arg(&driver)
203        .arg("bench")
204        .arg(&cases)
205        .arg(&out)
206        .arg(dir)
207        .arg(name)
208        .arg(&modules_path)
209        .arg(min_ms.to_string())
210        .env("PYTHONHASHSEED", "0")
211        // Recording must not leave `__pycache__` folders in the source tree.
212        .env("PYTHONDONTWRITEBYTECODE", "1"))?;
213    Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
214}
215
216/// record / diff / bench for Python. Cases and markers match the Node scripts.
217pub const DRIVER_PY: &str = r#"
218import dataclasses
219import importlib
220import json
221import math
222import os
223import sys
224import time
225
226BIG = 2 ** 53
227
228
229def enc(v, stack=()):
230    if v is None or isinstance(v, (bool, str)):
231        return v
232    if isinstance(v, int):
233        return v if -BIG <= v <= BIG else {"$int": str(v)}
234    if isinstance(v, float):
235        if math.isnan(v):
236            return {"$num": "NaN"}
237        if math.isinf(v):
238            return {"$num": "Infinity" if v > 0 else "-Infinity"}
239        if v == 0 and math.copysign(1, v) < 0:
240            return {"$num": "-0"}
241        # 1.0 and 1 are different Python values: keep floats distinguishable. Through float.__repr__:
242        # a subclass (numpy.float64 under NumPy 2) has its own repr, "np.float64(0.0)", and float()
243        # would call its __float__.
244        return {"$float": float.__repr__(v)} if v.is_integer() else v
245    if any(v is s for s in stack):
246        return {"$cycle": True}
247    stack = stack + (v,)
248    if isinstance(v, list):
249        return [enc(x, stack) for x in v]
250    if isinstance(v, tuple):
251        return {"$tuple": [enc(x, stack) for x in v]}
252    if isinstance(v, (set, frozenset)):
253        return {"$set": sorted((enc(x, stack) for x in v), key=json.dumps)}
254    if isinstance(v, (bytes, bytearray, memoryview)):
255        return {"$bytes": list(bytes(v))}
256    if isinstance(v, dict):
257        if all(isinstance(k, str) for k in v):
258            return {k: enc(x, stack) for k, x in v.items()}
259        return {"$dict": [[enc(k, stack), enc(x, stack)] for k, x in v.items()]}
260    if hasattr(v, "__dict__"):
261        return {"$object": type(v).__name__, "attrs": enc(vars(v), stack)}
262    return {"$repr": type(v).__name__}
263
264
265def dec(v):
266    if isinstance(v, list):
267        return [dec(x) for x in v]
268    if not isinstance(v, dict):
269        return v
270    if len(v) == 1:
271        (key, inner), = v.items()
272        if key == "$undefined":
273            return None
274        if key == "$num":
275            return {"NaN": math.nan, "Infinity": math.inf, "-Infinity": -math.inf, "-0": -0.0}[inner]
276        if key == "$float":
277            return float(inner)
278        if key == "$int":
279            return int(inner)
280        if key == "$tuple":
281            return tuple(dec(x) for x in inner)
282        if key == "$set":
283            return {dec(x) for x in inner}
284        if key == "$bytes":
285            return bytes(inner)
286        if key == "$dict":
287            return {dec(k): dec(x) for k, x in inner}
288    if set(v) == {"$object", "attrs"} and isinstance(v["attrs"], dict):
289        cls = dataclass_named(v["$object"])
290        if cls is not None:
291            return cls(**{k: dec(x) for k, x in v["attrs"].items()})
292    return {k: dec(x) for k, x in v.items()}
293
294
295def dataclass_named(name):
296    """A dataclass the loaded modules define, for building a recorded `$object` argument."""
297    for module in list(sys.modules.values()):
298        cls = getattr(module, name, None)
299        if isinstance(cls, type) and dataclasses.is_dataclass(cls):
300            return cls
301    return None
302
303
304PIN_CASE = None
305
306
307def pin_clock():
308    """With RUST_ANYTHING_NOW_MS set: a fixed clock and mulberry32 behind `random`, restarted
309    from RUST_ANYTHING_SEED by PIN_CASE before each case (see rust-anything's `pinned.rs`)."""
310    global PIN_CASE
311    now = os.environ.get("RUST_ANYTHING_NOW_MS")
312    if now is None:
313        return
314    import datetime as dt
315    import random as rnd
316    now_ms = int(now)
317    seconds = now_ms / 1000
318    seed = int(os.environ.get("RUST_ANYTHING_SEED", "0")) & 0xFFFFFFFF
319    time.time = lambda: seconds
320    time.time_ns = lambda: now_ms * 1_000_000
321    base_datetime, base_date = dt.datetime, dt.date
322
323    def pinned_type(base, methods):
324        class Meta(type):
325            def __instancecheck__(cls, obj):
326                return isinstance(obj, base)
327
328            def __subclasscheck__(cls, sub):
329                return issubclass(sub, base)
330
331        pinned = Meta(base.__name__, (base,), {k: classmethod(f) for k, f in methods.items()})
332        pinned.__module__ = base.__module__
333        return pinned
334
335    dt.datetime = pinned_type(base_datetime, {
336        "now": lambda cls, tz=None: base_datetime.fromtimestamp(seconds, tz),
337        "utcnow": lambda cls: base_datetime.fromtimestamp(seconds, dt.timezone.utc).replace(tzinfo=None),
338        "today": lambda cls: base_datetime.fromtimestamp(seconds),
339    })
340    dt.date = pinned_type(base_date, {"today": lambda cls: base_date.fromtimestamp(seconds)})
341    state = [seed]
342
343    def next_u32():
344        s = (state[0] + 0x6D2B79F5) & 0xFFFFFFFF
345        state[0] = s
346        t = ((s ^ (s >> 15)) * (s | 1)) & 0xFFFFFFFF
347        t ^= (t + ((t ^ (t >> 7)) * (t | 61))) & 0xFFFFFFFF
348        return t ^ (t >> 14)
349
350    class Pinned(rnd.Random):
351        def seed(self, *args, **kwargs):
352            self.gauss_next = None
353
354        def random(self):
355            return next_u32() / 4294967296
356
357        def getrandbits(self, k):
358            if k < 0:
359                raise ValueError("number of bits must be non-negative")
360            out, shift = 0, 0
361            while k > 0:
362                r = next_u32()
363                if k < 32:
364                    r >>= 32 - k
365                out |= r << shift
366                shift += 32
367                k -= 32
368            return out
369
370    inst = Pinned()
371    for name in rnd.__all__:
372        if not isinstance(getattr(rnd, name, None), type) and callable(getattr(inst, name, None)):
373            setattr(rnd, name, getattr(inst, name))
374
375    def pin_case(index):
376        state[0] = seed
377        inst.gauss_next = None
378        os.environ["RUST_ANYTHING_CASE"] = str(index)
379
380    PIN_CASE = pin_case
381
382
383def canon(v, sort):
384    return json.dumps(v, sort_keys=sort, ensure_ascii=False)
385
386
387def import_root(path):
388    """The folder a source file is imported from, with its package context, and its module name."""
389    path = os.path.abspath(path)
390    directory, filename = os.path.split(path)
391    parts = [os.path.splitext(filename)[0]]
392    while os.path.exists(os.path.join(directory, "__init__.py")):
393        directory, package = os.path.split(directory)
394        parts.insert(0, package)
395    if parts[-1] == "__init__":
396        parts.pop()
397    return directory, ".".join(parts)
398
399
400def load(path):
401    """Imports a source file with its package context, so relative imports work."""
402    directory, module = import_root(path)
403    if directory not in sys.path:
404        sys.path.insert(0, directory)
405    return importlib.import_module(module)
406
407
408def error_text(e):
409    return f"{type(e).__name__}: {e}"
410
411
412def call_args(args):
413    """Trailing `undefined` arguments are omitted, so Python defaults apply."""
414    args = list(args)
415    while args and args[-1] == {"$undefined": True}:
416        args.pop()
417    return [dec(a) for a in args]
418
419
420def binding_name(name):
421    """The name the Rust bindings give a parameter: `bridge::snake_case`, without `r#`."""
422    out = []
423    for i, ch in enumerate(name):
424        if ch.isupper():
425            prev = name[i - 1] if i else ""
426            nxt = name[i + 1:i + 2]
427            if prev and (prev.islower() or "0" <= prev <= "9") or (prev.isupper() and nxt.islower()):
428                out.append("_")
429            out.append(ch.lower())
430        else:
431            out.append(ch if ch.isalnum() else "_")
432    return "".join(out)
433
434
435def call_kwargs(c, rename=None):
436    """Keyword arguments by their names in the original, or in the bindings with `rename`."""
437    return {(rename(k) if rename else k): dec(v) for k, v in c.get("kwargs", {}).items()}
438
439
440def shown_args(c):
441    """A case's arguments as mismatches show them: keyword arguments appended, as Ruby does."""
442    if c.get("class"):
443        return [c.get("ctor"), c.get("calls")]
444    return c["args"] + [c["kwargs"]] if c.get("kwargs") else c["args"]
445
446
447def run_case(mod, c, rename=None):
448    if c.get("class"):
449        cls = getattr(mod, c["class"])
450        results = []
451        try:
452            instance = cls(*call_args(c["ctor"]))
453            results.append({"ok": True})
454        except (KeyboardInterrupt, SystemExit):
455            raise
456        except BaseException as e:  # noqa: BLE001
457            results.append({"error": error_text(e)})
458            return {"results": results}
459        for call in c["calls"]:
460            try:
461                results.append({"ok": enc(getattr(instance, call["method"])(*call_args(call["args"])))})
462            except (KeyboardInterrupt, SystemExit):
463                raise
464            except BaseException as e:  # noqa: BLE001
465                results.append({"error": error_text(e)})
466        return {"results": results}
467    kwargs = call_kwargs(c, rename)
468    try:
469        return {"ok": enc(getattr(mod, c["fn"])(*call_args(c["args"]), **kwargs))}
470    except (KeyboardInterrupt, SystemExit):
471        raise
472    except BaseException as e:  # noqa: BLE001
473        return {"error": error_text(e)}
474
475
476def record(inputs_path, out_path):
477    cases = json.load(open(inputs_path, encoding="utf-8"))
478    modules = {}
479    progress = os.environ.get("RUST_ANYTHING_PROGRESS")
480    with open(out_path, "w", encoding="utf-8") as out:
481        for index, c in enumerate(cases):
482            if progress:
483                with open(progress, "a", encoding="utf-8") as p:
484                    p.write("%d\n" % index)
485            if c["module"] not in modules:
486                modules[c["module"]] = load(c["module"])
487            if PIN_CASE:
488                PIN_CASE(index)
489            result = run_case(modules[c["module"]], c)
490            line = {k: c[k] for k in ("fn", "class", "ctor", "calls", "args", "kwargs") if k in c}
491            line.update(result)
492            out.write(json.dumps(line, ensure_ascii=False) + "\n")
493            out.flush()
494
495
496def native(package_dir, name):
497    sys.path.insert(0, package_dir)
498    return importlib.import_module(name)
499
500
501def error_type(text):
502    return text.split(":", 1)[0]
503
504
505def same(expected, actual, sort):
506    """Exception types are part of a Python contract and must match; a Rust `TypeError` means
507    the bindings rejected the arguments, which agrees with any error from the original."""
508    if "error" in expected or "error" in actual:
509        if not ("error" in expected and "error" in actual):
510            return False
511        return error_type(actual["error"]) in (error_type(expected["error"]), "TypeError")
512    return canon(expected.get("ok"), sort) == canon(actual.get("ok"), sort)
513
514
515def diff(cases_path, out_path, package_dir, name, key_order, sources_path=None):
516    mod = native(package_dir, name)
517    # The original's packages stay importable, as they are in the app: a port raises the
518    # original's own exception classes by importing them (`Err("pkg.errors.Bad: ...")`).
519    sources = json.load(open(sources_path, encoding="utf-8")) if sources_path else []
520    for source in sources:
521        directory = import_root(source)[0]
522        if directory not in sys.path:
523            sys.path.insert(0, directory)
524    sort = key_order == "sort"
525    summary = {"total": 0, "passed": 0, "failed": 0, "missing": [], "mismatches": []}
526    for index, line in enumerate(open(cases_path, encoding="utf-8")):
527        if not line.strip():
528            continue
529        c = json.loads(line)
530        summary["total"] += 1
531        name_ = c.get("class") or c["fn"]
532        if not hasattr(mod, name_):
533            if name_ not in summary["missing"]:
534                summary["missing"].append(name_)
535            summary["failed"] += 1
536            continue
537        if PIN_CASE:
538            PIN_CASE(index)
539        got = run_case(mod, c, binding_name)
540        if c.get("class"):
541            want, have = c["results"], got["results"]
542            ok = len(want) == len(have) and all(same(w, h, sort) for w, h in zip(want, have))
543            expected, actual = want, have
544        else:
545            expected = {"error": c["error"]} if "error" in c else {"ok": c.get("ok")}
546            ok = same(expected, got, sort)
547            actual = got
548        if ok:
549            summary["passed"] += 1
550        else:
551            summary["failed"] += 1
552            summary["mismatches"].append({"fn": name_, "args": shown_args(c), "expected": expected, "actual": actual})
553    json.dump(summary, open(out_path, "w", encoding="utf-8"), ensure_ascii=False)
554
555
556def bench(cases_path, out_path, package_dir, name, modules_path, min_ms):
557    new = native(package_dir, name)
558    sources = json.load(open(modules_path, encoding="utf-8"))
559    groups = {}
560    for line in open(cases_path, encoding="utf-8"):
561        if line.strip():
562            c = json.loads(line)
563            groups.setdefault(c.get("class") or c["fn"], []).append(c)
564    rows = []
565    for key, cases in groups.items():
566        if key not in sources or not hasattr(new, key):
567            continue
568        old = load(sources[key])
569
570        def timed(mod, rename=None):
571            if cases[0].get("class"):
572                def once():
573                    for c in cases:
574                        run_case(mod, c, rename)
575            else:
576                # Arguments are decoded once: only the calls are timed.
577                fn = getattr(mod, key)
578                prepared = [(call_args(c["args"]), call_kwargs(c, rename)) for c in cases]
579
580                def once():
581                    for args, kwargs in prepared:
582                        try:
583                            fn(*args, **kwargs)
584                        except (KeyboardInterrupt, SystemExit):
585                            raise
586                        except BaseException:  # noqa: BLE001
587                            pass
588            once()
589            passes, start = 0, time.perf_counter()
590            while True:
591                once()
592                passes += 1
593                elapsed = time.perf_counter() - start
594                if elapsed * 1000 >= min_ms:
595                    return elapsed * 1e9 / (passes * len(cases))
596        original_ns, rust_ns = timed(old), timed(new, binding_name)
597        label = f"class {key}" if cases[0].get("class") else key
598        rows.append({"fn": label, "cases": len(cases), "original_ns": original_ns, "rust_ns": rust_ns, "speedup": original_ns / rust_ns})
599    json.dump(rows, open(out_path, "w", encoding="utf-8"))
600
601
602if __name__ == "__main__":
603    mode, *rest = sys.argv[1:]
604    pin_clock()
605    if mode == "record":
606        record(*rest)
607    elif mode == "diff":
608        diff(*rest)
609    elif mode == "bench":
610        bench(rest[0], rest[1], rest[2], rest[3], rest[4], int(rest[5]))
611"#;