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