337 lines
10 KiB
Python
337 lines
10 KiB
Python
import argparse
|
|
import json
|
|
import math
|
|
import threading
|
|
import time
|
|
import uuid
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
import httpx
|
|
|
|
|
|
def percentile(values: list[float], percent: float) -> float:
|
|
if not values:
|
|
return 0.0
|
|
ordered = sorted(values)
|
|
index = math.ceil(len(ordered) * percent / 100) - 1
|
|
index = max(0, min(index, len(ordered) - 1))
|
|
return round(ordered[index], 3)
|
|
|
|
|
|
def require_json(response: httpx.Response, expected_status: int) -> dict:
|
|
if response.status_code != expected_status:
|
|
raise RuntimeError(
|
|
f"{response.request.method} {response.request.url} returned "
|
|
f"{response.status_code}, expected {expected_status}: {response.text}"
|
|
)
|
|
return response.json()
|
|
|
|
|
|
def create_fixture(
|
|
base_url: str,
|
|
history_size: int,
|
|
) -> tuple[str, str]:
|
|
suffix = uuid.uuid4().hex[:12]
|
|
|
|
with httpx.Client(base_url=base_url, timeout=30.0) as client:
|
|
user = require_json(
|
|
client.post(
|
|
"/api/v1/users",
|
|
json={
|
|
"username": f"bench_{suffix}",
|
|
"display_name": "Benchmark User",
|
|
},
|
|
),
|
|
201,
|
|
)
|
|
user_id = user["id"]
|
|
|
|
chat = require_json(
|
|
client.post(
|
|
"/api/v1/chats",
|
|
headers={"X-User-Id": user_id},
|
|
json={
|
|
"title": "Benchmark chat",
|
|
"member_ids": [user_id],
|
|
},
|
|
),
|
|
201,
|
|
)
|
|
chat_id = chat["id"]
|
|
|
|
headers = {"X-User-Id": user_id, "Connection": "close"}
|
|
|
|
for number in range(history_size):
|
|
last_error = None
|
|
|
|
for attempt in range(3):
|
|
try:
|
|
with httpx.Client(base_url=base_url, timeout=30.0) as client:
|
|
response = client.post(
|
|
f"/api/v1/chats/{chat_id}/messages",
|
|
headers=headers,
|
|
json={"text": f"synthetic-{number:06d}"},
|
|
)
|
|
|
|
if response.status_code == 201:
|
|
break
|
|
|
|
last_error = RuntimeError(
|
|
f"message {number}: got {response.status_code}: {response.text}"
|
|
)
|
|
|
|
except httpx.HTTPError as error:
|
|
last_error = error
|
|
|
|
time.sleep(0.05 * (attempt + 1))
|
|
else:
|
|
raise RuntimeError(
|
|
f"fixture failed at message {number} after 3 attempts: {last_error}"
|
|
)
|
|
|
|
if (number + 1) % 1000 == 0 or number + 1 == history_size:
|
|
print(f"fixture progress: {number + 1}/{history_size}")
|
|
|
|
return user_id, chat_id
|
|
|
|
def get_metrics(base_url: str) -> dict:
|
|
with httpx.Client(base_url=base_url, timeout=10.0) as client:
|
|
return require_json(client.get("/internal/metrics"), 200)
|
|
|
|
|
|
def prepare_deep_cursor(
|
|
base_url: str,
|
|
user_id: str,
|
|
chat_id: str,
|
|
history_size: int,
|
|
page_limit: int,
|
|
depth_fraction: float,
|
|
) -> str:
|
|
pages_before_cursor = max(
|
|
1,
|
|
int(history_size * depth_fraction) // page_limit,
|
|
)
|
|
|
|
cursor = None
|
|
headers = {"X-User-Id": user_id}
|
|
|
|
with httpx.Client(base_url=base_url, timeout=30.0) as client:
|
|
for _ in range(pages_before_cursor):
|
|
params = {"limit": page_limit}
|
|
if cursor is not None:
|
|
params["cursor"] = cursor
|
|
|
|
body = require_json(
|
|
client.get(
|
|
f"/api/v1/chats/{chat_id}/messages",
|
|
headers=headers,
|
|
params=params,
|
|
),
|
|
200,
|
|
)
|
|
cursor = body["next_cursor"]
|
|
|
|
if cursor is None:
|
|
raise RuntimeError(
|
|
"history ended before requested cursor depth; "
|
|
"start with a fresh container"
|
|
)
|
|
|
|
return cursor
|
|
|
|
|
|
def run_requests(
|
|
base_url: str,
|
|
user_id: str,
|
|
chat_id: str,
|
|
cursor: str,
|
|
page_limit: int,
|
|
concurrency: int,
|
|
seconds: int,
|
|
record_latencies: bool,
|
|
) -> tuple[int, int, list[float], dict[str, int]]:
|
|
deadline = time.perf_counter() + seconds
|
|
lock = threading.Lock()
|
|
|
|
successes = 0
|
|
failures = 0
|
|
latencies: list[float] = []
|
|
status_counts: dict[str, int] = {}
|
|
|
|
def worker() -> None:
|
|
nonlocal successes, failures
|
|
|
|
headers = {"X-User-Id": user_id}
|
|
with httpx.Client(base_url=base_url, timeout=10.0) as client:
|
|
while time.perf_counter() < deadline:
|
|
started = time.perf_counter()
|
|
try:
|
|
response = client.get(
|
|
f"/api/v1/chats/{chat_id}/messages",
|
|
headers=headers,
|
|
params={"limit": page_limit, "cursor": cursor},
|
|
)
|
|
elapsed_ms = (time.perf_counter() - started) * 1000
|
|
|
|
with lock:
|
|
key = str(response.status_code)
|
|
status_counts[key] = status_counts.get(key, 0) + 1
|
|
|
|
if response.status_code == 200:
|
|
successes += 1
|
|
if record_latencies:
|
|
latencies.append(elapsed_ms)
|
|
else:
|
|
failures += 1
|
|
|
|
except httpx.HTTPError:
|
|
with lock:
|
|
failures += 1
|
|
status_counts["transport_error"] = (
|
|
status_counts.get("transport_error", 0) + 1
|
|
)
|
|
|
|
with ThreadPoolExecutor(max_workers=concurrency) as executor:
|
|
futures = [executor.submit(worker) for _ in range(concurrency)]
|
|
for future in futures:
|
|
future.result()
|
|
|
|
return successes, failures, latencies, status_counts
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(
|
|
description="Track 1: deep cursor benchmark for in-memory message history."
|
|
)
|
|
parser.add_argument("--base-url", required=True)
|
|
parser.add_argument("--history-size", type=int, required=True)
|
|
parser.add_argument("--concurrency", type=int, required=True)
|
|
parser.add_argument("--warmup-seconds", type=int, default=5)
|
|
parser.add_argument("--duration-seconds", type=int, default=15)
|
|
parser.add_argument("--page-limit", type=int, default=100)
|
|
parser.add_argument("--depth-fraction", type=float, default=0.8)
|
|
parser.add_argument("--implementation", required=True)
|
|
parser.add_argument("--git-commit", required=True)
|
|
parser.add_argument("--output", required=True)
|
|
args = parser.parse_args()
|
|
|
|
if args.history_size < args.page_limit * 2:
|
|
raise SystemExit("history-size must contain at least two pages")
|
|
if args.concurrency < 1:
|
|
raise SystemExit("concurrency must be >= 1")
|
|
if not 0.1 <= args.depth_fraction < 1.0:
|
|
raise SystemExit("depth-fraction must be in [0.1, 1.0)")
|
|
|
|
print(
|
|
f"fixture: history={args.history_size}, "
|
|
f"concurrency={args.concurrency}, "
|
|
f"deep cursor={args.depth_fraction:.0%}"
|
|
)
|
|
|
|
user_id, chat_id = create_fixture(args.base_url, args.history_size)
|
|
|
|
metrics_before = get_metrics(args.base_url)
|
|
if metrics_before["messages"] != args.history_size:
|
|
raise RuntimeError(
|
|
f"expected exactly {args.history_size} messages, got "
|
|
f"{metrics_before['messages']}. "
|
|
"Run each scenario in a fresh container."
|
|
)
|
|
|
|
cursor = prepare_deep_cursor(
|
|
args.base_url,
|
|
user_id,
|
|
chat_id,
|
|
args.history_size,
|
|
args.page_limit,
|
|
args.depth_fraction,
|
|
)
|
|
|
|
print(f"warmup: {args.warmup_seconds}s")
|
|
run_requests(
|
|
args.base_url,
|
|
user_id,
|
|
chat_id,
|
|
cursor,
|
|
args.page_limit,
|
|
args.concurrency,
|
|
args.warmup_seconds,
|
|
record_latencies=False,
|
|
)
|
|
|
|
print(f"measurement: {args.duration_seconds}s")
|
|
started_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
|
successes, failures, latencies, status_counts = run_requests(
|
|
args.base_url,
|
|
user_id,
|
|
chat_id,
|
|
cursor,
|
|
args.page_limit,
|
|
args.concurrency,
|
|
args.duration_seconds,
|
|
record_latencies=True,
|
|
)
|
|
|
|
metrics_after = get_metrics(args.base_url)
|
|
attempted = successes + failures
|
|
|
|
result = {
|
|
"experiment": "track1-inmemory-deep-cursor",
|
|
"timestamp_utc": started_at,
|
|
"implementation": args.implementation,
|
|
"git_commit": args.git_commit,
|
|
"container_limits": {
|
|
"cpus": 2,
|
|
"memory": "512m",
|
|
},
|
|
"workload": {
|
|
"endpoint": "GET /api/v1/chats/{chat_id}/messages",
|
|
"history_size": args.history_size,
|
|
"page_limit": args.page_limit,
|
|
"cursor_depth_fraction": args.depth_fraction,
|
|
"concurrency": args.concurrency,
|
|
"warmup_seconds": args.warmup_seconds,
|
|
"duration_seconds": args.duration_seconds,
|
|
"writes_during_measurement": False,
|
|
"client": "httpx synchronous client; one instance per worker",
|
|
},
|
|
"results": {
|
|
"attempted_requests": attempted,
|
|
"successful_requests": successes,
|
|
"failed_requests": failures,
|
|
"error_rate_percent": round(
|
|
(failures / attempted * 100) if attempted else 0.0,
|
|
4,
|
|
),
|
|
"successful_rps": round(successes / args.duration_seconds, 3),
|
|
"latency_ms": {
|
|
"p50": percentile(latencies, 50),
|
|
"p95": percentile(latencies, 95),
|
|
"p99": percentile(latencies, 99),
|
|
},
|
|
"status_counts": status_counts,
|
|
"rss_before_bytes": metrics_before["rss_bytes"],
|
|
"rss_after_bytes": metrics_after["rss_bytes"],
|
|
"rss_after_mib": round(
|
|
metrics_after["rss_bytes"] / (1024 * 1024),
|
|
3,
|
|
),
|
|
"messages_after": metrics_after["messages"],
|
|
},
|
|
}
|
|
|
|
output = Path(args.output)
|
|
output.parent.mkdir(parents=True, exist_ok=True)
|
|
output.write_text(
|
|
json.dumps(result, ensure_ascii=False, indent=2),
|
|
encoding="utf-8",
|
|
)
|
|
|
|
print(json.dumps(result["results"], ensure_ascii=False, indent=2))
|
|
print(f"saved: {output}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |