import argparse
import hashlib
import json
import os
import pathlib
import platform
import re
import statistics
import subprocess
import sys
import time
from checksum import Checksum
ROOT = pathlib.Path(__file__).resolve().parents[2]
CASES = ("select", "point", "fill", "fill_bulk", "wide")
SEED = 0x5EED
def dataset(count, wide):
state = SEED
for index in range(count):
state = (1664525 * state + 1013904223) & 0xFFFFFFFF
row = {"id": index, "score": (state >> 8) + 0.5,
"title": "mem-%08x-知识\x00🙂" % index}
if wide:
for column in range(3, 20):
kind = column % 7
row["c%02d" % column] = (
-(state % 100000), (state % 10000) + 0.25,
"thread-%d-界" % (index % 37), [index, None, "内容", True],
{"id": index, "nested": ["\x00", False, {"标题": "value"}]},
index % 2 == 0, None,
)[kind]
yield row
def fixture(count, case):
rows = list(dataset(count, case == "wide"))
columns = sorted(rows[0])
properties = ", ".join("%s: row.%s" % (column, column) for column in columns)
projection = ", ".join("n.%s AS %s" % (column, column) for column in columns)
checksum = Checksum(columns)
for row in rows:
checksum.row([row[column] for column in columns])
return {
"case": case, "rows": rows, "columns": columns,
"insert_single": "CREATE (:Boundary {%s})" % ", ".join("%s: $%s" % (column, column) for column in columns),
"insert_bulk": "UNWIND $rows AS row CREATE (:Boundary {%s})" % properties,
"scan": "MATCH (n:Boundary) RETURN %s ORDER BY id" % projection,
"point": "MATCH (n:Boundary {id: $id}) RETURN %s" % projection,
"expected_checksum": checksum.hex(), "seed": SEED,
}
def command_text(*args):
return subprocess.check_output(args, cwd=ROOT, text=True).strip()
def source_identity():
if subprocess.run(["git", "diff", "--quiet"], cwd=ROOT).returncode:
raise RuntimeError("stage the final source before running the matrix")
if command_text("git", "ls-files", "--others", "--exclude-standard"):
raise RuntimeError("stage or remove untracked files before running the matrix")
return {"head": command_text("git", "rev-parse", "HEAD"),
"tree": command_text("git", "write-tree")}
def artifact_identity(paths):
return {str(path): hashlib.sha256(path.read_bytes()).hexdigest() for path in paths}
def require_artifact_identity(paths, expected):
if artifact_identity(paths) != expected:
raise RuntimeError("benchmark artifacts changed during qualification")
def native_profile_valid(result, layer, required):
if result["status"] != "ok":
return None
profile = result.get("native_profile")
if not required:
return profile is None
return native_counters_valid(profile, layer)
def native_counters_valid(profile, layer):
fields = ("allocation_calls", "allocated_bytes", "deallocation_calls",
"deallocated_bytes", "reallocation_calls",
"live_requested_bytes_before", "live_requested_bytes_after",
"process_peak_requested_bytes")
if layer != "rust":
fields += ("parameter_conversion_ns", "engine_call_ns", "result_conversion_ns")
return isinstance(profile, dict) and all(
type(profile.get(key)) is int and profile[key] >= 0 for key in fields
)
def failure_profile_valid(result, layer, required):
if result["status"] == "ok":
return None
profile = result.get("failure_native_profile")
if not required:
return False if profile is not None else None
return (result.get("failure_profile_scope") ==
"producer_run_including_setup_warmup_and_cleanup"
and native_counters_valid(profile, layer))
def go_host_counters_valid(profile):
fields = ("parameter_conversion_ns", "parameter_conversion_calls", "ffi_call_ns",
"ffi_calls", "result_conversion_ns", "result_conversion_calls")
return (isinstance(profile, dict) and profile.get("valid") is True
and profile.get("scope") == "go_query_parameter_native_call_result_phases"
and all(type(profile.get(key)) is int and 0 <= profile[key] < 2**64 for key in fields)
and profile["result_conversion_calls"] == profile["ffi_calls"]
and profile["ffi_calls"] <= profile["parameter_conversion_calls"])
def go_host_profile_valid(result, required):
if result["status"] != "ok":
return None
profile = result.get("go_host_profile")
if result["layer"] != "go" or not required:
return profile is None
if not go_host_counters_valid(profile):
return False
count, case = result.get("size"), result.get("case")
if type(count) is not int or count < 1 or case not in CASES:
return False
calls = count + 1 if case == "fill" else 2 if case == "fill_bulk" else count if case == "point" else 1
return all(profile[key] == calls for key in (
"parameter_conversion_calls", "ffi_calls", "result_conversion_calls"))
def failure_go_host_profile_valid(result, required):
if result["status"] == "ok":
return None
profile = result.get("failure_go_host_profile")
if result["layer"] != "go" or not required:
return False if profile is not None else None
return (result.get("failure_go_host_profile_scope") ==
"db_query_calls_including_setup_warmup_and_cleanup"
and go_host_counters_valid(profile))
def qualified_record(result):
return (result["status"] == "ok" and result["parity"]
and result["process_exit"] == 0 and result["profile_valid"] is True
and result["phase_timing_valid"] is True
and result.get("go_host_profile_valid", True) is True)
def run_child(command, artifact):
started = time.monotonic()
timer = ["/usr/bin/time", "-l"] if sys.platform == "darwin" else ["/usr/bin/time", "-v"]
with artifact.with_suffix(".stdout").open("w") as stdout, artifact.with_suffix(".stderr").open("w") as stderr:
environment = os.environ.copy()
runfiles = pathlib.Path(command[0] + ".runfiles")
if runfiles.is_dir():
for key in ("RUNFILES_MANIFEST_FILE", "JAVA_RUNFILES", "PYTHONPATH", "PYTHONHOME"):
environment.pop(key, None)
environment.update(RUNFILES_DIR=str(runfiles), PYTHONDONTWRITEBYTECODE="1")
process = subprocess.Popen(timer + command, cwd=ROOT, stdout=stdout, stderr=stderr,
env=environment)
return_code = process.wait()
lines = artifact.with_suffix(".stdout").read_text().splitlines()
try:
result = json.loads(lines[-1])
except (ValueError, IndexError):
result = {"status": "process_error", "error": "missing result JSON"}
native = artifact.with_suffix(".stderr").read_text()
peak = re.search(r"(\d+)\s+maximum resident set size", native) if sys.platform == "darwin" else re.search(r"Maximum resident set size \(kbytes\):\s*(\d+)", native)
result.update({"process_exit": return_code, "process_seconds": time.monotonic() - started,
"command": command, "stdout": str(artifact.with_suffix(".stdout")),
"stderr": str(artifact.with_suffix(".stderr")),
"process_peak_rss_bytes": int(peak[1]) * (1 if sys.platform == "darwin" else 1024) if peak else None})
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=pathlib.Path, required=True)
parser.add_argument("--sizes", default="1000,100000,1000000")
parser.add_argument("--cases", default=",".join(CASES))
parser.add_argument("--backends", default="memory,file")
parser.add_argument("--layers", default="rust,python,go")
parser.add_argument("--samples", type=int, default=3)
parser.add_argument("--rust", type=pathlib.Path, default=ROOT / "bazel-bin/hawdb_bench_host_boundary")
parser.add_argument("--python", type=pathlib.Path, default=ROOT / "bazel-bin/bindings/benchmarks/python_boundary")
parser.add_argument("--go", type=pathlib.Path)
parser.add_argument("--library", type=pathlib.Path)
parser.add_argument("--python-extension", type=pathlib.Path)
parser.add_argument("--native-profiles", action="store_true",
help="require native counters from all three instrumented artifacts")
parser.add_argument("--cpu-profiles", action="store_true")
parser.add_argument("--go-host-profiles", action="store_true",
help="require compile-tagged Go JSON/FFI phase counters with --native-profiles")
args = parser.parse_args()
sizes = [int(size) for size in args.sizes.split(",")]
cases = args.cases.split(",")
backends = args.backends.split(",")
layers = args.layers.split(",")
if args.samples < 1 or any(size < 1 for size in sizes) or set(cases) - set(CASES) or set(backends) - {"memory", "file"}:
parser.error("positive sizes/samples and known cases/backends are required")
if set(layers) - {"rust", "python", "go"} or len(set(layers)) != len(layers):
parser.error("known, distinct layers are required")
if args.native_profiles and args.python_extension is None:
parser.error("--native-profiles requires an explicit instrumented --python-extension")
if args.go_host_profiles and (not args.native_profiles or "go" not in layers):
parser.error("--go-host-profiles requires --native-profiles and the go layer")
args.output.mkdir(parents=True, exist_ok=False)
identity = source_identity()
if args.go is None:
target = "//bindings/go/cmd/boundary:boundary_profile" if args.go_host_profiles else "//bindings/go/cmd/boundary"
args.go = ROOT / command_text("bazel", "cquery", "-c", "opt", target, "--output=files")
library = args.library or ROOT / "bazel-bin/bindings/ffi" / ("libhawdb_ffi.dylib" if sys.platform == "darwin" else "libhawdb_ffi.so")
args.rust, args.python, args.go, library = (path.resolve() for path in (args.rust, args.python, args.go, library))
if args.python_extension is None:
args.python_extension = pathlib.Path(str(args.python) + ".runfiles") / "_main/bindings/python/python/hawdb/_hawdb.so"
args.python_extension = args.python_extension.resolve()
if not args.python_extension.is_file():
parser.error("build the matching Python extension or pass --python-extension: " + str(args.python_extension))
commands = {"rust": [str(args.rust)], "python": [str(args.python)], "go": [str(args.go)]}
commands = {layer: commands[layer] for layer in layers}
for path in (args.rust, args.python, args.go, library):
if not path.is_file():
parser.error("build the matching benchmark first: " + str(path))
artifact_paths = (args.rust, args.python, args.go, library, args.python_extension)
artifacts = artifact_identity(artifact_paths)
report = {
"source": identity, "spec": "ZERO_COPY_COLUMNAR_INTERCHANGE_SPEC.md",
"seed": SEED, "sizes": sizes, "cases": cases, "backends": backends,
"layers": layers,
"samples": args.samples, "discarded_iterations": 1,
"os": platform.platform(), "machine": platform.machine(),
"cpu": command_text("sysctl", "-n", "machdep.cpu.brand_string") if sys.platform == "darwin" else platform.processor(),
"rust": command_text("rustc", "--version"), "go": command_text("go", "version"),
"build": "Bazel opt, all three engine dependencies compiled together",
"defaults_changed": False, "strict_zero_copy": False, "terminal": False,
"instrumented": args.native_profiles or args.cpu_profiles or args.go_host_profiles,
"go_host_profiles": args.go_host_profiles,
"native_profiles": args.native_profiles, "go_cpu_profiles": args.cpu_profiles,
"binaries": {layer: {"path": command[0], "sha256": artifacts[command[0]]} for layer, command in commands.items()},
"library_sha256": artifacts[str(library)],
"python_extension_path": str(args.python_extension),
"python_extension_sha256": artifacts[str(args.python_extension)],
"records": [], "summaries": [],
"measurement_limits": [
"A selected layer/backend shard qualifies only its recorded groups; full-matrix acceptance requires complete coverage across shards.",
"Process peak RSS includes runtime, fixture, setup and query; it is not a query-only allocation ledger.",
"Allocator observations count Rust requests; Go/Python heaps and non-Rust workspace are separate." if args.native_profiles else "Go allocation counts exclude the native engine; run the separately instrumented matrix for native/Python profiles.",
"Each iteration opens its own store; seeded read runs measure a warm store, not cold artifact reads.",
"Write cases include a final verification query in query_boundary_ns; write_boundary_ns and read_boundary_ns separate the phases without removing calls.",
"The query timer excludes the identical checksum algorithm; consumer time is reported separately.",
],
}
destination = args.output / "report.json"
def save():
destination.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
def check_artifacts():
try:
require_artifact_identity(artifact_paths, artifacts)
except (OSError, RuntimeError) as error:
report["qualification_error"] = str(error)
save()
raise
save()
parity_failures = 0
for count in sizes:
for case in cases:
data = fixture(count, case)
for backend in backends:
for iteration in range(args.samples + 1):
layers = list(commands)
offset = iteration % len(layers)
for layer in layers[offset:] + layers[:offset]:
if source_identity() != identity:
raise RuntimeError("source changed during qualification")
check_artifacts()
stem = "%s-%s-%d-%s-%d" % (layer, case, count, backend, iteration)
job_path = args.output / (stem + ".job.json")
job = dict(data, backend=backend, path=str(args.output / (stem + ".db")))
if args.cpu_profiles and layer == "go":
job["cpu_profile_path"] = str(args.output / (stem + ".cpu.pprof"))
job_path.write_text(json.dumps(job, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
command = commands[layer] + [str(job_path)] + ([str(library)] if layer == "go" else [])
if layer == "python":
command.append(str(args.python_extension))
result = run_child(command, args.output / stem)
result.update({"layer": layer, "case": case, "size": count, "backend": backend, "iteration": iteration,
"discarded": iteration == 0, "fixture_sha256": hashlib.sha256(job_path.read_bytes()).hexdigest(),
"expected_checksum": data["expected_checksum"]})
if result["status"] == "ok":
result["parity"] = result.get("checksum") == data["expected_checksum"] and result.get("output_rows") == count
parity_failures += not result["parity"]
else:
result["parity"] = None
timings = ("query_boundary_ns", "write_boundary_ns", "read_boundary_ns")
result["phase_timing_valid"] = (
all(type(result.get(key)) is int and result[key] >= 0 for key in timings)
and result["query_boundary_ns"] == result["write_boundary_ns"] + result["read_boundary_ns"]
and (case in ("fill", "fill_bulk") or result["write_boundary_ns"] == 0)
) if result["status"] == "ok" else None
result["profile_valid"] = native_profile_valid(result, layer, args.native_profiles)
result["failure_profile_valid"] = failure_profile_valid(result, layer, args.native_profiles)
result["go_host_profile_valid"] = go_host_profile_valid(result, args.go_host_profiles)
result["failure_go_host_profile_valid"] = failure_go_host_profile_valid(result, args.go_host_profiles)
report["records"].append(result)
save()
check_artifacts()
print(stem, result["status"], result["parity"], flush=True)
job_path.unlink() if backend == "file":
import shutil
shutil.rmtree(job["path"], ignore_errors=False) if pathlib.Path(job["path"]).exists() else None
for layer in commands:
records = [r for r in report["records"] if r["case"] == case and r["size"] == count and r["backend"] == backend and r["layer"] == layer and not r["discarded"]]
valid = [r for r in records if qualified_record(r)]
report["summaries"].append({"layer": layer, "case": case, "size": count, "backend": backend,
"successful_samples": len(valid), "failed_samples": len(records) - len(valid),
"median_query_boundary_ns": statistics.median(r["query_boundary_ns"] for r in valid) if valid else None,
"median_write_boundary_ns": statistics.median(r["write_boundary_ns"] for r in valid) if valid else None,
"median_read_boundary_ns": statistics.median(r["read_boundary_ns"] for r in valid) if valid else None,
"median_elapsed_ns": statistics.median(r["elapsed_ns"] for r in valid) if valid else None})
save()
del data
if source_identity() != identity:
raise RuntimeError("source changed before completion")
check_artifacts()
report.update(terminal=True, parity_failures=parity_failures,
value_parity_records=sum(r["status"] == "ok" and r["parity"] for r in report["records"]),
successful_records=sum(qualified_record(r) for r in report["records"]),
refused_or_failed_records=sum(r["status"] != "ok" for r in report["records"]))
save()
report["profile_failures"] = sum(r["profile_valid"] is False for r in report["records"])
report["failure_profile_failures"] = sum(r["failure_profile_valid"] is False for r in report["records"])
report["go_host_profile_failures"] = sum(r["go_host_profile_valid"] is False for r in report["records"])
report["failure_go_host_profile_failures"] = sum(r["failure_go_host_profile_valid"] is False for r in report["records"])
report["phase_timing_failures"] = sum(r["phase_timing_valid"] is False for r in report["records"])
report["all_paths_succeeded"] = all(qualified_record(r) for r in report["records"])
save()
return int(not report["all_paths_succeeded"])
if __name__ == "__main__":
sys.exit(main())