Files
2026-11-27 06:03:56 +00:00

186 lines
11 KiB
Python

"""四方内核对照:固定 R0 旧版/Go,原 Rust 源码使用当前锁重建,构建当前三表源码。"""
import argparse
import json
import os
from pathlib import Path
import shutil
import statistics
import tomllib
from scale import execute, fingerprint
CASES = {
"integer": (16384, 65536), "float": (16384, 65536),
**{name: (512, 1024, 2048, 4096) for name in (
"list", "map", "list_read", "list_record", "list_record_read",
"record_update", "record_inspect", "call_read", "map_read", "map_lookup",
"map_text_lookup", "text_equal", "text_contains")},
"text_concat": (512, 2048, 8192, 32768),
"bytes_concat": (512, 2048, 8192, 32768),
}
for name in ("record_update", "record_inspect"):
CASES[name] += (16384, 65536)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--compiler", required=True, type=Path)
parser.add_argument("--baseline", required=True, type=Path, help="R0 kernel directory containing manifest.json")
parser.add_argument("--output", required=True, type=Path)
parser.add_argument("--previous", type=Path, help="same-contract prior candidate binary for interleaved comparison")
parser.add_argument("--earlier", type=Path, help="additional same-contract pre-regression Dever binary; retain the immediate previous candidate")
parser.add_argument("--project", type=Path, help="reuse the original formatted workload path without modifying its source")
parser.add_argument("--rust-reference", type=Path, help="reuse a previously built locked Rust peer without replacing its binary")
parser.add_argument("--aligned-rust-reference", type=Path, help="additional independent Rust peer with aligned optimizations; original Rust remains in the comparison")
parser.add_argument("--resource-rust-reference", type=Path, help="additional independent Rust peer aligning record input ownership, typed sample storage and monotonic clock API; retain original and algorithm-aligned peers")
parser.add_argument("--borrowed-text-rust-reference", type=Path, help="additional independent peer borrowing split Text pieces; retain all owned-piece references")
parser.add_argument("--argv0", help="use the same explicit process name for every measured binary; retain original-path measurements")
args = parser.parse_args()
core = Path(__file__).resolve().parents[2]
root = args.output.absolute()
root.mkdir(parents=True, exist_ok=False)
baseline = args.baseline.resolve(strict=True)
compiler = args.compiler.resolve(strict=True)
original = json.loads((baseline / "manifest.json").read_text())
binaries = {}
for name, artifact in original.items():
path = Path(artifact["path"])
assert fingerprint(path) == artifact["sha256"], f"R0 artifact changed: {name}"
binaries["old" if name == "dever" else name] = path
# 独立 Rust 仍不链接 Dever;不重写参考算法或更换较慢的依赖制造通过。
locked = {(p["name"], p["version"], p.get("source"))
for p in tomllib.loads((core / "rust/Cargo.lock").read_text())["package"]}
reference = root / "rust-reference"
reference.mkdir()
for name in ("main.rs", "Cargo.toml"):
shutil.copyfile(baseline / "rust-peer" / name, reference / name)
assert fingerprint(reference / "main.rs") == original["rust"]["source"]["sha256"]
rust_binary = args.rust_reference.resolve(strict=True) if args.rust_reference else None
if rust_binary:
peer = rust_binary.parents[2]
for name in ("main.rs", "Cargo.toml"):
assert fingerprint(peer / name) == fingerprint(reference / name)
shutil.copyfile(peer / "Cargo.lock", reference / "Cargo.lock")
else:
shutil.copyfile(core / "rust/Cargo.lock", reference / "Cargo.lock")
project = args.project.resolve(strict=True) if args.project else root / "project"
module = project / "module/benchmark/kernel"
if not args.project:
module.mkdir(parents=True)
for source in (Path(__file__).parent / "fixtures/kernel").iterdir():
shutil.copyfile(source, module / source.name)
report = dict(rounds=7, warmups=1, samples_per_process=10, cpu_affinity=[0],
contract="Same R0 input and checked checksum. Internal monotonic timing excludes preparation and final checksum. Each process emits ten raw samples; its first is retained but excluded from steady-state median. Process CPU/time also recorded. Kernel success paths only; no full application/error/ownership parity claim.",
baseline=original, compiler_sha256=fingerprint(compiler), builds=[], samples=[])
if args.argv0 is not None:
report["argv0"] = args.argv0
def save():
(root / "results.json").write_text(json.dumps(report, indent=2) + "\n")
binaries["new"] = root / "new"
if args.previous:
binaries["previous"] = args.previous.resolve(strict=True)
if args.earlier:
binaries["earlier"] = args.earlier.resolve(strict=True)
binaries["rust"] = rust_binary or reference / "target/release/kernel-peer"
for selected, binary_name, source_key in (
(args.aligned_rust_reference, "rust_aligned", "aligned_rust_reference"),
(args.resource_rust_reference, "rust_resource", "resource_rust_reference"),
(args.borrowed_text_rust_reference, "rust_text_borrowed", "borrowed_text_rust_reference"),
):
if selected is None:
continue
binary = selected.resolve(strict=True)
peer = binary.parents[2]
for name in ("Cargo.toml", "Cargo.lock"):
assert fingerprint(peer / name) == fingerprint(reference / name)
binaries[binary_name] = binary
report[source_key] = {
str(peer / name): fingerprint(peer / name)
for name in ("main.rs", "Cargo.toml", "Cargo.lock")}
commands = []
if not rust_binary:
commands.append(("rust-build", ["cargo", "+1.95.0", "build", "--offline", "--release",
"--manifest-path", str(reference / "Cargo.toml"),
"--target-dir", str(reference / "target")]))
commands += [("format", [str(compiler), "fmt", str(project)] + (["--check"] if args.project else [])),
("build", [str(compiler), "build", str(project), "--output", str(binaries["new"])])]
for label, command in commands:
row = execute(command, root, label, 900)
report["builds"].append(row)
save()
assert row["exit_code"] == 0, row
peer = tomllib.loads((reference / "Cargo.lock").read_text())["package"]
assert all(not p.get("source") or (p["name"], p["version"], p["source"]) in locked for p in peer)
report["rust_reference"] = dict(source_sha256=fingerprint(reference / "main.rs"),
lock_sha256=fingerprint(reference / "Cargo.lock"),
policy="Unchanged R0 Rust source/profile, current locked dependencies. Existing binary reused when explicitly selected; original R0 artifact retained in baseline.",
reused_binary=bool(rust_binary), reused_project=bool(args.project))
report["binaries"] = {name: dict(path=str(path), sha256=fingerprint(path), bytes=path.stat().st_size)
for name, path in binaries.items()}
inputs = [*core.joinpath("rust/src").rglob("*.rs"), *core.joinpath("lib").rglob("*.dv"),
*module.glob("*.dever"), Path(__file__), Path(__file__).with_name("scale.py")]
inputs += [Path(path) for path in report.get("aligned_rust_reference", {})]
inputs += [Path(path) for path in report.get("resource_rust_reference", {})]
inputs += [Path(path) for path in report.get("borrowed_text_rust_reference", {})]
report["sources"] = {str(p): fingerprint(p) for p in inputs}
report["business_sources"] = {
"new": [dict(path=str(p), lines=len(p.read_text().splitlines()), sha256=fingerprint(p)) for p in module.glob("*.dever")],
"old": [dict(path=str(p), lines=len(p.read_text().splitlines()), sha256=fingerprint(p)) for p in (baseline / "module").rglob("*.dever")],
"rust": dict(path=str(baseline / "rust-peer/main.rs"), lines=len((baseline / "rust-peer/main.rs").read_text().splitlines())),
"go": dict(path=original["go"]["source"]["path"], lines=len(Path(original["go"]["source"]["path"]).read_text().splitlines())),
}
os.sched_setaffinity(0, {0})
os.environ["GOMAXPROCS"] = "1"
names = ["new", "old", "rust", "go"]
if args.previous:
names.append("previous")
if args.earlier:
names.append("earlier")
if args.aligned_rust_reference:
names.append("rust_aligned")
if args.resource_rust_reference:
names.append("rust_resource")
if args.borrowed_text_rust_reference:
names.append("rust_text_borrowed")
for repeat in range(-1, 7):
assert all(fingerprint(Path(path)) == digest for path, digest in report["sources"].items())
for operation, sizes in CASES.items():
for count in sizes:
ticks = ",".join(["x"] * count) if operation == "text_concat" else "x" * count
for offset in range(len(names)):
name = names[(repeat + 1 + offset) % len(names)]
action = "continuous_" + operation
if name in ("old", "new", "previous", "earlier"):
action = "benchmark.kernel." + action
row = dict(name=name, operation=operation, count=count, repeat=repeat,
**execute([str(binaries[name]), action, json.dumps({"ticks": ticks})],
root, f"{repeat}-{operation}-{count}-{name}", 120, argv0=args.argv0))
value = json.loads(Path(row["stdout"]).read_text()) if row["exit_code"] == 0 else None
if name in ("old", "new", "previous", "earlier") and value is not None:
value = value["data"]
row["values"] = value
row["correct"] = isinstance(value, list) and len(value) == 10 and all(
v["checksum"] == count * 120 and v["elapsed_ns"] > 0 for v in value)
report["samples"].append(row)
if not row["correct"]:
save()
raise AssertionError(row)
# 原始输出逐进程落盘;每组汇总一次,避免反复重写不断增长的全部历史。
save()
print("round", repeat, "complete", flush=True)
report["medians"] = []
for operation, sizes in CASES.items():
for count in sizes:
item = dict(operation=operation, count=count, nanoseconds={})
for name in names:
rows = [r for r in report["samples"] if r["repeat"] >= 0 and r["name"] == name
and r["operation"] == operation and r["count"] == count]
item["nanoseconds"][name] = statistics.median(v["elapsed_ns"] for row in rows for v in row["values"][1:])
report["medians"].append(item)
save()
print(json.dumps(report["medians"], indent=2))
if __name__ == "__main__":
main()