Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -0,0 +1,260 @@
|
||||
"""固定规模的真实编译、执行和 inspect 基线,不清理共享缓存。"""
|
||||
|
||||
import argparse
|
||||
from collections import Counter
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import signal
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
|
||||
def fingerprint(path):
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def source(count, shape, changed=False, signature=False):
|
||||
if shape in ("owned", "deep"):
|
||||
# owned 的调用深度为 100,与真实项目同量级,是 30 秒门槛的正式输入;deep 保留 count 层单链作压力用例,
|
||||
# 因为 rustc 的内联环路检查随调用链深度平方增长,深链耗时不代表函数数量的成本(见 REMAINING.md)。
|
||||
depth = count if shape == "deep" else 100
|
||||
definitions = ["type Parcel {\n title: Text\n tags: List<Text>\n number: Int\n}"]
|
||||
for index in range(count - 1):
|
||||
arguments = "value: Parcel, extra: Int" if signature and index == 0 else "value: Parcel"
|
||||
if index == 0:
|
||||
increment = "extra" if signature else str(2 if changed else 1)
|
||||
body = f"length(value.title) + length(value.tags) + value.number + {increment}"
|
||||
else:
|
||||
# 每段的首个函数改调 step0,使所有段仍依赖同一个被修改的函数。
|
||||
callee = index - 1 if index % depth else 0
|
||||
call = "value, 1" if signature and callee == 0 else "value"
|
||||
body = f"step{callee}({call}) + 1"
|
||||
definitions.append(f"step{index}({arguments}) (answer: Int) {{ answer = {body} }}")
|
||||
heads = [min(start + depth, count - 1) - 1 for start in range(0, count - 1, depth)]
|
||||
terms = " + ".join(f"step{head}(parcel{', 1' if signature and head == 0 else ''})" for head in heads)
|
||||
definitions.append('main() (answer: Int) {\n parcel = Parcel { title = "hello", tags = ["one", "two"], number = 3 }\n'
|
||||
f" answer = {terms}\n}}")
|
||||
bottom = 10 + (1 if signature else 2 if changed else 1)
|
||||
expected = sum(bottom + head % depth + (1 if head >= depth else 0) for head in heads)
|
||||
return "\n\n".join(definitions) + "\n", expected
|
||||
if shape == "flow":
|
||||
# 与 linear 相同的调用链,改用唯一绑定的顺序表,检查表本身是否增加执行层。
|
||||
definitions = []
|
||||
for index in range(count - 1):
|
||||
arguments = "value: Int, extra: Int" if signature and index == 0 else "value: Int"
|
||||
rows = []
|
||||
if index == 0:
|
||||
increment = "extra" if signature else str(2 if changed else 1)
|
||||
rows.append(f"| answer | calc | value + {increment} |")
|
||||
else:
|
||||
call = "value, 1" if signature and index == 1 else "value"
|
||||
rows.extend([f"| previous | flow | step{index - 1}({call}) |", "| answer | calc | previous + 1 |"])
|
||||
definitions.append(f"flow step{index}({arguments}) (answer: Int)\n| step | kind | do |\n" + "\n".join(rows))
|
||||
call = "1, 1" if signature and count == 2 else "1"
|
||||
definitions.append(f"flow main() (answer: Int)\n| step | kind | do |\n| answer | flow | step{count - 2}({call}) |")
|
||||
return "\n\n".join(definitions) + "\n", count + int(changed)
|
||||
if shape == "handler":
|
||||
extra = ", offset: Int" if signature else ""
|
||||
result = "transform(value) + offset" if signature else "transform(value)"
|
||||
definitions = [f"apply(value: Int, transform: handler(value: Int) (answer: Int){extra}) (answer: Int) {{ answer = {result} }}"]
|
||||
for index in range(count - 2):
|
||||
increment = 2 if changed and index == 0 else 1
|
||||
definitions.append(f"step{index}(value: Int) (answer: Int) {{ answer = value + {increment} }}")
|
||||
lines = ["main() (answer: Int) {", " answer = 0"]
|
||||
for index in range(count - 2):
|
||||
arguments = f"1, step{index}, 0" if signature else f"1, step{index}"
|
||||
lines.append(f" answer = answer + apply({arguments})")
|
||||
definitions.append("\n".join(lines + ["}"]))
|
||||
return "\n\n".join(definitions) + "\n", 2 * (count - 2) + int(changed and count > 2)
|
||||
# 包含 main 在内恰好 count 个定义;main 使用每个函数的结果。
|
||||
if shape == "tree":
|
||||
definitions = []
|
||||
for index in range(count - 1):
|
||||
argument = "value: Int, extra: Int" if signature and index == 0 else "value: Int"
|
||||
increment = "extra" if signature and index == 0 else str(2 if changed and index == 0 else 1)
|
||||
terms = ["value", increment]
|
||||
terms.extend(f"step{child}(value)" for child in [2 * index + 1, 2 * index + 2]
|
||||
if child < count - 1)
|
||||
definitions.append(f"step{index}({argument}) (answer: Int) {{\n answer = {' + '.join(terms)}\n}}\n")
|
||||
call = "1, 1" if signature else "1"
|
||||
definitions.append(f"main() (answer: Int) {{\n answer = step0({call})\n}}\n")
|
||||
return "\n".join(definitions), 2 * (count - 1) + int(changed)
|
||||
definitions = []
|
||||
expected = []
|
||||
for index in range(count - 1):
|
||||
increment = 2 if changed and index == 0 else 1
|
||||
argument = "value: Int, extra: Int" if signature and index == 0 else "value: Int"
|
||||
if index == 0:
|
||||
body = "value + extra" if signature else f"value + {increment}"
|
||||
expected.append(2 if signature else 1 + increment)
|
||||
else:
|
||||
parent = index - 1 if shape in ("chain", "linear") else (index - 1) // 2
|
||||
call = "value, 1" if signature and parent == 0 else "value"
|
||||
body = f"step{parent}({call}) + 1"
|
||||
expected.append(expected[parent] + 1)
|
||||
definitions.append(f"step{index}({argument}) (answer: Int) {{\n answer = {body}\n}}\n")
|
||||
lines = ["main() (answer: Int) {", " answer = 0"]
|
||||
indices = [count - 2] if shape == "linear" else range(count - 1)
|
||||
for index in indices:
|
||||
call = "1, 1" if signature and index == 0 else "1"
|
||||
lines.append(f" answer = answer + step{index}({call})")
|
||||
definitions.append("\n".join(lines + ["}", ""]))
|
||||
return "\n".join(definitions), expected[-1] if shape == "linear" else sum(expected)
|
||||
|
||||
|
||||
def execute(command, directory, label, timeout, *, argv0=None):
|
||||
stdout = directory / (label + ".stdout")
|
||||
stderr = directory / (label + ".stderr")
|
||||
started = time.monotonic()
|
||||
timed_out = False
|
||||
with stdout.open("xb") as out, stderr.open("xb") as err:
|
||||
arguments = command if argv0 is None else [argv0, *command[1:]]
|
||||
process = subprocess.Popen(arguments, executable=command[0], stdout=out, stderr=err,
|
||||
start_new_session=True)
|
||||
def expire(signum, frame):
|
||||
nonlocal timed_out
|
||||
timed_out = True
|
||||
# 只结束本次创建的进程组,避免超时后 Cargo 仍占用共享开发预算。
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass # 截止时间与进程退出可以同时发生。
|
||||
|
||||
previous = signal.signal(signal.SIGALRM, expire)
|
||||
signal.alarm(timeout)
|
||||
try:
|
||||
_, status, usage = os.wait4(process.pid, 0)
|
||||
finally:
|
||||
signal.alarm(0)
|
||||
signal.signal(signal.SIGALRM, previous)
|
||||
process.returncode = os.waitstatus_to_exitcode(status)
|
||||
return dict(command=command, **({"argv0": argv0} if argv0 is not None else {}),
|
||||
exit_code=process.returncode, timeout=timed_out,
|
||||
seconds=time.monotonic() - started, peak_rss_kib=usage.ru_maxrss,
|
||||
user_cpu_seconds=usage.ru_utime, system_cpu_seconds=usage.ru_stime,
|
||||
voluntary_switches=usage.ru_nvcsw, involuntary_switches=usage.ru_nivcsw,
|
||||
stdout=str(stdout), stderr=str(stderr))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--compiler", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--sizes", type=int, nargs="+", default=[100, 1000, 10000])
|
||||
parser.add_argument("--shapes", nargs="+", choices=["tree", "linear", "layered", "chain", "handler", "flow", "owned", "deep"],
|
||||
default=["tree", "linear"])
|
||||
parser.add_argument("--phase", choices=["inspect", "build"], required=True)
|
||||
parser.add_argument("--syntax", choices=["old", "next"], default="old")
|
||||
parser.add_argument("--profile", choices=["dev", "release"], default="release")
|
||||
args = parser.parse_args()
|
||||
if args.syntax == "old" and args.profile != "release":
|
||||
parser.error("old syntax has no public dev build profile")
|
||||
if args.syntax == "old" and "flow" in args.shapes:
|
||||
parser.error("flow tables require next syntax; compare the old linear shape")
|
||||
if any(size < 2 for size in args.sizes):
|
||||
parser.error("sizes must include at least one function and main")
|
||||
compiler = str(args.compiler.resolve(strict=True))
|
||||
# 历史大项目曾使共享 dev OOM 重启;在子进程内失败,保留同一固定预算。
|
||||
address_limit = 6 * 1024 ** 3
|
||||
resource.setrlimit(resource.RLIMIT_AS, (address_limit, address_limit))
|
||||
os.environ["CARGO_BUILD_JOBS"] = "1"
|
||||
root = args.output.resolve()
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
(root / "scale.py").write_bytes(Path(__file__).read_bytes())
|
||||
report = dict(compiler=compiler, compiler_sha256=fingerprint(Path(compiler)),
|
||||
driver_sha256=fingerprint(root / "scale.py"), rounds=3, timeout_seconds=900,
|
||||
phase=args.phase, syntax=args.syntax, profile=args.profile, samples=[])
|
||||
cgroup = Path("/sys/fs/cgroup")
|
||||
report["environment"] = dict(cpu_affinity=sorted(os.sched_getaffinity(0)),
|
||||
cpu_max=(cgroup / "cpu.max").read_text().strip(),
|
||||
memory_max=(cgroup / "memory.max").read_text().strip(),
|
||||
process_virtual_address_limit_bytes=address_limit, cargo_build_jobs=1)
|
||||
memory_before = (cgroup / "memory.events").read_text()
|
||||
report["memory_events_before"] = memory_before
|
||||
initial_oom = dict(line.split() for line in memory_before.splitlines())["oom_kill"]
|
||||
|
||||
def record(sample):
|
||||
report["samples"].append(sample)
|
||||
(root / "results.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps(sample), flush=True)
|
||||
|
||||
for size in args.sizes:
|
||||
for shape in args.shapes:
|
||||
stop = False
|
||||
for round_number in range(3):
|
||||
case = root / f"{shape}-{size}-{round_number}"
|
||||
case.mkdir()
|
||||
path = case / "main.dever"
|
||||
scenarios = [("saved", False, False)] if args.phase == "inspect" else [
|
||||
("first", False, False), ("unchanged", False, False),
|
||||
("body", True, False), ("signature", False, True)]
|
||||
for scenario, changed, signature in scenarios:
|
||||
text, expected = source(size, shape, changed, signature)
|
||||
if scenario != "unchanged":
|
||||
path.write_text(text)
|
||||
formatted = execute([compiler, "fmt", str(case)], case, scenario + "-fmt", 900)
|
||||
if formatted["exit_code"] != 0:
|
||||
record(dict(size=size, shape=shape, round=round_number,
|
||||
scenario=scenario, stage="fmt", **formatted))
|
||||
stop = True
|
||||
break
|
||||
command = [compiler, "inspect", str(path), "--json"]
|
||||
if args.phase == "build":
|
||||
binary = case / scenario
|
||||
command = [compiler, "build", str(path), "--output", str(binary)]
|
||||
if args.syntax == "next":
|
||||
command.extend(["--profile", args.profile])
|
||||
measured = execute(command, case, scenario, 900)
|
||||
sample = dict(size=size, shape=shape, round=round_number, scenario=scenario,
|
||||
source_sha256=fingerprint(path), source_bytes=path.stat().st_size,
|
||||
expected=expected, **measured)
|
||||
if measured["exit_code"] == 0:
|
||||
if args.phase == "build":
|
||||
ran = execute([str(binary)], case, scenario + "-run", 900)
|
||||
sample["execution"] = ran
|
||||
sample["correct"] = ran["exit_code"] == 0 and Path(ran["stdout"]).read_text().strip() == str(expected)
|
||||
sample["binary_sha256"] = fingerprint(binary)
|
||||
sample["binary_bytes"] = binary.stat().st_size
|
||||
else:
|
||||
index = json.loads(Path(measured["stdout"]).read_text())
|
||||
names = {item["name"] for item in index["symbols"]}
|
||||
namespace = "main.main.app" if args.syntax == "next" else "main"
|
||||
count = size - 2 if shape == "handler" else size - 1
|
||||
wanted = {f"{namespace}.main"} | {f"{namespace}.step{i}" for i in range(count)}
|
||||
sample["correct"] = wanted.issubset(names)
|
||||
if args.syntax == "next":
|
||||
by_id = {symbol["id"]: symbol for symbol in index["symbols"]}
|
||||
versions = Counter(by_id[symbol["template"]]["name"] if "template" in symbol
|
||||
else symbol.get("source_name", symbol["name"]) for symbol in index["symbols"]
|
||||
if symbol["kind"] in {"function", "rule", "flow"})
|
||||
sample["checked_function_instances"] = sum(versions.values())
|
||||
sample["instances_per_source"] = dict(sorted(versions.items()))
|
||||
sample["correct"] &= not index["diagnostics"]
|
||||
if shape == "handler":
|
||||
sample["correct"] &= versions[f"{namespace}.apply"] == size - 2
|
||||
sample["correct"] &= sum(versions.values()) == 2 * size - 3
|
||||
sample["index_bytes"] = Path(measured["stdout"]).stat().st_size
|
||||
else:
|
||||
sample["correct"] = False
|
||||
record(sample)
|
||||
memory_after = (cgroup / "memory.events").read_text()
|
||||
if dict(line.split() for line in memory_after.splitlines())["oom_kill"] != initial_oom:
|
||||
record(dict(status="remaining workloads not executed after cgroup OOM",
|
||||
memory_events_after=memory_after))
|
||||
raise SystemExit(1)
|
||||
if not sample["correct"]:
|
||||
stop = True
|
||||
break
|
||||
if stop:
|
||||
record(dict(size=size, shape=shape, status="remaining rounds not executed after failure"))
|
||||
break
|
||||
failed = any(sample.get("correct") is False or sample.get("exit_code", 0) != 0
|
||||
for sample in report["samples"])
|
||||
raise SystemExit(1 if failed else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user