Files
core/test/performance/model.py
T
2026-11-27 06:03:56 +00:00

228 lines
14 KiB
Python

"""真实 Model CMD 四方对照:原子 CRUD、输入拒绝和失败回滚;原生对端不链接 Dever。"""
import argparse
import json
import os
from pathlib import Path
import shutil
import sqlite3
import statistics
import time
import tomllib
from scale import execute, fingerprint
def snapshot(database, table):
with sqlite3.connect(f"file:{database}?mode=ro", uri=True) as connection:
connection.create_function("_dever_length", 1, len, deterministic=True)
rows = connection.execute(
f'SELECT id,created_at,number,title,amount,note FROM "{table}" ORDER BY number'
).fetchall()
assert connection.execute("PRAGMA quick_check").fetchone() == ("ok",)
return rows
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--artifacts", type=Path,
help="contains new-app, old-app, go-app, rust/target/release/model-peer and new/old projects")
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--reads", action="store_true", help="build and measure full-row page/cursor/batched-relation reads")
parser.add_argument("--compiler", type=Path, help="current compiler for --reads")
parser.add_argument("--argv0", help="fixed process argv[0] for the read comparison; executable identity is retained")
parser.add_argument("--title", default="中文 benchmark",
help="title for timed batches; retained verbatim in the result identity")
parser.add_argument("--previous", type=Path, help="same-workload prior new-version binary")
parser.add_argument("--current", type=Path, help="candidate binary; preserves existing artifacts/new-app")
parser.add_argument("--resource-reference", type=Path,
help="independent Tokio/deadpool reference with SQL deadlines and cancellation drain")
parser.add_argument("--resource-baseline", type=Path,
help="retain the earlier independent resource reference in the same timed run")
args = parser.parse_args()
if args.reads:
if not args.compiler:
parser.error("--reads requires --compiler")
from model_reads import run
run(args)
return
if not args.artifacts:
parser.error("CRUD comparison requires --artifacts")
artifacts = args.artifacts.resolve(strict=True)
output = args.output.absolute()
output.mkdir(parents=True, exist_ok=False)
core = Path(__file__).resolve().parents[2]
binaries = {"new": artifacts / "new-app", "old": artifacts / "old-app",
"rust": artifacts / "rust/target/release/model-peer", "go": artifacts / "go-app"}
if args.current:
binaries["new"] = args.current.resolve(strict=True)
if args.previous:
binaries["previous"] = args.previous.resolve(strict=True)
if args.resource_reference:
binaries["rust-resource"] = args.resource_reference.resolve(strict=True)
if args.resource_baseline:
binaries["rust-resource-baseline"] = args.resource_baseline.resolve(strict=True)
databases = {name: artifacts / name / "data/model.db" for name in binaries}
# 旧版以可执行文件目录解析数据库相对路径;新版以 config 的项目根解析。
databases["old"] = artifacts / "data/model.db"
references = [name for name in binaries if name in ("rust", "rust-resource", "rust-resource-baseline", "go")]
for name in references:
databases[name] = output / (name + ".db")
tables = {"new": "benchmark_article", "old": "benchmark_article_model",
"rust": "benchmark_article", "go": "benchmark_article", "rust-resource": "benchmark_article"}
if args.resource_baseline:
tables["rust-resource-baseline"] = "benchmark_article"
if args.previous:
databases["previous"] = databases["new"]
tables["previous"] = tables["new"]
report = dict(rounds=7, warmups=1, sizes=[0, 1, 32, 256, 1024], cpu_affinity=[0],
timed_title=args.title,
contract="Each process parses one CMD, opens its SQLite database, begins IMMEDIATE, deletes prior nonnegative records, creates/reads/updates a full record per input, counts, encodes and commits. WAL/NORMAL, one connection, prepared statements, checked Int arithmetic, Unicode title and nullable note. Compare complete stored rows and transaction rollback. Wall/CPU include process startup and shutdown; verification is outside timing.",
limitation="Rust is synchronous rusqlite; Go uses database/sql. They do not implement Dever async Scope cancellation/deadline/pool ownership or the entire Model/permission/tenant contract. Independent peers normalize title once at entry; Dever normalizes each Model write, so title-heavy cases compare each implementation's current behavior, not equal normalization cost. This is a CLI business-workload comparison, not proof of equal async resource costs. Database engine versions are recorded; differences must not be hidden.",
binaries={name: dict(path=str(path), sha256=fingerprint(path), bytes=path.stat().st_size)
for name, path in binaries.items()}, functional=[], samples=[])
sources = [Path(__file__), *core.joinpath("test/performance/fixtures/model").iterdir(),
*core.joinpath("rust/src").rglob("*.rs"),
*core.joinpath("lib").rglob("*.dv"),
core / "rust/Cargo.toml", core / "rust/src/runtime/Cargo.toml",
core / "rust/Cargo.lock",
artifacts / "rust/Cargo.toml", artifacts / "rust/Cargo.lock",
artifacts / "go/go.mod", artifacts / "go/go.sum"]
sources += [p for name in ("new", "old") for p in (artifacts / name / "module").rglob("*.dever")]
if args.resource_reference:
peer = binaries["rust-resource"].parents[2]
sources += [peer / name for name in ("main.rs", "Cargo.toml", "Cargo.lock")]
if (peer / "sqlite_resource.rs").exists():
sources.append(peer / "sqlite_resource.rs")
report["resource_reference_contract"] = "Independent Tokio current-thread runtime, deadpool SQLite pool (one connection), per-SQL blocking handoff, eight worker permits, 30s deadlines, SQLite progress cancellation, tracked blocking-result disposal, unfinished transaction discard, rollback and unclaimed panic reporting. It does not implement all Dever schema validation, named FaultInfo, multi-backend or tenant semantics; this remains a bounded resource/workload comparison."
if args.resource_baseline:
peer = binaries["rust-resource-baseline"].parents[2]
sources += [peer / name for name in ("main.rs", "Cargo.toml", "Cargo.lock")]
report["resource_baseline_contract"] = "Earlier resource peer decodes all columns but returns only id/amount across the blocking boundary. Retained as a lighter reference; full-record transfer is measured separately."
report["sources"] = {str(p): fingerprint(p) for p in sources}
snapshots = output / "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, output / (name + "-binary"))
report["source_lines"] = {str(p): len(p.read_text().splitlines()) for p in sources}
business = {name: sorted((artifacts / name / "module").rglob("*.dever")) for name in ("new", "old")}
business.update(rust=[artifacts / "rust/main.rs"], go=sorted((artifacts / "go").glob("*.go")))
if args.resource_reference:
business["rust-resource"] = sorted(binaries["rust-resource"].parents[2].glob("*.rs"))
report["business_sources"] = {name: [dict(path=str(p), sha256=fingerprint(p),
physical_lines=len(p.read_text().splitlines()), nonblank_lines=sum(bool(line.strip()) for line in p.read_text().splitlines()))
for p in paths] for name,paths in business.items()}
report["old_source_verification"] = json.loads((artifacts / "baseline-identity.json").read_text())
report["rust_lock_dependencies"] = [dict(name=p["name"], version=p["version"]) for p in
tomllib.loads((artifacts / "rust/Cargo.lock").read_text())["package"]]
def save():
(output / "results.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
save()
with sqlite3.connect(f"file:{databases['new']}?mode=ro", uri=True) as connection:
schema = connection.execute("SELECT sql FROM sqlite_master WHERE name = ?", (tables["new"],)).fetchone()[0]
report["reference_schema"] = schema
with sqlite3.connect(f"file:{databases['old']}?mode=ro", uri=True) as connection:
report["old_schema"] = connection.execute("SELECT sql FROM sqlite_master WHERE name = ?", (tables["old"],)).fetchone()[0]
for name in references:
databases[name].parent.mkdir(exist_ok=True)
assert not databases[name].exists(), "reference database must be new"
with sqlite3.connect(databases[name]) as connection:
connection.create_function("_dever_length", 1, len, deterministic=True)
connection.execute(schema)
version = execute([str(binaries[name]), "--sqlite-version"], output, name + "-version", 30)
assert version["exit_code"] == 0, version
report[name + "_sqlite_version"] = Path(version["stdout"]).read_text().strip()
save()
if args.resource_reference:
row = execute([str(binaries["rust-resource"]), "--self-test", str(output / "resource-cleanup.db")],
output, "resource-cleanup", 30)
report["resource_cleanup"] = row
save()
assert row["exit_code"] == 0, row
def call(name, payload, label):
data = json.dumps(payload, ensure_ascii=False)
if name in ("new", "old", "previous"):
project = "new" if name == "previous" else name
command = [str(binaries[name]), "--config", str(artifacts / project / "config/setting.json"),
"benchmark.article.batch", data]
else:
command = [str(binaries[name]), str(databases[name]), data]
return execute(command, output, label, 120)
def checked(name, payload, row):
assert row["exit_code"] == 0, row
answer = json.loads(Path(row["stdout"]).read_text())
if name in ("new", "old", "previous"):
assert answer["code"] == 0, answer
answer = answer["data"]
numbers = payload["numbers"]
assert answer == {"checksum": sum(n + 1 for n in numbers), "count": len(numbers)}, answer
stored = snapshot(databases[name], tables[name])
assert [(r[2], r[3], r[4], r[5]) for r in stored] == [
(n, payload["title"].strip(), n + 1, None) for n in sorted(numbers)]
assert all(r[0] > 0 and 0 < r[1] <= int(time.time() * 1000) for r in stored)
row["checked"] = True
invalid = [
("unique-rollback", {"numbers": [11, 12, 11], "title": "must rollback"}),
("overflow-rollback", {"numbers": [11, 9223372036854775807], "title": "overflow"}),
("blank-title", {"numbers": [11], "title": " "}),
("long-title", {"numbers": [11], "title": "中" * 121}),
("wrong-number-type", {"numbers": ["11"], "title": "typed"}),
("missing-numbers", {"title": "required"}),
("unknown-field", {"numbers": [11], "title": "typed", "extra": 1}),
]
for name in binaries:
payload = {"numbers": [1, 7, 3], "title": " 中文 ' OR 1=1 -- "}
row = call(name, payload, name + "-functional-commit")
report["functional"].append(dict(implementation=name, case="commit", **row)); save()
checked(name, payload, row)
report["functional"][-1]["checked"] = True
before = snapshot(databases[name], tables[name])
for case, payload in invalid:
row = call(name, payload, name + "-" + case)
report["functional"].append(dict(implementation=name, case=case, **row)); save()
assert row["exit_code"] != 0 and not row["timeout"], row
assert Path(row["stderr"]).read_text().strip(), row
assert snapshot(databases[name], tables[name]) == before, (name, case, "rollback mismatch")
report["functional"][-1]["checked"] = True
save()
os.sched_setaffinity(0, {0})
os.environ["GOMAXPROCS"] = "1"
names = list(binaries)
for repeat in range(-1, 7):
assert all(fingerprint(Path(path)) == digest for path, digest in report["sources"].items())
assert all(fingerprint(binaries[name]) == report["binaries"][name]["sha256"] for name in names)
for size in report["sizes"]:
payload = {"numbers": list(range(1, size + 1)), "title": args.title}
for offset in range(len(names)):
name = names[(repeat + 1 + offset) % len(names)]
row = call(name, payload, f"{repeat + 1}-{size}-{name}")
report["samples"].append(dict(implementation=name, size=size, warmup=repeat < 0, **row)); save()
checked(name, payload, row)
report["samples"][-1]["checked"] = True
save()
report["medians"] = []
for size in report["sizes"]:
for name in names:
rows = [row for row in report["samples"] if not row["warmup"] and row["size"] == size and row["implementation"] == name]
seconds = statistics.median(row["seconds"] for row in rows)
quantiles = statistics.quantiles([row["seconds"] for row in rows], n=100, method="inclusive")
report["medians"].append(dict(size=size, implementation=name,
seconds=seconds, records_per_second=size / seconds,
batch_p95_seconds=quantiles[94], batch_p99_seconds=quantiles[98],
cpu_seconds=statistics.median(row["user_cpu_seconds"] + row["system_cpu_seconds"] for row in rows)))
report["latency_scope"] = "p95/p99 describe seven whole-CMD batch samples, not individual SQL/request latency or a high-confidence production tail. Zero-size measures startup/schema/empty transaction overhead."
save()
print(json.dumps(report["medians"], indent=2))
if __name__ == "__main__":
main()