264 lines
9.2 KiB
Python
264 lines
9.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Track 1: measure in-memory architecture limits.
|
|
|
|
Closed-loop workload with a mix of paginated reads (random cursor depth)
|
|
and writes. Iterates over history sizes and concurrency levels in one
|
|
process, so the server is seeded once per history size.
|
|
|
|
Requires the server to already run with the desired PAGINATION_MODE.
|
|
Use --docker-container to sample RSS via ``docker stats`` (Windows friendly).
|
|
"""
|
|
import argparse
|
|
import json
|
|
import math
|
|
import random
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
|
from client import Client, Failure # noqa: E402
|
|
|
|
|
|
def pct(sorted_values, p):
|
|
if not sorted_values:
|
|
return None
|
|
idx = max(0, math.ceil(p * len(sorted_values)) - 1)
|
|
return round(1000 * sorted_values[idx], 3)
|
|
|
|
|
|
def read_rss_kb(pid):
|
|
try:
|
|
text = Path("/proc/%d/status" % pid).read_text()
|
|
except OSError:
|
|
return None
|
|
for line in text.splitlines():
|
|
if line.startswith("VmRSS:"):
|
|
return int(line.split()[1])
|
|
return None
|
|
|
|
|
|
def docker_rss_kb(container):
|
|
"""Return MiB/KiB value from `docker stats --no-stream` as KB."""
|
|
try:
|
|
out = subprocess.run(
|
|
["docker", "stats", "--no-stream",
|
|
"--format", "{{.MemUsage}}", container],
|
|
capture_output=True, text=True, timeout=15).stdout.strip()
|
|
except Exception:
|
|
return None
|
|
if not out or "/" not in out:
|
|
return None
|
|
used = out.split("/")[0].strip()
|
|
for suffix, factor in (("GiB", 1024 * 1024), ("MiB", 1024),
|
|
("KiB", 1), ("B", 1 / 1024)):
|
|
if used.endswith(suffix):
|
|
try:
|
|
return int(float(used[:-len(suffix)]) * factor)
|
|
except ValueError:
|
|
return None
|
|
return None
|
|
|
|
|
|
def sample_rss(args):
|
|
if args.server_pid:
|
|
return read_rss_kb(args.server_pid)
|
|
if args.docker_container:
|
|
return docker_rss_kb(args.docker_container)
|
|
return None
|
|
|
|
|
|
def prepopulate(client, actor, chat, count, existing, progress_every=2000):
|
|
if existing >= count:
|
|
return existing
|
|
t0 = time.monotonic()
|
|
for i in range(existing, count):
|
|
client.message(actor, chat, "seed-%08d" % i)
|
|
if progress_every and (i + 1) % progress_every == 0:
|
|
print(" seeded %d/%d (%.1fs)"
|
|
% (i + 1, count, time.monotonic() - t0),
|
|
file=sys.stderr)
|
|
return count
|
|
|
|
|
|
def collect_cursors(client, actor, chat, page_limit=50):
|
|
cursors = []
|
|
path = "/api/v1/chats/%s/messages?limit=%d" % (chat["id"], page_limit)
|
|
while True:
|
|
page = client.call("GET", path, actor=actor,
|
|
schema="MessagePage")["json"]
|
|
nxt = page["next_cursor"]
|
|
if nxt is None:
|
|
break
|
|
cursors.append(nxt)
|
|
path = "/api/v1/chats/%s/messages?limit=%d&cursor=%s" % (
|
|
chat["id"], page_limit, nxt)
|
|
return cursors
|
|
|
|
|
|
def op_once(client, actor, chat, cursors, rng, read_ratio):
|
|
if cursors and rng.random() < read_ratio:
|
|
cur = rng.choice(cursors)
|
|
start = time.monotonic()
|
|
client.call("GET",
|
|
"/api/v1/chats/%s/messages?limit=50&cursor=%s"
|
|
% (chat["id"], cur),
|
|
actor=actor, schema="MessagePage")
|
|
return "read", time.monotonic() - start
|
|
start = time.monotonic()
|
|
client.message(actor, chat, "load-" + uuid.uuid4().hex[:8])
|
|
return "write", time.monotonic() - start
|
|
|
|
|
|
def run_one(args, alice, chat, history, cursors, concurrency):
|
|
barrier = threading.Barrier(concurrency)
|
|
results = [None] * concurrency
|
|
|
|
def worker(wid):
|
|
local = Client(args.base_url, timeout=15)
|
|
rng = random.Random(0xC0FFEE + wid)
|
|
read_lat, write_lat = [], []
|
|
read_err = write_err = 0
|
|
w_deadline = time.monotonic() + args.warmup
|
|
while time.monotonic() < w_deadline:
|
|
try:
|
|
op_once(local, alice, chat, cursors, rng, args.read_ratio)
|
|
except Failure:
|
|
pass
|
|
barrier.wait()
|
|
deadline = time.monotonic() + args.duration
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
kind, dt_s = op_once(local, alice, chat, cursors,
|
|
rng, args.read_ratio)
|
|
except Failure:
|
|
if rng.random() < args.read_ratio:
|
|
read_err += 1
|
|
else:
|
|
write_err += 1
|
|
continue
|
|
(read_lat if kind == "read" else write_lat).append(dt_s)
|
|
results[wid] = (read_lat, write_lat, read_err, write_err)
|
|
|
|
started = time.monotonic()
|
|
threads = [threading.Thread(target=worker, args=(i,))
|
|
for i in range(concurrency)]
|
|
for t in threads:
|
|
t.start()
|
|
for t in threads:
|
|
t.join()
|
|
elapsed = time.monotonic() - started
|
|
|
|
read_all, write_all = [], []
|
|
read_err_total = write_err_total = 0
|
|
for chunk in results:
|
|
r_lat, w_lat, r_err, w_err = chunk
|
|
read_all.extend(r_lat)
|
|
write_all.extend(w_lat)
|
|
read_err_total += r_err
|
|
write_err_total += w_err
|
|
read_all.sort()
|
|
write_all.sort()
|
|
|
|
return {
|
|
"history": history,
|
|
"concurrency": concurrency,
|
|
"duration_s": args.duration,
|
|
"elapsed_s": round(elapsed, 3),
|
|
"read_ratio": args.read_ratio,
|
|
"cursors": len(cursors),
|
|
"reads": {
|
|
"success": len(read_all),
|
|
"errors": read_err_total,
|
|
"rps": round(len(read_all) / elapsed, 2),
|
|
"p50_ms": pct(read_all, 0.50),
|
|
"p95_ms": pct(read_all, 0.95),
|
|
"p99_ms": pct(read_all, 0.99),
|
|
},
|
|
"writes": {
|
|
"success": len(write_all),
|
|
"errors": write_err_total,
|
|
"rps": round(len(write_all) / elapsed, 2),
|
|
"p50_ms": pct(write_all, 0.50),
|
|
"p95_ms": pct(write_all, 0.95),
|
|
"p99_ms": pct(write_all, 0.99),
|
|
},
|
|
"total_ops": len(read_all) + len(write_all) + read_err_total + write_err_total,
|
|
"error_ratio": round(
|
|
(read_err_total + write_err_total) /
|
|
max(1, len(read_all) + len(write_all) + read_err_total + write_err_total),
|
|
6),
|
|
}
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--base-url", default="http://localhost:8080")
|
|
ap.add_argument("--history", default="1000,5000,20000",
|
|
help="comma-separated history sizes")
|
|
ap.add_argument("--concurrency", default="1,4,16",
|
|
help="comma-separated concurrency levels")
|
|
ap.add_argument("--duration", type=float, default=15.0)
|
|
ap.add_argument("--warmup", type=float, default=2.0)
|
|
ap.add_argument("--read-ratio", type=float, default=0.8)
|
|
ap.add_argument("--server-pid", type=int, default=None,
|
|
help="server PID for /proc RSS sampling (Linux)")
|
|
ap.add_argument("--docker-container", default=None,
|
|
help="container name for `docker stats` RSS sampling")
|
|
ap.add_argument("--mode", default=None, help="label: linear | index")
|
|
ap.add_argument("--output-dir", default="evidence")
|
|
args = ap.parse_args()
|
|
|
|
histories = [int(x) for x in args.history.split(",") if x.strip()]
|
|
concurrencies = [int(x) for x in args.concurrency.split(",") if x.strip()]
|
|
label = args.mode or "run"
|
|
|
|
c = Client(args.base_url)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
print("chat=%s" % chat["id"], file=sys.stderr)
|
|
|
|
out_dir = Path(args.output_dir)
|
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
seeded = 0
|
|
summaries = []
|
|
for history in histories:
|
|
print("== history=%d ==" % history, file=sys.stderr)
|
|
seeded = prepopulate(c, alice, chat, history, seeded)
|
|
cursors = collect_cursors(c, bob, chat)
|
|
rss_after_seed = sample_rss(args)
|
|
print(" cursors=%d rss_kb=%s"
|
|
% (len(cursors), rss_after_seed), file=sys.stderr)
|
|
for concurrency in concurrencies:
|
|
print(" -- concurrency=%d" % concurrency, file=sys.stderr)
|
|
r = run_one(args, alice, chat, history, cursors, concurrency)
|
|
r["rss_kb_after_seed"] = rss_after_seed
|
|
r["rss_kb_end"] = sample_rss(args)
|
|
r["mode"] = label
|
|
summaries.append(r)
|
|
out = out_dir / ("%s_h%d_c%d.json"
|
|
% (label, history, concurrency))
|
|
out.write_text(json.dumps(r, indent=2) + "\n")
|
|
print(json.dumps({
|
|
"mode": r["mode"], "history": r["history"],
|
|
"concurrency": r["concurrency"],
|
|
"read_rps": r["reads"]["rps"],
|
|
"read_p95_ms": r["reads"]["p95_ms"],
|
|
"read_p99_ms": r["reads"]["p99_ms"],
|
|
"write_rps": r["writes"]["rps"],
|
|
"write_p95_ms": r["writes"]["p95_ms"],
|
|
"write_p99_ms": r["writes"]["p99_ms"],
|
|
"err_ratio": r["error_ratio"],
|
|
"rss_kb_end": r["rss_kb_end"],
|
|
}))
|
|
|
|
combined = out_dir / ("%s_summary.json" % label)
|
|
combined.write_text(json.dumps(summaries, indent=2) + "\n")
|
|
print("combined summary: %s" % combined, file=sys.stderr)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |