"""真实外部 Worker 四方进程对照;固定后端,核对全部文本和干净退出。""" import argparse import json import os from pathlib import Path import shutil import statistics import tomllib from scale import execute, fingerprint def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--compiler", type=Path, required=True) parser.add_argument("--old-compiler", type=Path, required=True) parser.add_argument("--baseline-identity", type=Path, required=True) parser.add_argument("--worker", type=Path, required=True, help="precompiled test/rust/build/port/worker_fixture.rs.txt") parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() core = Path(__file__).resolve().parents[2] fixture = Path(__file__).parent / "fixtures/worker" root = args.output.absolute() root.mkdir(parents=True, exist_ok=False) baseline = json.loads(args.baseline_identity.read_text()) assert fingerprint(args.old_compiler) == baseline["original_compiler"]["sha256"] report = dict(rounds=7, warmups=1, cpu_affinity=[0], contract="One CMD decodes a required List, starts one real Worker, validates hello/ready and health, calls unit once, calls echo sequentially for every item, returns every complete text and waits for shutdown. One shared backend executable serves all four programs. New/old published programs execute after removing their source Worker image. Wall/CPU include process startup, protocol, result encoding and shutdown.", limitations="Bounded successful external-exec workload and CMD input rejection; not full Worker cancellation, restart limits, process descendants, schema-range failures or auth/tenant equivalence. Independent peers use a disk executable; Dever embeds its executable and owns Scope resources. Rust/Go do not link Dever runtime. Go uses blocking standard pipes; Rust uses Tokio framing/deadlines. Tail summaries describe a whole CMD, not individual calls. wait4 RSS can include inherited launcher memory.", baseline_identity=baseline, commands=[], functional=[], samples=[]) def save(): (root / "results.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n") def run(label, command): row = execute(list(map(str, command)), root, label, 1800) report["commands"].append(row) save() assert row["exit_code"] == 0, row return row worker = root / "worker-image" shutil.copyfile(args.worker, worker) worker.chmod(0o755) report["worker"] = dict(path=str(worker), sha256=fingerprint(worker), source_sha256=fingerprint(core / "test/rust/build/port/worker_fixture.rs.txt")) report["compilers"] = {} binaries = {} for name, compiler in [("new", args.compiler), ("old", args.old_compiler)]: compiler = compiler.resolve(strict=True) report["compilers"][name] = dict(path=str(compiler), sha256=fingerprint(compiler)) project = root / name domain = project / "module/benchmark/echo" domain.joinpath("bin").mkdir(parents=True) shutil.copyfile(worker, domain / "bin/worker") domain.joinpath("bin/worker").chmod(0o755) target = domain / ("app/main.dever" if name == "new" else "app.dever") target.parent.mkdir(exist_ok=True) shutil.copyfile(fixture / ("app.dever" if name == "new" else "old.dever.txt"), target) failure = " fails dever.api.Error" if name == "old" else "" domain.joinpath("port.dever").write_text( f"echo(value: Text) (out: Text){failure}\nunit() (){failure}\n") domain.joinpath("adapter.dever").write_text('external exec "bin/worker" {}\n') domain.joinpath("api.dever").write_text("cmd bench = app.batch\n") project.joinpath("config").mkdir() project.joinpath("config/setting.json").write_text("{}\n") run(name + "-fmt", [compiler, "fmt", project]) binaries[name] = root / (name + "-app") run(name + "-build", [compiler, "build", project, "--output", binaries[name]]) domain.joinpath("bin/worker").unlink() rust = root / "rust" rust.mkdir() shutil.copyfile(fixture / "peer.rs.txt", rust / "main.rs") shutil.copyfile(core / "rust/Cargo.lock", rust / "Cargo.lock") rust.joinpath("Cargo.toml").write_text('''[package] name = "worker-peer" version = "0.0.1" edition = "2024" [[bin]] name = "worker-peer" path = "main.rs" [dependencies] bytes = "=1.12.1" futures-util = { version = "=0.3.34", features = ["sink"] } tokio = { version = "=1.53.1", features = ["rt", "time", "process", "io-util"] } tokio-util = { version = "=0.7.19", features = ["codec"] } serde = { version = "=1.0.228", features = ["derive"] } serde_json = "=1.0.145" [profile.release] lto = "fat" codegen-units = 1 overflow-checks = true strip = true ''') run("rust-build", ["cargo", "+1.95.0", "build", "--offline", "--release", "--manifest-path", rust / "Cargo.toml", "--target-dir", rust / "target"]) locked = {(p["name"], p["version"]) for p in tomllib.loads((core / "rust/Cargo.lock").read_text())["package"]} assert all((p["name"], p["version"]) in locked for p in tomllib.loads((rust / "Cargo.lock").read_text())["package"] if "source" in p) binaries["rust"] = rust / "target/release/worker-peer" go = root / "go" go.mkdir() go.joinpath("go.mod").write_text("module worker-peer\n\ngo 1.25.0\n") shutil.copyfile(fixture / "peer.go.txt", go / "main.go") run("go-fmt", ["gofmt", "-w", go / "main.go"]) binaries["go"] = root / "go-app" run("go-build", ["go", "-C", go, "build", "-buildvcs=false", "-trimpath", "-ldflags=-s -w", "-o", binaries["go"], "."]) report["binaries"] = {name: dict(path=str(path), sha256=fingerprint(path), bytes=path.stat().st_size) for name, path in binaries.items()} sources = [Path(__file__), *fixture.iterdir(), core / "test/rust/build/port/worker_fixture.rs.txt", core / "rust/Cargo.toml", core / "rust/Cargo.lock", core / "rust/src/runtime/Cargo.toml", *core.joinpath("rust/src").rglob("*.rs"), *core.joinpath("lib").rglob("*.dv"), rust / "Cargo.toml", rust / "Cargo.lock", rust / "main.rs", go / "go.mod", go / "main.go"] sources += [p for name in ("new", "old") for p in root.joinpath(name, "module").rglob("*.dever")] report["sources"] = {str(p): fingerprint(p) for p in sources} report["source_lines"] = {str(p): len(p.read_text().splitlines()) for p in sources} snapshots = root / "sources" snapshots.mkdir() for index, path in enumerate(sources): shutil.copyfile(path, snapshots / f"{index}-{path.name}") for name, binary in binaries.items(): shutil.copyfile(binary, root / (name + "-binary")) save() def command(name, data): if name in ("new", "old"): return [str(binaries[name]), "benchmark.echo.bench", data] return [str(binaries[name]), str(worker), data] def checked(name, row, values): assert row["exit_code"] == 0 and not row["timeout"], row answer = json.loads(Path(row["stdout"]).read_text()) if name in ("new", "old"): assert answer["code"] == 0, answer answer = answer["data"] assert answer == values, (name, "returned content differs") row["checked"] = True invalid = ['{}', '{"values":null}', '{"values":[null]}', '{"values":[1]}', '{"values":[],"extra":1}', '{"values":[],"values":[]}', '{"values":[],"\\u0076alues":[]}'] for name in binaries: for index, data in enumerate(invalid): row = execute(command(name, data), root, f"{name}-invalid-{index}", 30) report["functional"].append(dict(implementation=name, case=index, **row)) save() assert row["exit_code"] != 0 and not row["timeout"], row assert Path(row["stderr"]).read_text().strip(), row report["functional"][-1]["checked"] = True cases = dict(empty=[], single=["雪🙂\u0000quote\"\\"], small=[f"{i}:" + "雪🙂" * 9 for i in range(512)], medium=[f"{i}:" + "雪🙂" * 146 for i in range(32)], large=["雪🙂" * 9362]) os.sched_setaffinity(0, {0}) os.environ["GOMAXPROCS"] = "1" names = list(binaries) for repeat in range(-1, 7): assert all(fingerprint(Path(p)) == digest for p, digest in report["sources"].items()) assert all(fingerprint(path) == report["binaries"][name]["sha256"] for name, path in binaries.items()) assert fingerprint(worker) == report["worker"]["sha256"] for case, values in cases.items(): data = json.dumps(dict(values=values), ensure_ascii=False) order = names[repeat % len(names):] + names[:repeat % len(names)] if repeat % 2: order = list(reversed(order)) for name in order: row = execute(command(name, data), root, f"{repeat}-{case}-{name}", 30) report["samples"].append(dict(implementation=name, case=case, repeat=repeat, **row)) save() checked(name, row, values) report["samples"][-1]["checked"] = True save() report["summary"] = {} for case in cases: report["summary"][case] = {} for name in names: rows = [r for r in report["samples"] if r["case"] == case and r["implementation"] == name and r["repeat"] >= 0] report["summary"][case][name] = dict(seconds=statistics.median(r["seconds"] for r in rows), cpu_seconds=statistics.median(r["user_cpu_seconds"] + r["system_cpu_seconds"] for r in rows)) save() print(json.dumps(dict(functional=len(report["functional"]), measured=len(report["samples"]), summary=report["summary"]))) if __name__ == "__main__": main()