311 lines
19 KiB
Python
311 lines
19 KiB
Python
"""model.py --reads:完整行分页、游标、批量关系的同资源独立对照。"""
|
|
from datetime import datetime, timezone
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import sqlite3
|
|
import statistics
|
|
|
|
from model_build import build_resource
|
|
from scale import execute, fingerprint
|
|
|
|
|
|
def build(core, compiler, root):
|
|
root.mkdir()
|
|
identity = dict(compiler_sha256=fingerprint(compiler),
|
|
sources={str(p): fingerprint(p) for p in [*core.joinpath("rust/src").rglob("*.rs"),
|
|
*core.joinpath("lib").rglob("*.dv"), core / "rust/Cargo.lock"]})
|
|
(root / "identity.json").write_text(json.dumps(identity, indent=2))
|
|
fixture = core / "test/performance/fixtures/model"
|
|
article = root / "project/module/benchmark/article"
|
|
(article / "data").mkdir(parents=True)
|
|
(article / "app").mkdir()
|
|
shutil.copyfile(fixture / "model.dever", article / "data/main.dever")
|
|
shutil.copyfile(fixture / "reads.dever.txt", article / "app/main.dever")
|
|
(article / "api.dever").write_text("cmd page = app.page\ncmd cursor = app.cursor\n")
|
|
domain = root / "project/module/benchmark/read"
|
|
(domain / "data").mkdir(parents=True)
|
|
(domain / "data/author.dever").write_text(
|
|
"type Author { name: Text(1,120), note: Text? raw }\nrelation posts = data.post.author_id\n")
|
|
(domain / "data/post.dever").write_text(
|
|
"type Post { title: Text(1,120), author_id: data.author.id, note: Text? raw }\n")
|
|
(domain / "app").mkdir()
|
|
shutil.copyfile(fixture / "relations.dever.txt", domain / "app/main.dever")
|
|
(domain / "api.dever").write_text("cmd page = app.page\n")
|
|
config = root / "project/config/setting.json"
|
|
config.parent.mkdir()
|
|
(root / "project/data").mkdir()
|
|
config.write_text(json.dumps({"database": {"default": {"type": "sqlite",
|
|
"path": "data/model.db", "max_connections": 1, "max_page_size": 1024}}}) + "\n")
|
|
commands = []
|
|
|
|
def command(label, args):
|
|
row = execute([str(x) for x in args], root, label, 1800)
|
|
commands.append(row)
|
|
(root / "build.json").write_text(json.dumps(commands, indent=2) + "\n")
|
|
assert row["exit_code"] == 0, row
|
|
|
|
command("format", [compiler, "fmt", root / "project"])
|
|
command("build", [compiler, "build", root / "project", "--output", root / "new-app"])
|
|
command("migrate", [root / "new-app", "--config", config, "migrate"])
|
|
reference = build_resource(core, root, source="reads.rs.txt", target=core / "target/next-cargo",
|
|
dependencies='chrono = { version = "=0.4.45", default-features = false, features = ["std"] }\n')
|
|
shutil.copyfile(reference, root / "peer-app")
|
|
shutil.copymode(reference, root / "peer-app")
|
|
return root
|
|
|
|
|
|
def timestamp(value):
|
|
text = datetime.fromtimestamp(value // 1000, timezone.utc).strftime("%Y-%m-%dT%H:%M:%S")
|
|
return text + (f".{value % 1000:03d}" if value % 1000 else "") + "Z"
|
|
|
|
|
|
def seed(path, count):
|
|
"""只写本次创建的基准库;输入包含 Unicode、引号、NULL、空串和 NUL。"""
|
|
with sqlite3.connect(path) as db:
|
|
db.create_function("_dever_length", 1, len, deterministic=True)
|
|
db.execute("PRAGMA foreign_keys=ON")
|
|
for table in ("benchmark_read_post", "benchmark_read_author", "benchmark_article"):
|
|
db.execute(f'DELETE FROM "{table}"')
|
|
notes = (None, "", " 雪 ' \x00 raw ")
|
|
db.executemany("INSERT INTO benchmark_article(id,created_at,number,title,amount,note) VALUES(?,?,?,?,?,?)",
|
|
((i, 1700000000000 + i, i * 3, f"中文 article {i}", -i, notes[i % 3]) for i in range(1, count + 1)))
|
|
db.executemany("INSERT INTO benchmark_read_author(id,created_at,name,note) VALUES(?,?,?,?)",
|
|
((i, 1700000000000 + i, f"作者 {i}", notes[i % 3]) for i in range(1, count + 1)))
|
|
db.executemany("INSERT INTO benchmark_read_post(id,created_at,title,author_id,note) VALUES(?,?,?,?,?)",
|
|
((i * 3 + j, 1700000100000 + i * 3 + j, f"文章 {i}/{j}", i, notes[j])
|
|
for i in range(1, count + 1) for j in range(i % 4)))
|
|
|
|
|
|
def contents(path):
|
|
with sqlite3.connect(f"file:{path}?mode=ro", uri=True) as db:
|
|
assert db.execute("PRAGMA quick_check").fetchone() == ("ok",)
|
|
columns = {"benchmark_article": ("id", "created_at", "number", "title", "amount", "note"),
|
|
"benchmark_read_author": ("id", "created_at", "name", "note"),
|
|
"benchmark_read_post": ("id", "created_at", "title", "author_id", "note")}
|
|
rows = {table: [dict(zip(names, row)) for row in db.execute(
|
|
f'SELECT {",".join(names)} FROM "{table}" ORDER BY id')] for table, names in columns.items()}
|
|
digest = hashlib.sha256(json.dumps(rows, ensure_ascii=False).encode()).hexdigest()
|
|
for values in rows.values():
|
|
for row in values:
|
|
row["created_at"] = timestamp(row["created_at"])
|
|
return rows, digest
|
|
|
|
|
|
def cases(rows):
|
|
articles = rows["benchmark_article"]
|
|
groups = {}
|
|
for row in reversed(rows["benchmark_read_post"]):
|
|
groups.setdefault(row["author_id"], []).append(row)
|
|
authors = [dict(row, posts=groups.get(row["id"], [])) for row in rows["benchmark_read_author"]]
|
|
result = []
|
|
for size in (1, 32, 256, 1024):
|
|
for position in ("first", "deep"):
|
|
for operation, records in (("page", articles), ("cursor", articles), ("relations", authors)):
|
|
page = 1 if position == "first" else max(2, (len(records) - 1) // size + 1)
|
|
offset = (page - 1) * size
|
|
items = records[offset:offset + size]
|
|
if operation == "cursor":
|
|
after = records[min(offset, len(records)) - 1] if records and offset else None
|
|
payload = dict(after=after, size=size)
|
|
has_more = offset + size < len(records)
|
|
expected = dict(items=items, next=items[-1] if has_more else None, has_more=has_more)
|
|
else:
|
|
payload = dict(page=page, size=size)
|
|
expected = dict(items=items, page=page, size=size, total=len(records),
|
|
pages=(len(records) + size - 1) // size)
|
|
result.append((f"{operation}-{size}-{position}", operation, payload, expected))
|
|
return result
|
|
|
|
|
|
def run(args):
|
|
core = Path(__file__).resolve().parents[2]
|
|
compiler = args.compiler.resolve(strict=True)
|
|
output = args.output.absolute()
|
|
output.mkdir(parents=True, exist_ok=False)
|
|
report = dict(rounds=7, warmups=1, record_counts=[0, 4096, 65536], sizes=[1, 32, 256, 1024],
|
|
contract="Read-only CMD; complete typed rows. OFFSET page COUNT+SELECT; composite-key cursor SELECT size+1; relation page COUNT+SELECT+one batched window SELECT for nonempty pages. Both peers own one SQLite pool connection, per-SQL blocking handoff, 30s deadline/cancellation/drain and eight permits. Identical schema/data and release/fat LTO/single CGU/checked arithmetic.",
|
|
limitation="SQLite workload, not full four-way Model acceptance. The lighter rust-resource peer omits schema startup verification and input/wire budgets; rust-boundary adds the responsibilities explicitly listed in boundary_contract. Neither covers named Dever faults, PostgreSQL or authorization. Wall/CPU include process startup, encoding and shutdown; seven batch samples do not establish production request p99.",
|
|
compiler=dict(path=str(compiler), sha256=fingerprint(compiler)), process_argv0=args.argv0,
|
|
functional=[], samples=[])
|
|
|
|
def save():
|
|
(output / "results.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
|
|
|
save()
|
|
os.environ["CARGO_BUILD_JOBS"] = "2"
|
|
artifacts = args.artifacts.resolve(strict=True) if args.artifacts else build(core, compiler, output / "artifacts")
|
|
identity = json.loads((artifacts / "identity.json").read_text())
|
|
assert identity["compiler_sha256"] == fingerprint(compiler), "artifact/compiler identity mismatch"
|
|
assert all(fingerprint(Path(p)) == value for p, value in identity["sources"].items()), "artifact/source mismatch"
|
|
binaries = {"new": artifacts / "new-app", "rust-resource": artifacts / "peer-app"}
|
|
if args.previous:
|
|
binaries["previous"] = args.previous.resolve(strict=True)
|
|
if args.resource_baseline:
|
|
binaries["rust-resource-baseline"] = args.resource_baseline.resolve(strict=True)
|
|
if args.resource_reference:
|
|
binaries["rust-boundary"] = args.resource_reference.resolve(strict=True)
|
|
report["boundary_contract"] = "Independent Rust additionally reads the same named configuration, verifies all three compiled schema declarations against persistent history and actual SQLite catalog, and enforces named JSON objects plus byte/value/depth output limits. It still does not cover PostgreSQL, authorization, every Model operation or the entire language."
|
|
sources = [Path(__file__), Path(__file__).with_name("model.py"), Path(__file__).with_name("model_build.py"),
|
|
*artifacts.joinpath("project/module").rglob("*.dever"), *artifacts.joinpath("rust-resource").glob("*.rs"),
|
|
artifacts / "rust-resource/Cargo.toml", artifacts / "rust-resource/Cargo.lock",
|
|
*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"]
|
|
if args.resource_reference:
|
|
reference = binaries["rust-boundary"].parent / "rust-resource"
|
|
sources += [*reference.glob("*.rs"), reference / "Cargo.toml", reference / "Cargo.lock"]
|
|
report["sources"] = {str(p): fingerprint(p) for p in sources}
|
|
frozen = output / "sources"
|
|
frozen.mkdir()
|
|
for i, path in enumerate(sources):
|
|
shutil.copyfile(path, frozen / f"{i}-{path.name}")
|
|
report["binaries"] = {name: dict(path=str(binary), sha256=fingerprint(binary), bytes=binary.stat().st_size)
|
|
for name, binary in binaries.items()}
|
|
databases = {}
|
|
config = output / "new/config/setting.json"
|
|
config.parent.mkdir(parents=True)
|
|
(output / "new/data").mkdir()
|
|
shutil.copyfile(artifacts / "project/config/setting.json", config)
|
|
for name, binary in binaries.items():
|
|
shutil.copyfile(binary, output / (name + "-binary"))
|
|
databases[name] = output / ("new/data/model.db" if name in ("new", "previous", "rust-boundary") else name + ".db")
|
|
with sqlite3.connect(artifacts / "project/data/model.db") as source, sqlite3.connect(databases[name]) as destination:
|
|
source.backup(destination)
|
|
version = execute([str(binaries["rust-resource"]), "--sqlite-version"], output, "sqlite-version", 30)
|
|
assert version["exit_code"] == 0, version
|
|
report["sqlite_version"] = Path(version["stdout"]).read_text().strip()
|
|
save()
|
|
|
|
def call(name, operation, payload, label):
|
|
data = json.dumps(payload, ensure_ascii=False)
|
|
command = ([str(binaries[name]), "--config", str(config),
|
|
"benchmark.read.page" if operation == "relations" else "benchmark.article." + operation, data]
|
|
if name in ("new", "previous", "rust-boundary") else [str(binaries[name]), str(databases[name]), operation, data])
|
|
return execute(command, output, label, 120, argv0=args.argv0)
|
|
|
|
def check(name, row, expected):
|
|
assert row["exit_code"] == 0 and not row["timeout"], row
|
|
answer = json.loads(Path(row["stdout"]).read_text())
|
|
if name in ("new", "previous", "rust-boundary"):
|
|
assert answer["code"] == 0, answer
|
|
answer = answer["data"]
|
|
assert answer == expected, (name, row["stdout"], "full row/page mismatch")
|
|
row["checked"] = True
|
|
|
|
if args.resource_reference:
|
|
# 同一份实际结构及篡改同时交给两方;不让参考少做启动责任。
|
|
for case, mutation in [
|
|
("valid", None),
|
|
("missing-file", None),
|
|
("missing-history", "DELETE FROM _dever_history WHERE name='benchmark_read_post'"),
|
|
("changed-declaration", "UPDATE _dever_history SET definition='changed' WHERE name='benchmark_article'"),
|
|
("changed-column", "ALTER TABLE benchmark_read_author ADD COLUMN changed TEXT"),
|
|
("missing-table", "DROP TABLE benchmark_read_post"),
|
|
("changed-index", "CREATE INDEX unexpected ON benchmark_read_author(name)"),
|
|
]:
|
|
directory = output / ("boundary-" + case)
|
|
(directory / "data").mkdir(parents=True)
|
|
(directory / "config").mkdir()
|
|
database = directory / "data/model.db"
|
|
if case != "missing-file":
|
|
with sqlite3.connect(artifacts / "project/data/model.db") as source, sqlite3.connect(database) as destination:
|
|
source.backup(destination)
|
|
if mutation:
|
|
destination.execute(mutation)
|
|
test_config = directory / "config/setting.json"
|
|
shutil.copyfile(config, test_config)
|
|
if case == "valid":
|
|
valid_config = test_config
|
|
for name in ("new", "rust-boundary"):
|
|
row = dict(implementation=name, case="schema-" + case,
|
|
**execute([str(binaries[name]), "--config", str(test_config), "benchmark.article.page",
|
|
'{"page":1,"size":1}'], output, "schema-" + case + "-" + name, 30, argv0=args.argv0))
|
|
report["functional"].append(row); save()
|
|
assert not row["timeout"], row
|
|
if case == "valid":
|
|
check(name, row, dict(items=[], page=1, size=1, total=0, pages=0))
|
|
else:
|
|
assert row["exit_code"] != 0 and Path(row["stderr"]).read_text().strip(), row
|
|
row["checked"] = True
|
|
if case == "missing-file":
|
|
assert not database.exists(), "opening a missing database created a file"
|
|
anchor = dict(id=1, created_at="2023-11-14T22:13:20.001Z", number=3, title="中文", amount=-1, note=None)
|
|
invalid = [("root-array", "page", "[1,1]"), ("root-null", "page", "null"),
|
|
("duplicate", "page", '{"page":1,"page":2,"size":1}'),
|
|
("unknown", "page", '{"page":1,"size":1,"extra":0}'),
|
|
("trailing", "page", '{"page":1,"size":1}{}'),
|
|
("wrong-type", "page", '{"page":"1","size":1}'),
|
|
("after-array", "cursor", json.dumps(dict(after=list(anchor.values()), size=1)))]
|
|
for field, value in [("id", 0),
|
|
("created_at", "2023-11-14T22:13:20.0001Z"), ("extra", 1)]:
|
|
invalid.append(("after-" + field + "-" + str(len(invalid)), "cursor",
|
|
json.dumps(dict(after=dict(anchor, **{field:value}), size=1))))
|
|
for case, operation, payload in invalid:
|
|
for name in ("new", "rust-boundary"):
|
|
row = dict(implementation=name, case=case, **execute([str(binaries[name]), "--config", str(valid_config),
|
|
"benchmark.article." + operation, payload], output, case + "-" + name, 30, argv0=args.argv0))
|
|
report["functional"].append(row); save()
|
|
assert row["exit_code"] != 0 and not row["timeout"] and Path(row["stderr"]).read_text().strip(), row
|
|
row["checked"] = True
|
|
# 长度和规范化属于写入边界;游标不清洗或重验这些非排序字段。
|
|
for index, title in enumerate(("", "中" * 121, " Mixed ")):
|
|
payload = json.dumps(dict(after=dict(anchor, title=title), size=1))
|
|
for name in ("new", "rust-boundary"):
|
|
row = dict(implementation=name, case="cursor-preserves-fields-" + str(index),
|
|
**execute([str(binaries[name]), "--config", str(valid_config),
|
|
"benchmark.article.cursor", payload], output,
|
|
"cursor-preserves-fields-" + str(index) + "-" + name, 30, argv0=args.argv0))
|
|
report["functional"].append(row); save()
|
|
check(name, row, dict(items=[], next=None, has_more=False))
|
|
save()
|
|
|
|
os.sched_setaffinity(0, {0})
|
|
for count in report["record_counts"]:
|
|
for path in set(databases.values()):
|
|
seed(path, count)
|
|
rows, digest = contents(databases["new"])
|
|
assert contents(databases["rust-resource"])[1] == digest
|
|
workloads = cases(rows)
|
|
for repeat in range(-1, 7):
|
|
assert all(fingerprint(Path(p)) == value for p, value in report["sources"].items())
|
|
assert all(fingerprint(path) == report["binaries"][name]["sha256"] for name, path in binaries.items())
|
|
for case, operation, payload, expected in workloads:
|
|
names = list(binaries)
|
|
offset = (repeat + 1) % len(names)
|
|
names = names[offset:] + names[:offset]
|
|
for name in names:
|
|
row = dict(implementation=name, records=count, case=case, warmup=repeat < 0,
|
|
**call(name, operation, payload, f"{count}-{repeat + 1}-{case}-{name}"))
|
|
report["samples"].append(row)
|
|
save()
|
|
check(name, row, expected)
|
|
for name in binaries:
|
|
for case, operation, payload in [
|
|
("zero-page", "page", dict(page=0, size=1)),
|
|
("large-size", "page", dict(page=1, size=1025)),
|
|
("offset-overflow", "page", dict(page=9223372036854775807, size=1024)),
|
|
("zero-cursor", "cursor", dict(after=None, size=0)),
|
|
("relation-large", "relations", dict(page=1, size=1025)),
|
|
]:
|
|
row = dict(implementation=name, records=count, case=case,
|
|
**call(name, operation, payload, f"{count}-{case}-{name}"))
|
|
report["functional"].append(row)
|
|
save()
|
|
assert row["exit_code"] != 0 and not row["timeout"] and Path(row["stderr"]).read_text().strip(), row
|
|
row["checked"] = True
|
|
assert contents(databases[name])[1] == digest, (name, "reads changed stored records")
|
|
save()
|
|
report["medians"] = []
|
|
keys = sorted({(row["records"], row["case"], row["implementation"]) for row in report["samples"]})
|
|
for count, case, name in keys:
|
|
rows = [row for row in report["samples"] if not row["warmup"] and
|
|
(row["records"], row["case"], row["implementation"]) == (count, case, name)]
|
|
report["medians"].append(dict(records=count, case=case, implementation=name,
|
|
seconds=statistics.median(row["seconds"] for row in rows),
|
|
cpu_seconds=statistics.median(row["user_cpu_seconds"] + row["system_cpu_seconds"] for row in rows)))
|
|
save()
|
|
print(json.dumps(dict(samples=len(report["samples"]), functional=len(report["functional"]),
|
|
checked=all(row["checked"] for row in report["samples"] + report["functional"])) ))
|