#!/usr/bin/env python3 """Measure disposable native clients/servers; never install or alter a real project.""" import argparse import datetime import hashlib import json import math import os from pathlib import Path import platform import shutil import statistics import subprocess import sys import time def distribution(samples): ordered = sorted(samples) return {"samples": len(samples), "minMs": ordered[0], "p50Ms": statistics.median(samples), "p95Ms": ordered[math.ceil(len(samples) * .95) - 1], "maxMs": ordered[-1], "rawMs": samples} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--binary", type=Path, required=True) parser.add_argument("--baseline", type=Path, required=True) parser.add_argument("--directory", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--samples", type=int, default=100) parser.add_argument("--starts", type=int, default=10) parser.add_argument("--fixture", type=Path, help="Copy a previously generated, stopped synthetic fixture into the new directory.") parser.add_argument("--server-baseline", type=Path, help="Also compare a preserved server package, such as the pre-SSE build.") args = parser.parse_args() if args.samples < 20 or args.starts < 5: parser.error("Use at least 20 samples and 5 starts") binary, baseline = args.binary.resolve(strict=True), args.baseline.resolve(strict=True) root = args.directory.absolute() root.mkdir(parents=True, exist_ok=False) dataset = root / "nominal" roots = [dataset] def run(directory, *command, executable=binary): before = time.perf_counter_ns() result = subprocess.run([str(executable), *command], cwd=directory, text=True, capture_output=True, timeout=60) elapsed = (time.perf_counter_ns() - before) / 1_000_000 if result.returncode: raise RuntimeError(f"{command}: exit {result.returncode}: {result.stderr}") return result.stdout, elapsed def stop(directory): if (directory / ".ai-engineering").exists(): run(directory, "stop", "--timeout-seconds", "10") report = {"observedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), "environment": {"platform": platform.platform(), "machine": platform.machine(), "logicalCpus": os.cpu_count(), "initialLoadAverage": os.getloadavg()}, "method": {"works": 100, "notesPerWork": 10, "storage": "sqlite", "git": False, "provider": False, "freshClientPerSample": True, "percentile": "nearest rank", "cold": "process cold; OS file caches not flushed"}, "candidate": {"path": str(binary), "sha256": hashlib.sha256(binary.read_bytes()).hexdigest(), "package": json.loads((binary.parent / "aie-package.json").read_text())}, "baseline": {"path": str(baseline), "sha256": hashlib.sha256(baseline.read_bytes()).hexdigest()}} if sys.platform == "darwin": for key, name in (("cpu", "machdep.cpu.brand_string"), ("physicalMemoryBytes", "hw.memsize")): report["environment"][key] = subprocess.check_output(["/usr/sbin/sysctl", "-n", name], text=True).strip() try: if args.fixture: source = args.fixture.resolve(strict=True) status = json.loads(run(source, "server", "status")[0]) if status["state"] != "STOPPED": raise RuntimeError("Stop the synthetic source fixture before copying") print("Copying the stopped synthetic dataset; operational server state excluded...", flush=True) shutil.copytree(source, dataset, ignore=shutil.ignore_patterns(".local")) report["method"]["copiedFixture"] = str(source) else: print("Generating 100 Works and 1,000 notes through the public CLI...", flush=True) subprocess.run([sys.executable, str(Path(__file__).with_name("latency-fixture.py")), "--binary", str(binary), "--directory", str(dataset), "--works", "100", "--entries", "10"], check=True, stdout=subprocess.DEVNULL, timeout=1800) report["fixture"] = json.loads((dataset / "latency-fixture.json").read_text()) if report["fixture"]["works"] != 100 or report["fixture"]["entriesPerWork"] != 10: raise RuntimeError("Expected the nominal 100 Work / 10 note fixture") command = ("work", "show", "WRK-0064", "--format", "json") report["method"]["command"] = list(command) expected = json.loads(run(dataset, *command)[0]) def sample(executable=binary): output, milliseconds = run(dataset, *command, executable=executable) if json.loads(output) != expected: raise RuntimeError("Benchmark output differs between invocations/builds") return milliseconds print("Measuring process-cold readiness and automatic first use...", flush=True) starts, first = [], [] for _ in range(args.starts): stop(dataset) starts.append(run(dataset, "start")[1]) stop(dataset) first.append(sample()) report["readiness"] = distribution(starts) report["firstUse"] = distribution(first) print("Measuring ready-server roundtrips...", flush=True) for _ in range(10): sample() report["warm"] = distribution([sample() for _ in range(args.samples)]) print("Measuring preserved per-call native baseline against identical records...", flush=True) stop(dataset) for _ in range(5): sample(baseline) report["baseline"]["version"] = run(dataset, "--version", executable=baseline)[0].strip() report["baseline"]["roundtrip"] = distribution([sample(baseline) for _ in range(args.samples)]) if args.server_baseline: previous = args.server_baseline.resolve(strict=True) print("Measuring the preserved server implementation on identical records...", flush=True) run(dataset, "start", executable=previous) try: for _ in range(10): sample(previous) report["serverBaseline"] = {"path": str(previous), "sha256": hashlib.sha256(previous.read_bytes()).hexdigest(), "package": json.loads((previous.parent / "aie-package.json").read_text()), "roundtrip": distribution([sample(previous) for _ in range(args.samples)])} finally: run(dataset, "stop", "--timeout-seconds", "10", executable=previous) print("Measuring idle resident memory for 1/5/10 active projects...", flush=True) run(dataset, "start") sample() report["method"]["memoryWorkload"] = "Fresh server then work show per project; first project has 100 Works/1000 notes, remaining projects one Work each. Summed process RSS, shared pages may be counted repeatedly." report["memory"] = [] for count in range(1, 11): if count > 1: project = root / ("project-" + str(count)) project.mkdir() roots.append(project) run(project, "init", "--name", "Disposable memory project " + str(count)) run(project, "work", "create", "One resident Work") stop(project) run(project, "start") run(project, "work", "show", "WRK-0001", "--format", "json") if count in (1, 5, 10): time.sleep(1) processes = [] for project in roots: status = json.loads(run(project, "server", "status")[0]) if status["state"] != "RUNNING": raise RuntimeError("Memory fixture server is not running") pid = status["server"]["pid"] rss_kib = int(subprocess.check_output(["/bin/ps", "-o", "rss=", "-p", str(pid)], text=True).strip()) processes.append({"pid": pid, "rssMiB": rss_kib / 1024}) report["memory"].append({"projects": count, "processes": processes, "totalRssMiB": sum(item["rssMiB"] for item in processes)}) report["acceptance"] = {"warmP95AtMost100Ms": report["warm"]["p95Ms"] <= 100, "allReadinessAtMost1000Ms": report["readiness"]["maxMs"] <= 1000} args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(report, indent=2) + "\n") print(json.dumps({"warm": {k: v for k, v in report["warm"].items() if k != "rawMs"}, "readiness": {k: v for k, v in report["readiness"].items() if k != "rawMs"}, "acceptance": report["acceptance"]}, indent=2), flush=True) return 0 if all(report["acceptance"].values()) else 1 finally: for project in reversed(roots): stop(project) if __name__ == "__main__": sys.exit(main())