askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
profile_requests.py · 72.3 KB · 1376 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """Where does the time actually go, per request type, in a realistic install? |
| 3 | |
| 4 | MEASUREMENT ONLY. Edits nothing in the server: everything is monkeypatched inside THIS process |
| 5 | (wrappers that count/time calls) and everything lives in a throwaway temp dir. |
| 6 | |
| 7 | What it does |
| 8 | * installs a realistic package set (default: every package under packages/, dependency order), |
| 9 | with permission enforcement ON, event handlers ON (DBBASIC_ENABLE_EVENT_HANDLERS) and the durable |
| 10 | event log ON (DBBASIC_ENABLE_RECORD_EVENTS, the default), realtime ON (default), site routes ON; |
| 11 | * seeds U users (3 sessions, 2 projects, 3 project grants, 10 notes, 2 orders x 3 lines, 1 invoice x 2 |
| 12 | lines, 3 contacts, 3 tasks each) straight into the TSVs (so seeding is not O(n^2)); |
| 13 | * drives the REAL ASGI app in-process (no HTTP server) as a signed-in NON-admin user; |
| 14 | * for each request type: wall time (best-of-N / median / p90, no profiler), a per-stage breakdown from |
| 15 | exclusive-time wrappers (perf_counter, own process), a call-count table (permission checks, |
| 16 | read_collection_records, file parses, opens, json, csv, object loads, identity...), and cProfile |
| 17 | top lists (cumulative and total). Every response is validated (status AND body shape), so a |
| 18 | request that falls onto an error path fails loudly instead of being profiled. |
| 19 | |
| 20 | usage (run with .venv-jit/bin/python) |
| 21 | profile_requests.py --users 10 one size, prints the report |
| 22 | profile_requests.py --compare 10,1000 spawns one subprocess per size, prints both + growth tables |
| 23 | (--out FILE keeps the text, --json FILE keeps the raw numbers) |
| 24 | profile_requests.py --from-json a.json[,b.json] re-print a saved report without measuring |
| 25 | profile_requests.py --whatif --users 1000 re-time hot requests with the cheapest candidate fixes monkeypatched in (own process) |
| 26 | profile_requests.py --micro isolate: rule-scan share of check_permission, load_policy, get_schema, event-log size |
| 27 | options: --only a,b --reps N --profile-reps N --budget SECONDS --packages full|core --no-cprofile |
| 28 | --changelog-prefill N (pre-existing change-log lines per written collection, to test O(log size)) |
| 29 | |
| 30 | Phases, in this order, so the instruments never contaminate the bare number: (1) bare wall, nothing patched; |
| 31 | (2) exclusive-time wrappers + audit hook (perf_counter, counts); (3) cProfile with the wrappers switched off. |
| 32 | |
| 33 | Numbers on a shared machine are indicative; prefer the counts and the percentages. |
| 34 | """ |
| 35 | from __future__ import annotations |
| 36 | |
| 37 | import argparse |
| 38 | import asyncio |
| 39 | import collections |
| 40 | import cProfile |
| 41 | import functools |
| 42 | import json |
| 43 | import os |
| 44 | import pstats |
| 45 | import re |
| 46 | import shutil |
| 47 | import statistics |
| 48 | import subprocess |
| 49 | import sys |
| 50 | import tempfile |
| 51 | import time |
| 52 | from datetime import datetime, timedelta, timezone |
| 53 | from pathlib import Path |
| 54 | |
| 55 | REPO = Path(__file__).resolve().parents[3] |
| 56 | sys.path.insert(0, str(REPO)) |
| 57 | PY = str(REPO / ".venv-jit/bin/python") |
| 58 | pc = time.perf_counter |
| 59 | |
| 60 | |
| 61 | # ===================================================================================================== |
| 62 | # environment + seeding |
| 63 | # ===================================================================================================== |
| 64 | def configure_env(tmp: Path) -> None: |
| 65 | os.environ.update( |
| 66 | DBBASIC_DATA_DIR=str(tmp / "data"), |
| 67 | DBBASIC_OBJECTS_DIR=str(tmp / "objects"), |
| 68 | DBBASIC_ADMIN_TOKEN="admin-t", |
| 69 | DBBASIC_ENABLE_PERMISSION_ENFORCEMENT="true", |
| 70 | DBBASIC_ALLOW_UNREADY_PERMISSION_ENFORCEMENT="true", |
| 71 | DBBASIC_MAX_CONCURRENT_REQUESTS="0", |
| 72 | DBBASIC_MAX_CONCURRENT_EXECUTIONS="0", |
| 73 | DBBASIC_ENABLE_SITE_ROUTES="true", |
| 74 | DBBASIC_ENABLE_EVENT_HANDLERS="true", # HANDLES objects (object_handlers.HANDLERS_ENABLED_ENV) |
| 75 | DBBASIC_ENABLE_RECORD_EVENTS="true", # durable event log (default on; set explicitly) |
| 76 | DBBASIC_ENABLE_REALTIME="true", # realtime publish overlay (default on) |
| 77 | DBBASIC_COOKIE_SECURE="false", |
| 78 | ) |
| 79 | os.environ.pop("DBBASIC_RATE_LIMIT_REQUESTS", None) |
| 80 | os.environ.pop("DBBASIC_OBJECT_TIMEOUT_SECONDS", None) |
| 81 | |
| 82 | |
| 83 | def package_order(root: Path, which: str) -> list[str]: |
| 84 | deps: dict[str, list[str]] = {} |
| 85 | for f in sorted(root.glob("*/dbbasic-package.json")): |
| 86 | j = json.loads(f.read_text()) |
| 87 | deps[j["id"]] = list(j.get("dependencies") or []) |
| 88 | if which == "core": |
| 89 | want = ["app-views", "app-projects", "app-notes", "app-orders", "app-invoices", "app-payments", |
| 90 | "app-contacts", "app-tasks", "app-timers", "app-catalog", "app-shipping"] |
| 91 | else: |
| 92 | want = [p for p in deps if p not in ("admin-write-probe", "hello-world")] |
| 93 | order: list[str] = [] |
| 94 | seen: set[str] = set() |
| 95 | |
| 96 | def visit(n: str) -> None: |
| 97 | if n in seen or n not in deps: |
| 98 | return |
| 99 | seen.add(n) |
| 100 | for d in deps[n]: |
| 101 | visit(d) |
| 102 | order.append(n) |
| 103 | |
| 104 | for n in want: |
| 105 | visit(n) |
| 106 | return order |
| 107 | |
| 108 | |
| 109 | def install_packages(tmp: Path, which: str) -> tuple[list[str], dict[str, str]]: |
| 110 | import object_packages |
| 111 | ok, failed = [], {} |
| 112 | for name in package_order(REPO / "packages", which): |
| 113 | try: |
| 114 | object_packages.install_package(name, root=REPO / "packages", base_dir=tmp / "data", object_roots=[tmp / "objects"]) |
| 115 | ok.append(name) |
| 116 | except Exception as exc: # noqa: BLE001 -- reported, not hidden |
| 117 | failed[name] = str(exc)[:200] |
| 118 | return ok, failed |
| 119 | |
| 120 | |
| 121 | def append_rows(tmp: Path, collection: str, rows: list[dict[str, str]]) -> None: |
| 122 | path = tmp / "data" / "collections" / collection / "records.tsv" |
| 123 | header = path.read_text().split("\n", 1)[0].split("\t") |
| 124 | with open(path, "a") as f: |
| 125 | for r in rows: |
| 126 | f.write("\t".join(str(r.get(h, "")) for h in header) + "\n") |
| 127 | |
| 128 | |
| 129 | def seed(tmp: Path, users: int, packages: str) -> dict: |
| 130 | """Install packages and seed `users` users. Returns {tokens, installed, failed}.""" |
| 131 | (tmp / "objects").mkdir(parents=True, exist_ok=True) |
| 132 | configure_env(tmp) |
| 133 | import object_identity as oi |
| 134 | installed, failed = install_packages(tmp, packages) |
| 135 | |
| 136 | now = datetime.now(timezone.utc).replace(microsecond=0) |
| 137 | stamp = oi._format_timestamp(now) |
| 138 | expires = oi._format_timestamp(now + timedelta(days=30)) |
| 139 | user_rows, sessions, tokens = [], [], [] |
| 140 | for i in range(users): |
| 141 | uid = f"u{i}" |
| 142 | user_rows.append(oi.IdentityUser(user_id=uid, account_id=None, email=f"{uid}@example.test", display_name=f"User {i}", |
| 143 | status="active", roles=(), subscriptions=(), created_at=stamp, updated_at=stamp)) |
| 144 | for d in range(3): |
| 145 | token = f"tok-{i}-{d}" |
| 146 | sessions.append(oi.IdentitySession(session_id=oi._new_session_id(), token_hash=oi.hash_token(token), user_id=uid, account_id=None, |
| 147 | roles=(), subscriptions=(), label="", created_at=stamp, expires_at=expires)) |
| 148 | if d == 0: |
| 149 | tokens.append(token) |
| 150 | oi._write_users(oi.users_path(tmp / "data"), user_rows) |
| 151 | oi._write_sessions(oi.sessions_path(tmp / "data"), sessions) |
| 152 | |
| 153 | A = lambda coll, rows: append_rows(tmp, coll, rows) # noqa: E731 |
| 154 | A("projects", [dict(id=f"p{i}_{p}", name=f"Project {i}.{p}", description="seed", status="active", owner_id=f"u{i}") |
| 155 | for i in range(users) for p in range(2)]) |
| 156 | A("project_access", [dict(id=f"a{i}_{g}", project_id=f"p{(i + 1 + g) % users}_0", user_id=f"u{i}", permission="read", |
| 157 | granted_by=f"u{(i + 1 + g) % users}") for i in range(users) for g in range(3)]) |
| 158 | A("notes", [dict(id=f"n{i}_{n}", content=f"note {n} of user {i}, some realistic length text", project_id=f"p{i}_0", |
| 159 | is_public="true" if (i == 0 and n < 3) else "false", owner_id=f"u{i}") |
| 160 | for i in range(users) for n in range(10)]) |
| 161 | if "app-orders" in installed: |
| 162 | A("orders", [dict(id=f"o{i}_{o}", doc_type="sale", number=f"SO-{i}-{o}", customer_name=f"Customer {i}", currency="USD", |
| 163 | status="draft", subtotal_cents="3000", tax_cents="0", total_cents="3000", fulfillment_source="stock", |
| 164 | fulfillment_method="shipping", owner_id=f"u{i}", created_at="2026-01-01T00:00:00") |
| 165 | for i in range(users) for o in range(2)]) |
| 166 | A("order_lines", [dict(id=f"ol{i}_{o}_{l}", order_id=f"o{i}_{o}", description=f"line {l}", quantity="1", unit_price_cents="1000", |
| 167 | line_total_cents="1000", line_tax_cents="0", owner_id=f"u{i}", created_at="2026-01-01T00:00:00") |
| 168 | for i in range(users) for o in range(2) for l in range(3)]) |
| 169 | if "app-invoices" in installed: |
| 170 | A("invoices", [dict(id=f"inv{i}", doc_type="invoice", number=f"INV-{i}", customer_name=f"Customer {i}", currency="USD", |
| 171 | status="draft", subtotal_cents="2000", tax_cents="0", total_cents="2000", owner_id=f"u{i}", |
| 172 | created_at="2026-01-01T00:00:00") for i in range(users)]) |
| 173 | A("invoice_lines", [dict(id=f"il{i}_{l}", invoice_id=f"inv{i}", description=f"iline {l}", quantity="1", unit_price_cents="1000", |
| 174 | line_total_cents="1000", line_tax_cents="0", owner_id=f"u{i}", created_at="2026-01-01T00:00:00") |
| 175 | for i in range(users) for l in range(2)]) |
| 176 | if "app-contacts" in installed: |
| 177 | A("contacts", [dict(id=f"c{i}_{c}", first_name=f"First{c}", last_name=f"Last{i}", full_name=f"First{c} Last{i}", |
| 178 | email=f"c{i}_{c}@example.test", project_id=f"p{i}_0", lead_status="warm", owner_id=f"u{i}", |
| 179 | created_at="2026-01-01T00:00:00") for i in range(users) for c in range(3)]) |
| 180 | if "app-tasks" in installed: |
| 181 | A("tasks", [dict(id=f"t{i}_{t}", title=f"Task {t} of user {i}", description="seed", task_type="STANDARD", project_id=f"p{i}_0", |
| 182 | status="open", urgency="normal", assigned_to=f"u{i}", owner_id=f"u{i}", created_at="2026-01-01T00:00:00") |
| 183 | for i in range(users) for t in range(3)]) |
| 184 | return {"tokens": tokens, "installed": installed, "failed": failed} |
| 185 | |
| 186 | |
| 187 | # ===================================================================================================== |
| 188 | # the in-process ASGI driver |
| 189 | # ===================================================================================================== |
| 190 | class Driver: |
| 191 | def __init__(self, tokens: list[str]): |
| 192 | import object_server |
| 193 | self.srv = object_server |
| 194 | self.tokens = tokens |
| 195 | self.loop = asyncio.new_event_loop() |
| 196 | asyncio.set_event_loop(self.loop) |
| 197 | |
| 198 | def call(self, method: str, path: str, *, query: str = "", body=None, user: int | None = 0, token: str | None = None, |
| 199 | accept: str = "application/json", extra_headers: list | None = None): |
| 200 | """-> (status, headers dict, body bytes). user=None means anonymous.""" |
| 201 | headers = [(b"accept", accept.encode()), (b"host", b"bench.test")] |
| 202 | if token is None and user is not None: |
| 203 | token = self.tokens[user % len(self.tokens)] |
| 204 | if token: |
| 205 | headers.append((b"authorization", f"Bearer {token}".encode())) |
| 206 | raw = b"" |
| 207 | if body is not None: |
| 208 | raw = body if isinstance(body, bytes) else json.dumps(body).encode() |
| 209 | headers.append((b"content-type", b"application/json")) |
| 210 | headers += extra_headers or [] |
| 211 | scope = {"type": "http", "method": method, "path": path, "query_string": query.encode(), "headers": headers, |
| 212 | "client": ("127.0.0.1", 1), "scheme": "http", "http_version": "1.1"} |
| 213 | sent: list[dict] = [] |
| 214 | done = False |
| 215 | |
| 216 | async def receive(): |
| 217 | nonlocal done |
| 218 | if done: |
| 219 | return {"type": "http.disconnect"} |
| 220 | done = True |
| 221 | return {"type": "http.request", "body": raw, "more_body": False} |
| 222 | |
| 223 | async def send(m): |
| 224 | sent.append(m) |
| 225 | |
| 226 | self.loop.run_until_complete(self.srv.app(scope, receive, send)) |
| 227 | status = sent[0]["status"] |
| 228 | hdrs = {k.decode().lower(): v.decode("latin-1") for k, v in sent[0].get("headers", [])} |
| 229 | data = b"".join(m.get("body", b"") for m in sent[1:]) |
| 230 | return status, hdrs, data |
| 231 | |
| 232 | |
| 233 | def jbody(data: bytes): |
| 234 | return json.loads(data.decode()) |
| 235 | |
| 236 | |
| 237 | # ===================================================================================================== |
| 238 | # instrumentation: exclusive-time stage wrappers + leaf counters + file-open audit hook |
| 239 | # ===================================================================================================== |
| 240 | class Meter: |
| 241 | def __init__(self): |
| 242 | self.enabled = False |
| 243 | self.calls: collections.Counter = collections.Counter() |
| 244 | self.incl: dict[str, float] = collections.defaultdict(float) |
| 245 | self.excl: dict[str, float] = collections.defaultdict(float) |
| 246 | self.depth: collections.Counter = collections.Counter() |
| 247 | self.stack: list[list[float]] = [] |
| 248 | self.opens_r = 0 |
| 249 | self.opens_w = 0 |
| 250 | self.open_paths: collections.Counter = collections.Counter() |
| 251 | self.fsyncs = 0 |
| 252 | self.renames = 0 |
| 253 | self.skipped: list[str] = [] |
| 254 | |
| 255 | def reset(self): |
| 256 | self.calls.clear(); self.incl.clear(); self.excl.clear(); self.depth.clear(); self.stack.clear() |
| 257 | self.opens_r = self.opens_w = self.fsyncs = self.renames = 0 |
| 258 | self.open_paths.clear() |
| 259 | |
| 260 | def stage(self, fn, label): |
| 261 | m = self |
| 262 | |
| 263 | @functools.wraps(fn) |
| 264 | def w(*a, **k): |
| 265 | if not m.enabled: |
| 266 | return fn(*a, **k) |
| 267 | st = m.stack |
| 268 | frame = [0.0] |
| 269 | st.append(frame) |
| 270 | m.depth[label] += 1 |
| 271 | t0 = pc() |
| 272 | try: |
| 273 | return fn(*a, **k) |
| 274 | finally: |
| 275 | dt = pc() - t0 |
| 276 | st.pop() |
| 277 | m.depth[label] -= 1 |
| 278 | m.calls[label] += 1 |
| 279 | m.excl[label] += dt - frame[0] |
| 280 | if m.depth[label] == 0: |
| 281 | m.incl[label] += dt |
| 282 | if st: |
| 283 | st[-1][0] += dt |
| 284 | return w |
| 285 | |
| 286 | def leaf(self, fn, label): |
| 287 | """Counted and inclusive-timed, but does NOT take part in the exclusive accounting.""" |
| 288 | m = self |
| 289 | |
| 290 | @functools.wraps(fn) |
| 291 | def w(*a, **k): |
| 292 | if not m.enabled: |
| 293 | return fn(*a, **k) |
| 294 | t0 = pc() |
| 295 | try: |
| 296 | return fn(*a, **k) |
| 297 | finally: |
| 298 | m.calls[label] += 1 |
| 299 | m.incl[label] += pc() - t0 |
| 300 | return w |
| 301 | |
| 302 | def count_only(self, fn, label): |
| 303 | m = self |
| 304 | |
| 305 | @functools.wraps(fn) |
| 306 | def w(*a, **k): |
| 307 | if m.enabled: |
| 308 | m.calls[label] += 1 |
| 309 | return fn(*a, **k) |
| 310 | return w |
| 311 | |
| 312 | |
| 313 | METER = Meter() |
| 314 | SKIP_SET: set[str] = set() |
| 315 | |
| 316 | |
| 317 | def install_audit_hook(): |
| 318 | def hook(event, args): |
| 319 | if not METER.enabled: |
| 320 | return |
| 321 | if event == "open": |
| 322 | path, mode, flags = args |
| 323 | p = str(path) |
| 324 | if "/data/" not in p and "/objects/" not in p: |
| 325 | return # interpreter/imports/bytecode |
| 326 | writing = (isinstance(mode, str) and any(c in mode for c in "wa+x")) or (isinstance(flags, int) and flags & (os.O_WRONLY | os.O_RDWR | os.O_APPEND | os.O_CREAT)) |
| 327 | if writing: |
| 328 | METER.opens_w += 1 |
| 329 | else: |
| 330 | METER.opens_r += 1 |
| 331 | rel = p.split("/data/", 1)[-1] if "/data/" in p else p.split("/objects/", 1)[-1] |
| 332 | rel = re.sub(r"\bu\d+\b|\b[0-9a-f]{8}-[0-9a-f-]{27,}\b", "*", rel) |
| 333 | METER.open_paths[("W " if writing else "R ") + rel] += 1 |
| 334 | sys.addaudithook(hook) |
| 335 | |
| 336 | |
| 337 | def patch_everywhere(orig, new, skip_modules=()): |
| 338 | """Replace every reference to `orig` (module-level names) with `new` in all loaded repo modules.""" |
| 339 | for mod in list(sys.modules.values()): |
| 340 | f = getattr(mod, "__file__", None) |
| 341 | if not f or not str(f).startswith(str(REPO)) or mod is sys.modules[__name__]: |
| 342 | continue |
| 343 | for k, v in list(vars(mod).items()): |
| 344 | if v is orig: |
| 345 | setattr(mod, k, new) |
| 346 | |
| 347 | |
| 348 | STAGES = [ |
| 349 | # identity / permission engine |
| 350 | ("object_server", "_permission_identity", "identity.total"), |
| 351 | ("object_server", "_with_accessible_projects", "identity.project_access+projects scan"), |
| 352 | ("object_server", "_with_shared_records", "identity.record_shares scan"), |
| 353 | ("object_identity", "resolve_session_token", "identity.session lookup"), |
| 354 | ("object_permission_store", "load_policy", "policy.load_policy"), |
| 355 | ("object_permissions", "check_permission", "perm.check_permission"), |
| 356 | ("object_server", "_filter_records_for_permission", "list.row filter (check_permission/row)"), |
| 357 | ("object_server", "_redact_records_for_permission", "list.redact (check_permission+field policy/row)"), |
| 358 | ("object_server", "_apply_record_field_policy", "perm.field policy"), |
| 359 | ("object_field_permissions", "redact_record", "perm.field redact_record"), |
| 360 | ("object_field_permissions", "denied_write_fields", "perm.denied_write_fields"), |
| 361 | # storage |
| 362 | ("object_records", "read_collection_records", "storage.read_collection_records"), |
| 363 | ("object_records", "_parse_records_file", "storage.parse_records_file (cache MISS)"), |
| 364 | ("object_records", "get_collection_record", "storage.get_collection_record"), |
| 365 | ("object_records", "create_collection_record", "storage.create_collection_record"), |
| 366 | ("object_records", "update_collection_record", "storage.update_collection_record"), |
| 367 | ("object_records", "delete_collection_record", "storage.delete_collection_record"), |
| 368 | ("object_records", "_persist_write", "storage.persist_write(lock+file)"), |
| 369 | ("object_records", "_apply_computed_fields", "write.computed fields"), |
| 370 | ("object_records", "_recompute_rollups_for_source", "write.rollup re-trigger"), |
| 371 | ("object_records", "_validate_record_against_schema", "write.schema validation"), |
| 372 | ("object_records", "_validate_field_transitions", "write.transition check"), |
| 373 | ("object_records", "_apply_schema_defaults", "write.schema defaults"), |
| 374 | ("object_record_changes", "append_record_change", "write.change-log append"), |
| 375 | ("object_record_changes", "latest_record_change", "write.change-log latest lookup"), |
| 376 | ("object_schemas", "get_schema", "schema.get_schema"), |
| 377 | ("object_collections", "get_collection", "schema.get_collection"), |
| 378 | # fan-out |
| 379 | ("object_server", "_publish_record_change_event", "fanout.publish_record_change_event"), |
| 380 | ("object_server", "_realtime_publish", "fanout.realtime"), |
| 381 | ("object_server", "_dispatch_event_handlers", "fanout.event handlers dispatch"), |
| 382 | ("object_server", "_record_change_for_publish", "fanout.change lookup"), |
| 383 | ("object_events", "publish_event", "fanout.durable event log"), |
| 384 | ("object_handlers", "get_handlers", "fanout.handler index lookup"), |
| 385 | ("object_handlers", "build_index", "fanout.handler index BUILD"), |
| 386 | # object execution |
| 387 | ("object_execution", "execute_object", "exec.execute_object"), |
| 388 | ("python_object_runtime", "_load_module", "exec.load_module (object import)"), |
| 389 | ("object_state", "get_object_state", "state.get_object_state"), |
| 390 | ("object_state", "_write_object_state", "state.write_object_state"), |
| 391 | # search / site |
| 392 | ("object_search", "search_records", "search.search_records"), |
| 393 | ("object_site_routes", "match_records", "site.match_records"), |
| 394 | ("object_site_routes", "resolve_host", "site.resolve_host"), |
| 395 | ("object_namespace", "iter_object_sources", "ns.iter_object_sources (dir scan)"), |
| 396 | ("object_namespace", "resolve_object_id", "ns.resolve_object_id"), |
| 397 | ("object_records", "compute_record_rev", "list.compute_record_rev"), |
| 398 | ("object_records", "collection_records_payload", "list.payload build"), |
| 399 | ("object_records", "filter_records", "list.field filter"), |
| 400 | ] |
| 401 | LEAVES = [ |
| 402 | ("json", "loads", "json.loads"), |
| 403 | ("json", "dumps", "json.dumps"), |
| 404 | ("json", "load", "json.load"), |
| 405 | ("json", "dump", "json.dump"), |
| 406 | ("csv", "reader", "csv.reader"), |
| 407 | ("csv", "writer", "csv.writer"), |
| 408 | ("os", "fsync", "os.fsync"), |
| 409 | ("os", "replace", "os.replace"), |
| 410 | ("os", "stat", "os.stat"), |
| 411 | ("os", "scandir", "os.scandir"), |
| 412 | ("os", "listdir", "os.listdir"), |
| 413 | ("hashlib", "sha256", "hashlib.sha256"), |
| 414 | ("importlib.util", "spec_from_file_location", "importlib.spec_from_file_location"), |
| 415 | ] |
| 416 | |
| 417 | |
| 418 | # ---- instrument control: wrappers can be switched off so the wall / cProfile phases run bare code -------- |
| 419 | REGISTRY: list[tuple] = [] # (orig, new) |
| 420 | DYN = collections.Counter() # dynamic-label counts, e.g. ("exec", object_id), ("parse", collection) |
| 421 | |
| 422 | |
| 423 | def _dyn(fn, kind, labelfn): |
| 424 | @functools.wraps(fn) |
| 425 | def w(*a, **k): |
| 426 | if METER.enabled: |
| 427 | try: |
| 428 | DYN[(kind, labelfn(*a, **k))] += 1 |
| 429 | except Exception: # noqa: BLE001 |
| 430 | pass |
| 431 | return fn(*a, **k) |
| 432 | return w |
| 433 | |
| 434 | |
| 435 | def wrap(modname: str, attr: str, label: str, kind: str = "stage", dyn=None): |
| 436 | mod = sys.modules.get(modname) or __import__(modname) |
| 437 | name = attr |
| 438 | orig = getattr(mod, name, None) |
| 439 | if orig is None or not callable(orig): |
| 440 | METER.skipped.append(f"{modname}.{attr}") |
| 441 | return |
| 442 | new = getattr(METER, kind)(orig, label) if kind != "dyn" else _dyn(orig, *dyn) |
| 443 | setattr(mod, name, new) |
| 444 | patch_everywhere(orig, new) |
| 445 | REGISTRY.append((orig, new)) |
| 446 | |
| 447 | |
| 448 | def set_instruments(active: bool) -> None: |
| 449 | for orig, new in (REGISTRY if active else list(reversed(REGISTRY))): # unwind in reverse: wrappers are stacked |
| 450 | a, b = (orig, new) if active else (new, orig) |
| 451 | patch_everywhere(a, b) |
| 452 | for mod in list(sys.modules.values()): # stdlib leaf wrappers |
| 453 | if mod is None or getattr(mod, "__name__", "") in ("json", "csv", "os", "hashlib", "importlib.util"): |
| 454 | for k, v in list(vars(mod).items()): |
| 455 | if v is a: |
| 456 | setattr(mod, k, b) |
| 457 | |
| 458 | |
| 459 | def install_instruments(): |
| 460 | install_audit_hook() |
| 461 | for m, a, l in STAGES: |
| 462 | try: |
| 463 | wrap(m, a, l, "stage") |
| 464 | except Exception as exc: # noqa: BLE001 |
| 465 | METER.skipped.append(f"{m}.{a}: {exc}") |
| 466 | for m, a, l in LEAVES: |
| 467 | try: |
| 468 | wrap(m, a, l, "leaf") |
| 469 | except Exception as exc: # noqa: BLE001 |
| 470 | METER.skipped.append(f"{m}.{a}: {exc}") |
| 471 | # dynamic per-object / per-collection counters (counted, not timed) |
| 472 | wrap("object_execution", "execute_object", "", "dyn", ("exec", lambda rt, req, *a, **k: req.object_id)) |
| 473 | wrap("python_object_runtime", "_load_module", "", "dyn", ("load_module", lambda path, oid, *a, **k: oid)) |
| 474 | wrap("object_records", "_parse_records_file", "", "dyn", ("parse_file", lambda coll, path, *a, **k: coll)) |
| 475 | wrap("object_records", "read_collection_records", "", "dyn", ("read_collection", lambda coll, *a, **k: coll)) |
| 476 | wrap("object_schemas", "get_schema", "", "dyn", ("get_schema", lambda schema, *a, **k: schema)) |
| 477 | wrap("object_state", "get_object_state", "", "dyn", ("get_object_state", lambda oid, *a, **k: oid)) |
| 478 | wrap("object_permissions", "check_permission", "", "dyn", ("check_permission", lambda subj, action, *a, collection=None, object_id=None, **k: f"{action}:{collection or object_id}")) |
| 479 | |
| 480 | |
| 481 | # ===================================================================================================== |
| 482 | # cases |
| 483 | # ===================================================================================================== |
| 484 | class Fail(AssertionError): |
| 485 | pass |
| 486 | |
| 487 | |
| 488 | def expect(cond, msg): |
| 489 | if not cond: |
| 490 | raise Fail(msg) |
| 491 | |
| 492 | |
| 493 | def ok_json(resp, status=200, keys=()): |
| 494 | st, hdrs, data = resp |
| 495 | expect(st == status, f"status {st} != {status}: {data[:200]!r}") |
| 496 | body = jbody(data) |
| 497 | expect(isinstance(body, dict), "body not an object") |
| 498 | for k in keys: |
| 499 | expect(k in body, f"missing key {k!r} in {list(body)[:8]}") |
| 500 | return body |
| 501 | |
| 502 | |
| 503 | class Ctx: |
| 504 | def __init__(self, drv: Driver, users: int): |
| 505 | self.d = drv |
| 506 | self.U = users |
| 507 | self.ids: dict[str, list] = collections.defaultdict(list) |
| 508 | self.stats: dict = {} |
| 509 | |
| 510 | def user(self, j: int) -> int: |
| 511 | return (j * 37 + 11) % self.U |
| 512 | |
| 513 | |
| 514 | class Case: |
| 515 | def __init__(self, name, title, run, check, group=None, kind="read"): |
| 516 | self.name, self.title, self.run, self.check, self.group, self.kind = name, title, run, check, group, kind |
| 517 | |
| 518 | |
| 519 | def build_cases(ctx: Ctx, installed: list[str]) -> list[Case]: |
| 520 | d, U = ctx.d, ctx.U |
| 521 | cases: list[Case] = [] |
| 522 | add = cases.append |
| 523 | H = lambda j: "tok" # noqa: E731 |
| 524 | |
| 525 | # ---- floor -------------------------------------------------------------------------------------- |
| 526 | add(Case("floor_health", "GET /health (no identity: the in-process driver + ASGI floor)", |
| 527 | lambda j: d.call("GET", "/health", user=None), |
| 528 | lambda j, r: ok_json(r, 200))) |
| 529 | |
| 530 | # ---- 1. list -------------------------------------------------------------------------------------- |
| 531 | def list_run(j): return d.call("GET", "/collections/notes/records", query="limit=20", user=ctx.user(j)) |
| 532 | |
| 533 | def list_check(j, r): |
| 534 | b = ok_json(r, 200, ("records", "total")) |
| 535 | expect(len(b["records"]) == 20, f"expected 20 rows, got {len(b['records'])}") |
| 536 | u = f"u{ctx.user(j)}" |
| 537 | expect(all(x.get("owner_id") == u or x.get("project_id") or x.get("is_public") == "true" for x in b["records"]), "foreign rows leaked") |
| 538 | expect(b["total"] >= 20, "total") |
| 539 | ctx.stats["list_total"] = b["total"] |
| 540 | add(Case("list_notes", "1. GET /collections/notes/records?limit=20 (owner-scoped list, signed-in)", list_run, list_check)) |
| 541 | |
| 542 | # ---- 2. one record ------------------------------------------------------------------------------ |
| 543 | def get_run(j): u = ctx.user(j); return d.call("GET", f"/collections/notes/records/n{u}_{j % 10}", user=u) |
| 544 | |
| 545 | def get_check(j, r): |
| 546 | b = ok_json(r, 200, ("record",)) |
| 547 | expect(b["record"]["id"] == f"n{ctx.user(j)}_{j % 10}", "wrong record") |
| 548 | add(Case("get_note", "2. GET /collections/notes/records/{id}", get_run, get_check)) |
| 549 | |
| 550 | # ---- 3/4. generic lifecycle builder ---------------------------------------------------------------- |
| 551 | def lifecycle(group, coll, make_body, upd_body, title, extra_check=None): |
| 552 | def c_run(j): u = ctx.user(j); return d.call("POST", f"/collections/{coll}/records", body=make_body(u, j), user=u) |
| 553 | |
| 554 | def c_check(j, r): |
| 555 | b = ok_json(r, 201, ("record",)) |
| 556 | ctx.ids[group].append((b["record"]["id"], ctx.user(j))) |
| 557 | if extra_check: extra_check("create", j, b) |
| 558 | |
| 559 | def u_run(j): rid, u = ctx.ids[group][j]; return d.call("PUT", f"/collections/{coll}/records/{rid}", body=upd_body(u, j), user=u) |
| 560 | |
| 561 | def u_check(j, r): |
| 562 | b = ok_json(r, 200, ("record",)) |
| 563 | expect(b["record"]["id"] == ctx.ids[group][j][0], "wrong record") |
| 564 | if extra_check: extra_check("update", j, b) |
| 565 | |
| 566 | def d_run(j): rid, u = ctx.ids[group][j]; return d.call("DELETE", f"/collections/{coll}/records/{rid}", user=u) |
| 567 | |
| 568 | def d_check(j, r): |
| 569 | b = ok_json(r, 200) |
| 570 | expect(b.get("deleted") is True, "not deleted") |
| 571 | return [Case(f"{group}_create", f"POST /collections/{coll}/records [{title}]", c_run, c_check, group, "create"), |
| 572 | Case(f"{group}_update", f"PUT /collections/{coll}/records/{{id}} [{title}]", u_run, u_check, group, "update"), |
| 573 | Case(f"{group}_delete", f"DELETE /collections/{coll}/records/{{id}} [{title}]", d_run, d_check, group, "delete")] |
| 574 | |
| 575 | cases += lifecycle("note", "notes", |
| 576 | lambda u, j: {"content": f"bench note {j}", "project_id": f"p{u}_0", "owner_id": f"u{u}"}, |
| 577 | lambda u, j: {"content": f"bench note {j} edited"}, |
| 578 | "3/4. plain collection, owner_id sent as the form does") |
| 579 | |
| 580 | # ---- 5. order lines: HANDLES order_totals + (order_portal_link/order_email/.. handlers) --------------- |
| 581 | if "app-orders" in installed: |
| 582 | cases += lifecycle("orderline", "order_lines", |
| 583 | lambda u, j: {"order_id": f"o{u}_{j % 2}", "owner_id": f"u{u}", "description": f"bench {j}", "quantity": 2, "unit_price_cents": 500}, |
| 584 | lambda u, j: {"quantity": 3}, |
| 585 | "5. order line: HANDLES order_totals re-stamps the order") |
| 586 | if "app-payments" in installed: |
| 587 | cases += lifecycle("payment", "payments", |
| 588 | lambda u, j: {"invoice_id": f"inv{u}", "owner_id": f"u{u}", "amount_cents": 1, "received_on": "2026-01-02", "method": "cash"}, |
| 589 | lambda u, j: {"amount_cents": 2}, |
| 590 | "5b. payment: before_write hook + invoice rollup re-trigger + HANDLES (books/invoice_status)") |
| 591 | if "app-contacts" in installed: |
| 592 | cases += lifecycle("contact", "contacts", |
| 593 | lambda u, j: {"first_name": "Ann", "last_name": f"Bench{j}", "owner_id": f"u{u}"}, |
| 594 | lambda u, j: {"last_name": f"Edited{j}"}, |
| 595 | "5c. contact: computed formula field (full_name)", |
| 596 | extra_check=lambda ph, j, b: expect(b["record"].get("full_name", "").startswith("Ann "), "computed full_name missing")) |
| 597 | |
| 598 | # ---- 6. the page ------------------------------------------------------------------------------- |
| 599 | def page_run(j): return d.call("GET", "/notes", user=ctx.user(j), accept="text/html") |
| 600 | |
| 601 | def page_check(j, r): |
| 602 | st, h, data = r |
| 603 | expect(st == 200 and h.get("content-type", "").startswith("text/html"), f"page {st} {h.get('content-type')}") |
| 604 | t = data.decode() |
| 605 | expect("VIEW_ID = 'view_notes'" in t and f"VIEWER_ID = 'u{ctx.user(j)}'" in t, "page does not carry this viewer / view") |
| 606 | add(Case("page_notes", "6. GET /notes (site_view_render, signed-in HTML)", page_run, page_check)) |
| 607 | |
| 608 | # ---- 7. search ---------------------------------------------------------------------------------- |
| 609 | def search_run(j): return d.call("GET", "/api/search", query="q=note", user=ctx.user(j)) |
| 610 | |
| 611 | def search_check(j, r): |
| 612 | b = ok_json(r, 200, ("results",)) |
| 613 | n = b["results"].get("notes") |
| 614 | expect(isinstance(n, list) and len(n) > 0, f"no notes hits: {str(b)[:200]}") |
| 615 | ctx.stats["search_collections"] = len(b["results"]) |
| 616 | add(Case("search_note", "7. GET /api/search?q=note (all searchable collections)", search_run, search_check)) |
| 617 | |
| 618 | # ---- 8. what the /notes page asks of the server on load (read from the HTML/JS it serves) ------------ |
| 619 | def get_json(name, title, path, query, keys, shape=None): |
| 620 | def run(j): return d.call("GET", path, query=query, user=ctx.user(j)) |
| 621 | |
| 622 | def check(j, r): |
| 623 | b = ok_json(r, 200, keys) |
| 624 | if shape: shape(j, b) |
| 625 | add(Case(name, title, run, check)) |
| 626 | |
| 627 | get_json("load_schema_notes", "8. GET /api/schema/notes", "/api/schema/notes", "", ("schema",), |
| 628 | lambda j, b: expect(b["schema"]["name"] == "notes" and b["schema"]["fields"], "schema shape")) |
| 629 | get_json("load_view_record", "8. GET /collections/views/records/view_notes", "/collections/views/records/view_notes", "", ("record",), |
| 630 | lambda j, b: expect(b["record"]["id"] == "view_notes", "view")) |
| 631 | get_json("load_notes_500", "8. GET /collections/notes/records?limit=500 (what the list block fetches)", "/collections/notes/records", "limit=500", |
| 632 | ("records",), lambda j, b: expect(len(b["records"]) >= 10, "rows")) |
| 633 | get_json("load_projects_labels", "8. GET /collections/projects/records?limit=500 (relation labels)", "/collections/projects/records", "limit=500", |
| 634 | ("records",), lambda j, b: expect(len(b["records"]) >= 2, "rows")) |
| 635 | get_json("load_nav_entries", "8. GET /objects/action_nav_entries (nav bar)", "/objects/action_nav_entries", "", ("groups",)) |
| 636 | get_json("load_views_200", "8. GET /collections/views/records?limit=200 (nav)", "/collections/views/records", "limit=200", ("records",), |
| 637 | lambda j, b: expect(len(b["records"]) > 5, "views")) |
| 638 | get_json("load_entities_200", "8. GET /collections/entities/records?limit=200 (nav)", "/collections/entities/records", "limit=200", ("records",)) |
| 639 | get_json("load_notifications_50", "8. GET /collections/notifications/records?limit=50 (nav bell)", "/collections/notifications/records", "limit=50", ("records",)) |
| 640 | get_json("load_prefs", "8. GET /prefs (nav)", "/prefs", "", ("prefs",)) |
| 641 | for asset in ("style", "markdown", "list", "form", "detail", "thread", "attachments", "share", "nav"): |
| 642 | def mk(asset): |
| 643 | def run(j): return d.call("GET", f"/{asset}", user=ctx.user(j), accept="*/*") |
| 644 | |
| 645 | def check(j, r): |
| 646 | st, h, data = r |
| 647 | expect(st == 200 and len(data) > 1000, f"/{asset}: {st} {len(data)}B") |
| 648 | expect(h.get("content-type", "").startswith(("application/javascript", "text/css")), f"/{asset} ctype {h.get('content-type')}") |
| 649 | return Case(f"asset_{asset}", f"8. GET /{asset} (page asset served by a site object)", run, check) |
| 650 | add(mk(asset)) |
| 651 | |
| 652 | # ---- 9. anonymous ------------------------------------------------------------------------------ |
| 653 | def anon_rows_run(j): return d.call("GET", "/collections/notes/records", query="limit=20", user=None) |
| 654 | |
| 655 | def anon_rows_check(j, r): |
| 656 | b = ok_json(r, 200, ("records",)) |
| 657 | expect(len(b["records"]) == 3 and all(x["is_public"] == "true" for x in b["records"]), f"anon rows: {len(b['records'])}") |
| 658 | add(Case("anon_public_rows", "9. anonymous GET /collections/notes/records?limit=20 (public rows)", anon_rows_run, anon_rows_check)) |
| 659 | |
| 660 | def anon_page_run(j): return d.call("GET", "/notes", user=None, accept="text/html") |
| 661 | |
| 662 | def anon_page_check(j, r): |
| 663 | st, h, data = r |
| 664 | expect(st == 200 and h.get("content-type", "").startswith("text/html"), f"anon page {st}") |
| 665 | expect("VIEW_ID = 'view_notes'" in data.decode(), "anon page") |
| 666 | add(Case("anon_page_notes", "9. anonymous GET /notes (public page)", anon_page_run, anon_page_check)) |
| 667 | return cases |
| 668 | |
| 669 | |
| 670 | def case_groups(cases: list[Case]) -> list[list[Case]]: |
| 671 | out, cur = [], None |
| 672 | for c in cases: |
| 673 | if c.group is None: |
| 674 | out.append([c]); cur = None |
| 675 | elif cur is not None and cur[0].group == c.group: |
| 676 | cur.append(c) |
| 677 | else: |
| 678 | cur = [c]; out.append(cur) |
| 679 | return out |
| 680 | |
| 681 | |
| 682 | # ===================================================================================================== |
| 683 | # prefill + fan-out verification |
| 684 | # ===================================================================================================== |
| 685 | def prefill_event_log(tmp: Path, target: int = 1000) -> int: |
| 686 | """Put the durable event log at its retention cap (steady state) so a publish pays the real cost.""" |
| 687 | import object_events |
| 688 | for _ in range(target + 10): |
| 689 | object_events.publish_event("bench.prefill", payload={"collection": "notes", "record_id": "x", "action": "create"}, |
| 690 | source="record_changes", actor="bench", base_dir=tmp / "data", |
| 691 | keep_count=object_events.DEFAULT_EVENT_KEEP_COUNT, keep_seconds=object_events.DEFAULT_EVENT_KEEP_SECONDS) |
| 692 | f = tmp / "data" / "state" / "events" / "state.tsv" |
| 693 | return sum(1 for _ in open(f)) if f.exists() else -1 |
| 694 | |
| 695 | |
| 696 | def prefill_changelog(tmp: Path, n: int, collections_: list[str]) -> None: |
| 697 | import object_record_changes as orc |
| 698 | if n <= 0: |
| 699 | return |
| 700 | for coll in collections_: |
| 701 | path = orc.record_changes_file(coll, base_dir=tmp / "data") |
| 702 | path.parent.mkdir(parents=True, exist_ok=True) |
| 703 | with open(path, "a") as f: |
| 704 | for i in range(n): |
| 705 | e = {"action": "update", "actor": "u1", "after": {"id": f"old{i}", "content": "x" * 60, "owner_id": "u1"}, |
| 706 | "before": {"id": f"old{i}", "content": "y" * 60, "owner_id": "u1"}, "change_id": f"2025-01-01T00:00:00.{i:06d}Z-{coll}-old{i}-update", |
| 707 | "changed_fields": ["content"], "collection": coll, "correlation_id": None, "message": "Record updated", |
| 708 | "record_id": f"old{i}", "timestamp": "2025-01-01T00:00:00Z"} |
| 709 | f.write(json.dumps(e, sort_keys=True, separators=(",", ":")) + "\n") |
| 710 | |
| 711 | |
| 712 | def events_count(tmp: Path) -> int: |
| 713 | """Rows in the durable event log, plus a fingerprint of the newest row (the log is capped, so the count alone stays flat).""" |
| 714 | f = tmp / "data" / "state" / "events" / "state.tsv" |
| 715 | return (sum(1 for _ in open(f)), hash(open(f).read()[-400:])) if f.exists() else (0, 0) |
| 716 | |
| 717 | |
| 718 | def verify_fanout(ctx: Ctx, tmp: Path, installed: list[str]) -> dict: |
| 719 | """Prove the write fan-out actually runs (handlers, rollups, hook, event log), not just that writes return 201.""" |
| 720 | d, out = ctx.d, {} |
| 721 | ev0 = events_count(tmp) |
| 722 | r = d.call("POST", "/collections/notes/records", body={"content": "v", "owner_id": "u1"}, user=1) |
| 723 | rid = ok_json(r, 201)["record"]["id"] |
| 724 | out["event_log_published_on_note_create"] = events_count(tmp) != ev0 |
| 725 | d.call("DELETE", f"/collections/notes/records/{rid}", user=1) |
| 726 | if "app-orders" in installed: |
| 727 | before = ok_json(d.call("GET", "/collections/orders/records/o1_0", user=1))["record"] |
| 728 | r = d.call("POST", "/collections/order_lines/records", body={"order_id": "o1_0", "owner_id": "u1", "description": "v", "quantity": 2, "unit_price_cents": 500}, user=1) |
| 729 | lid = ok_json(r, 201)["record"]["id"] |
| 730 | after = ok_json(d.call("GET", "/collections/orders/records/o1_0", user=1))["record"] |
| 731 | out["order_totals_handler_fired"] = int(after["total_cents"]) - int(before["total_cents"]) == 1000 |
| 732 | out["order_total_before_after"] = [before["total_cents"], after["total_cents"]] |
| 733 | d.call("DELETE", f"/collections/order_lines/records/{lid}", user=1) |
| 734 | if "app-payments" in installed: |
| 735 | r = d.call("POST", "/collections/payments/records", body={"invoice_id": "inv1", "owner_id": "u1", "amount_cents": -5, "received_on": "2026-01-02"}, user=1) |
| 736 | out["payments_before_write_hook_rejects_negative"] = (r[0] == 400 and b"positive" in r[2]) |
| 737 | r = d.call("POST", "/collections/payments/records", body={"invoice_id": "inv1", "owner_id": "u1", "amount_cents": 1, "received_on": "2026-01-02"}, user=1) |
| 738 | pid = ok_json(r, 201)["record"]["id"] |
| 739 | inv = ok_json(d.call("GET", "/collections/invoices/records/inv1", user=1))["record"] |
| 740 | out["invoice_rollup_retriggered"] = inv.get("payments_received_cents") == "1" |
| 741 | d.call("DELETE", f"/collections/payments/records/{pid}", user=1) |
| 742 | import object_handlers |
| 743 | out["handler_index"] = {k: v for k, v in object_handlers.build_index().items() if k.startswith(("order_lines.", "payments.", "notes.", "contacts."))} |
| 744 | out["handlers_enabled"] = object_handlers.handlers_enabled() |
| 745 | return out |
| 746 | |
| 747 | |
| 748 | # ===================================================================================================== |
| 749 | # the measurement phases |
| 750 | # ===================================================================================================== |
| 751 | def pct(xs, q): |
| 752 | xs = sorted(xs) |
| 753 | return xs[min(len(xs) - 1, int(round(q * (len(xs) - 1))))] |
| 754 | |
| 755 | |
| 756 | def clamp(v, lo, hi): |
| 757 | return max(lo, min(hi, v)) |
| 758 | |
| 759 | |
| 760 | class GroupRun: |
| 761 | """Runs one group of cases (a lone read, or create/update/delete of one collection) in one mode.""" |
| 762 | |
| 763 | def __init__(self, ctx: Ctx, group: list[Case], mode: str, args): |
| 764 | self.ctx, self.group, self.mode, self.args = ctx, group, mode, args |
| 765 | self.results: dict[str, dict] = {} |
| 766 | |
| 767 | def run(self) -> dict: |
| 768 | ctx, args = self.ctx, self.args |
| 769 | gname = self.group[0].group |
| 770 | if gname: |
| 771 | ctx.ids[gname].clear() |
| 772 | n = None |
| 773 | budget = {"wall": args.budget, "meter": args.budget, "cprof": args.budget}[self.mode] |
| 774 | nmax = {"wall": args.reps, "meter": args.reps, "cprof": args.profile_reps}[self.mode] |
| 775 | nmin = 3 if self.mode == "cprof" else 5 |
| 776 | for case in self.group: |
| 777 | res = {"title": case.title} |
| 778 | self.results[case.name] = res |
| 779 | try: |
| 780 | warm = 2 |
| 781 | t_warm = [] |
| 782 | for j in range(warm): |
| 783 | t = pc(); r = case.run(j); t_warm.append(pc() - t); case.check(j, r) |
| 784 | if n is None: |
| 785 | # cost model: cProfile and wrappers add ~2-3x; budget is seconds of measured work per phase |
| 786 | n = clamp(int(budget / max(statistics.mean(t_warm) * (2.5 if self.mode != "wall" else 1.0), 1e-6)), nmin, nmax) |
| 787 | if self.mode == "wall": |
| 788 | ts = [] |
| 789 | for j in range(warm, warm + n): |
| 790 | t = pc(); r = case.run(j); ts.append(pc() - t); case.check(j, r) |
| 791 | res.update(n=n, wall_ms=sorted(x * 1000 for x in ts)) |
| 792 | elif self.mode == "meter": |
| 793 | METER.reset(); DYN.clear(); ts = [] |
| 794 | for j in range(warm, warm + n): |
| 795 | METER.stack.clear() |
| 796 | METER.enabled = True |
| 797 | t = pc(); r = case.run(j); ts.append(pc() - t) |
| 798 | METER.enabled = False |
| 799 | case.check(j, r) |
| 800 | res.update(n=n, meter_wall_ms=sum(ts) / n * 1000, meter_wall_list=sorted(x * 1000 for x in ts), |
| 801 | calls={k: v / n for k, v in METER.calls.items()}, |
| 802 | excl_ms={k: v / n * 1000 for k, v in METER.excl.items()}, |
| 803 | incl_ms={k: v / n * 1000 for k, v in METER.incl.items()}, |
| 804 | dyn={f"{k[0]}:{k[1]}": v / n for k, v in DYN.items()}, |
| 805 | opens_r=METER.opens_r / n, opens_w=METER.opens_w / n, |
| 806 | open_paths={k: v / n for k, v in METER.open_paths.most_common(10)}) |
| 807 | else: |
| 808 | prof = cProfile.Profile(); ts = [] |
| 809 | for j in range(warm, warm + n): |
| 810 | prof.enable() |
| 811 | t = pc(); r = case.run(j); ts.append(pc() - t) |
| 812 | prof.disable() |
| 813 | case.check(j, r) |
| 814 | res.update(n=n, prof_wall_ms=sum(ts) / n * 1000, **summarize_profile(prof, n)) |
| 815 | except Fail as exc: |
| 816 | res["FAILED"] = f"response check failed: {exc}" |
| 817 | except Exception as exc: # noqa: BLE001 |
| 818 | import traceback |
| 819 | res["FAILED"] = f"{type(exc).__name__}: {exc}\n{traceback.format_exc()[-600:]}" |
| 820 | return self.results |
| 821 | |
| 822 | |
| 823 | def summarize_profile(prof: cProfile.Profile, n: int, top: int = 14) -> dict: |
| 824 | st = pstats.Stats(prof) |
| 825 | rows = [] |
| 826 | here = str(Path(__file__).resolve()) |
| 827 | for (fn, line, name), (cc, nc, tt, ct, _callers) in st.stats.items(): |
| 828 | if fn == here or name in ("disable", "enable"): |
| 829 | continue |
| 830 | short = fn.replace(str(REPO) + "/", "") |
| 831 | if "/lib/python" in short: |
| 832 | short = "py:" + short.split("/lib/python3.15/")[-1] if "/lib/python3.15/" in short else short.rsplit("/", 1)[-1] |
| 833 | rows.append({"fn": f"{short}:{line}({name})", "calls": nc / n, "tot_ms": tt / n * 1000, "cum_ms": ct / n * 1000}) |
| 834 | return {"prof_cum": sorted(rows, key=lambda r: -r["cum_ms"])[:top], "prof_tot": sorted(rows, key=lambda r: -r["tot_ms"])[:top], |
| 835 | "prof_total_calls": sum(r["calls"] for r in rows)} |
| 836 | |
| 837 | |
| 838 | def measure(args) -> dict: |
| 839 | tmp = Path(tempfile.mkdtemp(prefix="profreq-")) |
| 840 | try: |
| 841 | t0 = pc() |
| 842 | info = seed(tmp, args.users, args.packages) |
| 843 | seed_s = pc() - t0 |
| 844 | drv = Driver(info["tokens"]) |
| 845 | ctx = Ctx(drv, args.users) |
| 846 | t0 = pc() |
| 847 | ev_rows = prefill_event_log(tmp) |
| 848 | prefill_changelog(tmp, args.changelog_prefill, ["notes", "order_lines", "payments", "contacts"]) |
| 849 | cases = build_cases(ctx, info["installed"]) |
| 850 | if args.only: |
| 851 | keep = set(args.only.split(",")) |
| 852 | cases = [c for c in cases if c.name in keep or (c.group and c.group in keep)] |
| 853 | groups = case_groups(cases) |
| 854 | out: dict = {"users": args.users, "packages": len(info["installed"]), "failed_installs": info["failed"], "seed_s": seed_s, |
| 855 | "event_log_rows_after_prefill": ev_rows, "changelog_prefill": args.changelog_prefill, "cases": {}, "order": [c.name for c in cases]} |
| 856 | # one cold request first so imports / first-use caches are not billed to anyone |
| 857 | verify = verify_fanout(ctx, tmp, info["installed"]) |
| 858 | out["fanout_verified"] = verify |
| 859 | out["files"] = {coll: (tmp / "data" / "collections" / coll / "records.tsv").stat().st_size |
| 860 | for coll in ("notes", "orders", "order_lines", "projects", "project_access", "payments", "contacts") if (tmp / "data" / "collections" / coll / "records.tsv").exists()} |
| 861 | out["policy_rules"] = len(json.loads((tmp / "data" / "permissions" / "policy.json").read_text())["rules"]) |
| 862 | out["sessions_file_bytes"] = (tmp / "data" / "identity" / "sessions.tsv").stat().st_size if (tmp / "data" / "identity" / "sessions.tsv").exists() else None |
| 863 | for mode in ("wall", "meter", "cprof"): |
| 864 | if mode == "wall" and False: |
| 865 | pass |
| 866 | if mode == "meter": |
| 867 | install_instruments() |
| 868 | if mode == "cprof": |
| 869 | set_instruments(False) |
| 870 | elif mode == "meter": |
| 871 | set_instruments(True) |
| 872 | if mode == "cprof" and args.no_cprofile: |
| 873 | continue |
| 874 | for g in groups: |
| 875 | res = GroupRun(ctx, g, mode, args).run() |
| 876 | for k, v in res.items(): |
| 877 | out["cases"].setdefault(k, {}).update({f"{mode}": v}) |
| 878 | print(f" [{args.users} users] {mode:5s} {g[0].name}" + (" ..." if len(g) > 1 else "") + |
| 879 | "".join(f" FAILED({k})" for k, v in res.items() if "FAILED" in v), file=sys.stderr, flush=True) |
| 880 | out["skipped_instruments"] = METER.skipped |
| 881 | return out |
| 882 | finally: |
| 883 | shutil.rmtree(tmp, ignore_errors=True) |
| 884 | |
| 885 | |
| 886 | # ===================================================================================================== |
| 887 | # reporting |
| 888 | # ===================================================================================================== |
| 889 | KNOWN = [ # (name, labels whose INCLUSIVE time is summed) |
| 890 | ("(1) check_permission, all calls", ["perm.check_permission"]), |
| 891 | ("(2) session lookup", ["identity.session lookup"]), |
| 892 | ("(3a) durable event publish", ["fanout.durable event log"]), |
| 893 | ("(3b) change-log latest lookup", ["fanout.change lookup"]), |
| 894 | ("(4) _redact_records_for_permission", ["list.redact (check_permission+field policy/row)"]), |
| 895 | ("(5) project_access/projects/record_shares scans", ["identity.project_access+projects scan", "identity.record_shares scan"]), |
| 896 | ] |
| 897 | COUNTS = [("read_collection_records", "storage.read_collection_records"), ("parse_records_file (cache miss)", "storage.parse_records_file (cache MISS)"), |
| 898 | ("get_object_state", "state.get_object_state"), ("check_permission", "perm.check_permission"), ("identity resolutions", "identity.total"), |
| 899 | ("session lookups", "identity.session lookup"), ("policy load_policy", "policy.load_policy"), ("object loads (_load_module)", "exec.load_module (object import)"), |
| 900 | ("execute_object", "exec.execute_object"), ("get_schema", "schema.get_schema"), ("json.loads", "json.loads"), ("json.dumps", "json.dumps"), |
| 901 | ("csv.reader", "csv.reader"), ("os.stat", "os.stat"), ("os.fsync", "os.fsync"), ("os.replace", "os.replace"), ("iter_object_sources (dir scans)", "ns.iter_object_sources (dir scan)"), |
| 902 | ("handler index BUILD", "fanout.handler index BUILD")] |
| 903 | |
| 904 | |
| 905 | def fmt_ms(x): |
| 906 | return f"{x:9.3f}" if x < 100 else f"{x:9.1f}" |
| 907 | |
| 908 | |
| 909 | def stage_table(m: dict, top: int = 14) -> list[str]: |
| 910 | wall = m["meter_wall_ms"] |
| 911 | rows = sorted(m["excl_ms"].items(), key=lambda kv: -kv[1]) |
| 912 | out = [f" {'stage (exclusive time)':<52}{'calls/req':>10}{'excl ms':>10}{'excl %':>8}{'incl ms':>10}{'incl %':>8}"] |
| 913 | acc = 0.0 |
| 914 | for label, ex in rows[:top]: |
| 915 | if label in ("json.loads", "json.dumps"): |
| 916 | continue |
| 917 | inc = m["incl_ms"].get(label, 0.0) |
| 918 | acc += ex |
| 919 | out.append(f" {label:<52}{m['calls'].get(label, 0):>10.1f}{ex:>10.3f}{ex / wall * 100:>7.1f}%{inc:>10.3f}{inc / wall * 100:>7.1f}%") |
| 920 | total_ex = sum(m["excl_ms"].values()) |
| 921 | out.append(f" {'(all other: routing, framework, response build, python glue)':<52}{'':>10}{wall - total_ex:>10.3f}{(wall - total_ex) / wall * 100:>7.1f}%") |
| 922 | return out |
| 923 | |
| 924 | |
| 925 | def report_one(out: dict, w=sys.stdout): |
| 926 | P = lambda *a: print(*a, file=w) # noqa: E731 |
| 927 | P(f"\n{'#' * 110}\n# {out['users']} users | {out['packages']} packages | policy rules {out['policy_rules']} | event log prefilled to {out['event_log_rows_after_prefill']} rows | " |
| 928 | f"changelog prefill {out['changelog_prefill']}/collection | seed {out['seed_s']:.0f}s\n{'#' * 110}") |
| 929 | P("fan-out verified:", json.dumps(out["fanout_verified"])) |
| 930 | P("collection file bytes:", json.dumps(out["files"])) |
| 931 | for name in out["order"]: |
| 932 | c = out["cases"].get(name, {}) |
| 933 | wl, mt, cp = c.get("wall", {}), c.get("meter", {}), c.get("cprof", {}) |
| 934 | P(f"\n== {name}: {wl.get('title') or mt.get('title') or cp.get('title')}") |
| 935 | for mode, r in (("wall", wl), ("meter", mt), ("cprof", cp)): |
| 936 | if "FAILED" in r: |
| 937 | P(f" !! {mode} phase FAILED (this request type is NOT profiled): {r['FAILED']}") |
| 938 | if "wall_ms" in wl: |
| 939 | ws = wl["wall_ms"] |
| 940 | P(f" wall (bare, no profiler, n={wl['n']}): best {ws[0]:.3f} ms median {statistics.median(ws):.3f} ms p90 {pct(ws, .9):.3f} ms max {ws[-1]:.3f} ms") |
| 941 | if "meter_wall_ms" in mt and "wall_ms" in wl: |
| 942 | P(f" with stage wrappers: {mt['meter_wall_ms']:.3f} ms/req (x{mt['meter_wall_ms'] / statistics.median(wl['wall_ms']):.2f} of bare median -- wrapper overhead; percentages below use this denominator)") |
| 943 | for line in stage_table(mt): |
| 944 | P(line) |
| 945 | kn = [] |
| 946 | for nm, labels in KNOWN: |
| 947 | inc = sum(mt["incl_ms"].get(l, 0.0) for l in labels) |
| 948 | kn.append(f"{nm}: {inc:.3f} ms ({inc / mt['meter_wall_ms'] * 100:.1f}%)") |
| 949 | P(" known items (inclusive, may overlap):") |
| 950 | for k in kn: |
| 951 | P(" " + k) |
| 952 | cnt = ", ".join(f"{nm} {mt['calls'].get(l, 0):.1f}" for nm, l in COUNTS if mt["calls"].get(l, 0)) |
| 953 | P(f" counts/req: {cnt}") |
| 954 | P(f" file opens/req (data+objects dirs only): read {mt['opens_r']:.1f}, write/append {mt['opens_w']:.1f}") |
| 955 | P(" opens by path: " + "; ".join(f"{k} x{v:.1f}" for k, v in list(mt["open_paths"].items())[:7])) |
| 956 | dyn = mt["dyn"] |
| 957 | for kind in ("read_collection", "parse_file", "exec", "load_module", "get_object_state"): |
| 958 | items = sorted(((k.split(':', 1)[1], v) for k, v in dyn.items() if k.startswith(kind + ':')), key=lambda kv: -kv[1])[:8] |
| 959 | if items: |
| 960 | P(f" {kind} by target: " + ", ".join(f"{k} x{v:.1f}" for k, v in items)) |
| 961 | cp_items = sorted(((k.split(':', 1)[1], v) for k, v in dyn.items() if k.startswith("check_permission:")), key=lambda kv: -kv[1])[:5] |
| 962 | if cp_items: |
| 963 | P(" check_permission by action:collection: " + ", ".join(f"{k} x{v:.1f}" for k, v in cp_items)) |
| 964 | if "prof_cum" in cp: |
| 965 | P(f" cProfile (n={cp['n']}, {cp['prof_wall_ms']:.3f} ms/req under profiler, {cp['prof_total_calls']:.0f} python calls/req):") |
| 966 | P(f" {'by CUMULATIVE':<92}{'calls/req':>10}{'tot ms':>9}{'cum ms':>9}") |
| 967 | for r in cp["prof_cum"][:10]: |
| 968 | P(f" {r['fn'][:90]:<92}{r['calls']:>10.1f}{r['tot_ms']:>9.3f}{r['cum_ms']:>9.3f}") |
| 969 | P(f" {'by TOTAL (self) time':<92}{'calls/req':>10}{'tot ms':>9}{'cum ms':>9}") |
| 970 | for r in cp["prof_tot"][:10]: |
| 971 | P(f" {r['fn'][:90]:<92}{r['calls']:>10.1f}{r['tot_ms']:>9.3f}{r['cum_ms']:>9.3f}") |
| 972 | |
| 973 | |
| 974 | def report_compare(outs: list[dict], w=sys.stdout): |
| 975 | P = lambda *a: print(*a, file=w) # noqa: E731 |
| 976 | sizes = [o["users"] for o in outs] |
| 977 | P(f"\n{'=' * 110}\nCOMPARISON {' vs '.join(str(s) + ' users' for s in sizes)}\n{'=' * 110}") |
| 978 | P("\nWALL TIME per request, bare (no profiler/wrappers), ms. best / median. Status+shape checked on every response.") |
| 979 | P(f"{'request':<26}" + "".join(f"{s:>9}u best{s:>9}u med" for s in sizes) + f"{'x growth (med)':>16} status") |
| 980 | for name in outs[0]["order"]: |
| 981 | row, meds = f"{name:<26}", [] |
| 982 | stat = "ok" |
| 983 | for o in outs: |
| 984 | c = o["cases"].get(name, {}).get("wall", {}) |
| 985 | if "FAILED" in c or "wall_ms" not in c: |
| 986 | row += f"{'FAILED':>14}{'':>14}"; stat = "FAILED"; meds.append(None) |
| 987 | else: |
| 988 | ws = c["wall_ms"]; row += f"{ws[0]:>14.3f}{statistics.median(ws):>14.3f}"; meds.append(statistics.median(ws)) |
| 989 | gr = f"{meds[-1] / meds[0]:.1f}x" if all(meds) else "-" |
| 990 | P(row + f"{gr:>16} {stat}") |
| 991 | # page-load bundle |
| 992 | P("\nPAGE-LOAD BUNDLE for /notes (server time, median ms, sum of the page's own requests; a browser would issue these)") |
| 993 | bundle_names = [n for n in outs[0]["order"] if n.startswith(("page_notes", "load_", "asset_"))] |
| 994 | for o in outs: |
| 995 | tot = sum(statistics.median(o["cases"][n]["wall"]["wall_ms"]) for n in bundle_names if "wall_ms" in o["cases"].get(n, {}).get("wall", {})) |
| 996 | assets = sum(statistics.median(o["cases"][n]["wall"]["wall_ms"]) for n in bundle_names if n.startswith("asset_") and "wall_ms" in o["cases"].get(n, {}).get("wall", {})) |
| 997 | data = sum(statistics.median(o["cases"][n]["wall"]["wall_ms"]) for n in bundle_names if n.startswith("load_") and "wall_ms" in o["cases"].get(n, {}).get("wall", {})) |
| 998 | pg = statistics.median(o["cases"]["page_notes"]["wall"]["wall_ms"]) |
| 999 | P(f" {o['users']:>5} users: total {tot:8.1f} ms = html {pg:7.1f} + {len([n for n in bundle_names if n.startswith('asset_')])} static assets {assets:7.1f} + {len([n for n in bundle_names if n.startswith('load_')])} data calls {data:7.1f}") |
| 1000 | # stage growth |
| 1001 | P("\nSTAGE GROWTH (exclusive ms/req from wrapper run; only stages that are >=3% of a request at some size)") |
| 1002 | for name in outs[0]["order"]: |
| 1003 | ms = [o["cases"].get(name, {}).get("meter", {}) for o in outs] |
| 1004 | if any("excl_ms" not in m for m in ms): |
| 1005 | continue |
| 1006 | labels = set() |
| 1007 | for m in ms: |
| 1008 | for l, v in m["excl_ms"].items(): |
| 1009 | if v / m["meter_wall_ms"] >= 0.03 and l not in ("json.loads", "json.dumps"): |
| 1010 | labels.add(l) |
| 1011 | if not labels: |
| 1012 | continue |
| 1013 | P(f" {name}") |
| 1014 | P(f" {'stage':<52}" + "".join(f"{s:>9}u ms{'%':>6}" for s in sizes) + f"{'calls/req':>22} grows") |
| 1015 | for l in sorted(labels, key=lambda l: -ms[-1]["excl_ms"].get(l, 0)): |
| 1016 | vals = [m["excl_ms"].get(l, 0.0) for m in ms] |
| 1017 | calls = [m["calls"].get(l, 0.0) for m in ms] |
| 1018 | g = vals[-1] / vals[0] if vals[0] > 1e-6 else float("inf") |
| 1019 | flag = "SCALES" if g > 3 else "" |
| 1020 | P(f" {l:<52}" + "".join(f"{v:>12.3f}{v / m['meter_wall_ms'] * 100:>5.0f}%" for v, m in zip(vals, ms)) + f"{'/'.join(f'{c:.0f}' for c in calls):>22} {g:5.1f}x {flag}") |
| 1021 | other = [m["meter_wall_ms"] - sum(m["excl_ms"].values()) for m in ms] |
| 1022 | P(f" {'(other / framework)':<52}" + "".join(f"{v:>12.3f}{v / m['meter_wall_ms'] * 100:>5.0f}%" for v, m in zip(other, ms))) |
| 1023 | P("\nPER-REQUEST COUNTS (calls/req). columns: " + " / ".join(f"{s}u" for s in sizes)) |
| 1024 | keys = [(nm, l) for nm, l in COUNTS] |
| 1025 | for name in outs[0]["order"]: |
| 1026 | ms = [o["cases"].get(name, {}).get("meter", {}) for o in outs] |
| 1027 | if any("calls" not in m for m in ms): |
| 1028 | continue |
| 1029 | parts = [] |
| 1030 | for nm, l in keys: |
| 1031 | vals = [m["calls"].get(l, 0.0) for m in ms] |
| 1032 | if any(vals): |
| 1033 | parts.append(f"{nm} {'/'.join(f'{v:.0f}' for v in vals)}") |
| 1034 | opens_r = "/".join(f"{m['opens_r']:.0f}" for m in ms) |
| 1035 | opens_w = "/".join(f"{m['opens_w']:.0f}" for m in ms) |
| 1036 | parts.append(f"opens R {opens_r} W {opens_w}") |
| 1037 | P(f" {name:<24} " + "; ".join(parts)) |
| 1038 | P("\nKNOWN ITEMS as % of request (inclusive, bare wrapper-run wall). columns: " + " / ".join(f"{s}u" for s in sizes)) |
| 1039 | P(f" {'request':<24}" + "".join(f"{nm.split(')')[0] + ')':>9}" for nm, _ in KNOWN)) |
| 1040 | for name in outs[0]["order"]: |
| 1041 | ms = [o["cases"].get(name, {}).get("meter", {}) for o in outs] |
| 1042 | if any("incl_ms" not in m for m in ms): |
| 1043 | continue |
| 1044 | cells = [] |
| 1045 | for nm, labels in KNOWN: |
| 1046 | vals = [sum(m["incl_ms"].get(l, 0.0) for l in labels) / m["meter_wall_ms"] * 100 for m in ms] |
| 1047 | cells.append("/".join(f"{v:.0f}" for v in vals)) |
| 1048 | P(f" {name:<24}" + "".join(f"{c:>9}" for c in cells)) |
| 1049 | |
| 1050 | |
| 1051 | # ===================================================================================================== |
| 1052 | # what-if: the cheapest plausible fixes, monkeypatched into THIS process only, to turn "inferred" into "measured" |
| 1053 | # ===================================================================================================== |
| 1054 | def _replace(modname: str, attr: str, new): |
| 1055 | mod = sys.modules[modname] |
| 1056 | orig = getattr(mod, attr) |
| 1057 | setattr(mod, attr, new) |
| 1058 | patch_everywhere(orig, new) |
| 1059 | return (modname, attr, orig, new) |
| 1060 | |
| 1061 | |
| 1062 | def _undo(tok): |
| 1063 | modname, attr, orig, new = tok |
| 1064 | setattr(sys.modules[modname], attr, orig) |
| 1065 | patch_everywhere(new, orig) |
| 1066 | |
| 1067 | |
| 1068 | def whatif_patches(): |
| 1069 | """name -> factory returning a list of undo tokens. Each is the smallest obvious cache; none is wired into the server.""" |
| 1070 | import object_permission_store |
| 1071 | import object_records |
| 1072 | import object_schemas |
| 1073 | import object_server |
| 1074 | |
| 1075 | def p_schema(): |
| 1076 | real = object_schemas.get_schema |
| 1077 | cache: dict = {} |
| 1078 | |
| 1079 | def fast(schema, *, base_dir=object_schemas.DEFAULT_DATA_DIR, roots=None): |
| 1080 | if not object_schemas.validate_schema_name(schema): |
| 1081 | return real(schema, base_dir=base_dir, roots=roots) |
| 1082 | path = f"{base_dir}/schemas/{schema}.json" |
| 1083 | try: |
| 1084 | st = os.stat(path) |
| 1085 | except OSError: |
| 1086 | return real(schema, base_dir=base_dir, roots=roots) # absent: keep the real (slow) semantics |
| 1087 | sig = (st.st_mtime_ns, st.st_size, st.st_ino) |
| 1088 | hit = cache.get(path) |
| 1089 | if hit is not None and hit[0] == sig: |
| 1090 | return hit[1] |
| 1091 | val = real(schema, base_dir=base_dir, roots=roots) |
| 1092 | cache[path] = (sig, val) |
| 1093 | return val |
| 1094 | return [_replace("object_schemas", "get_schema", fast)] |
| 1095 | |
| 1096 | def p_policy(): |
| 1097 | real = object_permission_store.load_policy |
| 1098 | cache: dict = {} |
| 1099 | |
| 1100 | def fast(base_dir=object_permission_store.DEFAULT_DATA_DIR): |
| 1101 | path = f"{base_dir}/permissions/policy.json" |
| 1102 | try: |
| 1103 | st = os.stat(path) |
| 1104 | except OSError: |
| 1105 | return real(base_dir) |
| 1106 | sig = (st.st_mtime_ns, st.st_size, st.st_ino) |
| 1107 | hit = cache.get(path) |
| 1108 | if hit is not None and hit[0] == sig: |
| 1109 | return hit[1] |
| 1110 | val = real(base_dir) |
| 1111 | cache[path] = (sig, val) |
| 1112 | return val |
| 1113 | return [_replace("object_permission_store", "load_policy", fast)] |
| 1114 | |
| 1115 | def p_rollup(): |
| 1116 | real = object_records._rollup_parents_for_source |
| 1117 | cache: dict = {} |
| 1118 | |
| 1119 | def fast(source_collection, *, base_dir, roots): |
| 1120 | try: |
| 1121 | sig = os.stat(f"{base_dir}/schemas").st_mtime_ns # dir mtime: add/remove/atomic-replace of a schema file |
| 1122 | except OSError: |
| 1123 | return real(source_collection, base_dir=base_dir, roots=roots) |
| 1124 | key = (str(base_dir), source_collection) |
| 1125 | hit = cache.get(key) |
| 1126 | if hit is not None and hit[0] == sig: |
| 1127 | return hit[1] |
| 1128 | val = real(source_collection, base_dir=base_dir, roots=roots) |
| 1129 | cache[key] = (sig, val) |
| 1130 | return val |
| 1131 | return [_replace("object_records", "_rollup_parents_for_source", fast)] |
| 1132 | |
| 1133 | def p_site_hosts(): |
| 1134 | real = object_server._site_host_records |
| 1135 | |
| 1136 | def fast(): |
| 1137 | if not (Path(object_server._data_dir()) / "collections" / "site_hosts" / "records.tsv").exists(): |
| 1138 | return [] # exactly what the real one returns on CollectionNotFound |
| 1139 | return real() |
| 1140 | return [_replace("object_server", "_site_host_records", fast)] |
| 1141 | |
| 1142 | def p_sources(): |
| 1143 | import object_namespace |
| 1144 | real = object_namespace.iter_object_sources |
| 1145 | cache: dict = {} |
| 1146 | |
| 1147 | def fast(roots=None): |
| 1148 | search_roots = list(roots) if roots is not None else object_namespace.get_object_roots() |
| 1149 | try: |
| 1150 | sig = [] |
| 1151 | for r in search_roots: |
| 1152 | sig.append(os.stat(r).st_mtime_ns) |
| 1153 | with os.scandir(r) as it: # objects live one directory deep (+ users/<id>/) |
| 1154 | for e in it: |
| 1155 | if e.is_dir(follow_symlinks=False) and not e.name.startswith((".", "__")): |
| 1156 | sig.append(e.stat().st_mtime_ns) |
| 1157 | if e.name == "users": |
| 1158 | with os.scandir(e.path) as it2: |
| 1159 | sig.extend(x.stat().st_mtime_ns for x in it2 if x.is_dir(follow_symlinks=False)) |
| 1160 | sig = tuple(sig) |
| 1161 | except OSError: |
| 1162 | return real(roots) |
| 1163 | key = tuple(str(r) for r in search_roots) |
| 1164 | hit = cache.get(key) |
| 1165 | if hit is not None and hit[0] == sig: |
| 1166 | return list(hit[1]) |
| 1167 | val = real(roots) |
| 1168 | cache[key] = (sig, val) |
| 1169 | return list(val) |
| 1170 | return [_replace("object_namespace", "iter_object_sources", fast)] |
| 1171 | |
| 1172 | return [("get_schema stat-keyed cache", p_schema), ("load_policy stat-keyed cache", p_policy), |
| 1173 | ("rollup-parents memo (schemas dir mtime)", p_rollup), ("iter_object_sources cached by objects-dir mtimes", p_sources), |
| 1174 | ("site_hosts absent short-circuit", p_site_hosts)] |
| 1175 | |
| 1176 | |
| 1177 | WHATIF_CASES = ["list_notes", "get_note", "note", "orderline", "payment", "page_notes", "asset_style", "search_note", "load_views_200", |
| 1178 | "load_nav_entries", "anon_public_rows"] |
| 1179 | WHATIF_EQ = ["list_notes", "get_note", "load_views_200", "page_notes", "asset_style", "load_schema_notes", "search_note", "anon_public_rows"] |
| 1180 | |
| 1181 | |
| 1182 | def whatif(args) -> dict: |
| 1183 | tmp = Path(tempfile.mkdtemp(prefix="profreq-wi-")) |
| 1184 | try: |
| 1185 | info = seed(tmp, args.users, args.packages) |
| 1186 | drv = Driver(info["tokens"]) |
| 1187 | ctx = Ctx(drv, args.users) |
| 1188 | prefill_event_log(tmp) |
| 1189 | cases = build_cases(ctx, info["installed"]) |
| 1190 | keep = set(WHATIF_CASES) |
| 1191 | cases = [c for c in cases if c.name in keep or (c.group and c.group in keep)] |
| 1192 | groups = case_groups(cases) |
| 1193 | eqcases = {c.name: c for c in build_cases(ctx, info["installed"]) if c.name in WHATIF_EQ} |
| 1194 | verify_fanout(ctx, tmp, info["installed"]) |
| 1195 | |
| 1196 | def snapshot(): |
| 1197 | out = {} |
| 1198 | for n, c in eqcases.items(): |
| 1199 | r = c.run(0) |
| 1200 | out[n] = r[2] if r[0] == 200 else f"status {r[0]}".encode() |
| 1201 | return out |
| 1202 | |
| 1203 | a = argparse.Namespace(**vars(args)); a.budget = args.budget |
| 1204 | configs, tokens = [("baseline", None)], [] |
| 1205 | for name, factory in whatif_patches(): |
| 1206 | configs.append(("+ " + name, factory)) |
| 1207 | results, base_snap = {}, None |
| 1208 | for label, factory in configs: |
| 1209 | if factory is not None: |
| 1210 | tokens += factory() |
| 1211 | snap = snapshot() |
| 1212 | if base_snap is None: |
| 1213 | base_snap = snap |
| 1214 | same = {n: (snap[n] == base_snap[n]) for n in snap} |
| 1215 | row = {} |
| 1216 | for g in groups: |
| 1217 | res = GroupRun(ctx, g, "wall", a).run() |
| 1218 | for k, v in res.items(): |
| 1219 | row[k] = statistics.median(v["wall_ms"]) if "wall_ms" in v else None |
| 1220 | results[label] = {"ms": row, "responses_identical_to_baseline": same} |
| 1221 | print(f" [{args.users} users] what-if done: {label}", file=sys.stderr, flush=True) |
| 1222 | for t in reversed(tokens): |
| 1223 | _undo(t) |
| 1224 | return {"users": args.users, "results": results, "order": [c.name for c in cases]} |
| 1225 | finally: |
| 1226 | shutil.rmtree(tmp, ignore_errors=True) |
| 1227 | |
| 1228 | |
| 1229 | def report_whatif(outs: list[dict]): |
| 1230 | for o in outs: |
| 1231 | labels = list(o["results"]) |
| 1232 | print(f"\nWHAT-IF (median ms, bare, cumulative patches, {o['users']} users)") |
| 1233 | print(f"{'request':<20}" + "".join(f"{('c' + str(i)):>10}" for i in range(len(labels))) + f"{'saved':>9}") |
| 1234 | for i, l in enumerate(labels): |
| 1235 | print(f" c{i} = {l}") |
| 1236 | for n in o["order"]: |
| 1237 | vals = [o["results"][l]["ms"].get(n) for l in labels] |
| 1238 | if not all(vals): |
| 1239 | continue |
| 1240 | print(f"{n:<20}" + "".join(f"{v:>10.2f}" for v in vals) + f"{(1 - vals[-1] / vals[0]) * 100:>8.0f}%") |
| 1241 | last = o["results"][labels[-1]]["responses_identical_to_baseline"] |
| 1242 | print(" response bytes identical to baseline after all patches: " + ", ".join(f"{k}={'yes' if v else 'NO'}" for k, v in last.items())) |
| 1243 | |
| 1244 | |
| 1245 | # ===================================================================================================== |
| 1246 | # micro-measurements for the scaling questions that a whole-request number cannot isolate |
| 1247 | # ===================================================================================================== |
| 1248 | def best_of(fn, n=200, trials=7): |
| 1249 | best = 1e9 |
| 1250 | for _ in range(trials): |
| 1251 | t = pc() |
| 1252 | for _ in range(n): |
| 1253 | fn() |
| 1254 | best = min(best, (pc() - t) / n) |
| 1255 | return best * 1e6 |
| 1256 | |
| 1257 | |
| 1258 | def micro(args): |
| 1259 | tmp = Path(tempfile.mkdtemp(prefix="profreq-micro-")) |
| 1260 | try: |
| 1261 | info = seed(tmp, 10, args.packages) |
| 1262 | data = tmp / "data" |
| 1263 | import object_events, object_permission_store, object_permissions as op, object_schemas, object_server, object_records, object_collections |
| 1264 | print("\nMICRO (best-of-7 trials, microseconds per call, single process, shared machine => indicative)") |
| 1265 | policy = object_permission_store.load_policy(data) |
| 1266 | subj = op.PermissionSubject(user_id="u1", roles=(), project_ids=("p2_0", "p3_0", "p4_0"), owned_project_ids=("p1_0", "p1_1")) |
| 1267 | row = {"id": "n1_1", "owner_id": "u1", "project_id": "p1_0", "is_public": "false", "content": "x"} |
| 1268 | t_full = best_of(lambda: op.check_permission(subj, "read", policy=policy, collection="notes", record=row), n=300) |
| 1269 | at = op.datetime.now(op.timezone.utc) |
| 1270 | keep = tuple(r for r in policy.rules if op._rule_is_active(r, at) and op._action_matches(r, "read") and op._resource_matches(r, collection="notes", object_id=None)) |
| 1271 | import dataclasses |
| 1272 | narrow = dataclasses.replace(policy, rules=keep) |
| 1273 | t_narrow = best_of(lambda: op.check_permission(subj, "read", policy=narrow, collection="notes", record=row), n=300) |
| 1274 | print(f" check_permission(read notes row): full policy {len(policy.rules)} rules {t_full:7.1f} us | narrowed to the {len(keep)} rules for (read, notes) {t_narrow:7.1f} us | rule scan = {(1 - t_narrow / t_full) * 100:.0f}% of the call") |
| 1275 | print(f" load_policy (parse policy.json + rule_from_dict x{len(policy.rules)}): {best_of(lambda: object_permission_store.load_policy(data), n=30):9.1f} us/call") |
| 1276 | print(f" get_schema('notes') warm (mtime-cached object, but 4x resolve + 3x stat per call): {best_of(lambda: object_schemas.get_schema('notes', base_dir=data), n=300):7.1f} us/call") |
| 1277 | print(f" os.stat of the schema file alone: {best_of(lambda: os.stat(data / 'schemas' / 'notes.json'), n=2000):7.1f} us/call Path.resolve(): {best_of(lambda: (data / 'schemas' / 'notes.json').resolve(strict=False), n=300):7.1f} us/call") |
| 1278 | n_sch = len(list((data / 'schemas').glob('*.json'))) |
| 1279 | print(f" schemas on disk: {n_sch} _rollup_parents_for_source('notes') (runs on EVERY write): {best_of(lambda: object_records._rollup_parents_for_source('notes', base_dir=data, roots=None), n=20):9.1f} us/call") |
| 1280 | for coll in ("site_hosts", "record_shares", "project_access"): |
| 1281 | def rd(coll=coll): |
| 1282 | try: |
| 1283 | object_records.read_collection_records(coll, base_dir=data) |
| 1284 | except Exception: |
| 1285 | pass |
| 1286 | has_schema = (data / "schemas" / f"{coll}.json").exists(); has_rec = (data / "collections" / coll / "records.tsv").exists() |
| 1287 | print(f" read_collection_records('{coll}') [schema file: {has_schema}, records file: {has_rec}]: {best_of(rd, n=5):10.1f} us/call") |
| 1288 | print(f" object_collections.list_collections() (what a missing-schema collection triggers): {best_of(lambda: object_collections.list_collections(base_dir=data), n=3, trials=5):10.1f} us/call") |
| 1289 | # durable event log: publish cost vs rows already in the log |
| 1290 | print(" durable event publish vs log rows (default retention caps the log at 1000 rows):") |
| 1291 | ev_tmp = tmp / "evdata" |
| 1292 | for target in (0, 100, 500, 1000): |
| 1293 | f = ev_tmp / "state" / "events" / "state.tsv" |
| 1294 | if f.exists(): |
| 1295 | f.unlink() |
| 1296 | for _ in range(target): |
| 1297 | object_events.publish_event("bench.x", payload={"collection": "notes", "record_id": "x", "action": "create"}, base_dir=ev_tmp, keep_count=None, keep_seconds=None) |
| 1298 | us = best_of(lambda: object_events.publish_event("bench.x", payload={"collection": "notes", "record_id": "x", "action": "create"}, base_dir=ev_tmp, |
| 1299 | keep_count=target + 1000, keep_seconds=7 * 86400), n=10, trials=3) |
| 1300 | print(f" log at ~{target:>4} rows: {us:9.1f} us/publish file {f.stat().st_size / 1024:.0f} KiB") |
| 1301 | finally: |
| 1302 | shutil.rmtree(tmp, ignore_errors=True) |
| 1303 | |
| 1304 | |
| 1305 | # ===================================================================================================== |
| 1306 | def main() -> int: |
| 1307 | ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| 1308 | ap.add_argument("--users", type=int, default=10) |
| 1309 | ap.add_argument("--compare", help="comma list of sizes, e.g. 10,1000 (one subprocess per size)") |
| 1310 | ap.add_argument("--packages", default="full", choices=["full", "core"]) |
| 1311 | ap.add_argument("--only", default="") |
| 1312 | ap.add_argument("--reps", type=int, default=100, help="max timed repetitions per request") |
| 1313 | ap.add_argument("--profile-reps", type=int, default=40) |
| 1314 | ap.add_argument("--budget", type=float, default=1.2, help="target seconds of measured work per case per phase") |
| 1315 | ap.add_argument("--changelog-prefill", type=int, default=0, help="pre-existing change-log entries per written collection") |
| 1316 | ap.add_argument("--no-cprofile", action="store_true") |
| 1317 | ap.add_argument("--micro", action="store_true", help="isolate scaling questions: rule scan, get_schema, policy load, event-log size") |
| 1318 | ap.add_argument("--whatif", action="store_true", help="re-time the hot requests with the cheapest candidate fixes monkeypatched in") |
| 1319 | ap.add_argument("--json", default="") |
| 1320 | ap.add_argument("--out", default="", help="also write the text report here") |
| 1321 | ap.add_argument("--from-json", default="", help="no measuring: re-print the report from saved --json file(s), comma separated") |
| 1322 | a = ap.parse_args() |
| 1323 | |
| 1324 | if a.micro: |
| 1325 | micro(a) |
| 1326 | return 0 |
| 1327 | |
| 1328 | if a.whatif: |
| 1329 | outs = [] |
| 1330 | for sz in ([int(x) for x in a.compare.split(",")] if a.compare else [a.users]): |
| 1331 | b = argparse.Namespace(**vars(a)); b.users = sz |
| 1332 | outs.append(whatif(b)) |
| 1333 | if a.json: |
| 1334 | Path(a.json).write_text(json.dumps(outs)) |
| 1335 | report_whatif(outs) |
| 1336 | return 0 |
| 1337 | |
| 1338 | if a.from_json: |
| 1339 | outs = [] |
| 1340 | for f in a.from_json.split(","): |
| 1341 | j = json.loads(Path(f).read_text()) |
| 1342 | outs += j if isinstance(j, list) else [j] |
| 1343 | for o in outs: |
| 1344 | report_one(o) |
| 1345 | if len(outs) > 1: |
| 1346 | report_compare(outs) |
| 1347 | return 0 |
| 1348 | |
| 1349 | if a.compare: |
| 1350 | outs = [] |
| 1351 | for s in [int(x) for x in a.compare.split(",")]: |
| 1352 | jf = tempfile.mktemp(suffix=".json") |
| 1353 | cmd = [PY, "-I", __file__ if False else str(Path(__file__).resolve()), "--users", str(s), "--packages", a.packages, "--reps", str(a.reps), |
| 1354 | "--profile-reps", str(a.profile_reps), "--budget", str(a.budget), "--changelog-prefill", str(a.changelog_prefill), "--json", jf] |
| 1355 | if a.only: cmd += ["--only", a.only] |
| 1356 | if a.no_cprofile: cmd += ["--no-cprofile"] |
| 1357 | subprocess.run(cmd, check=True, cwd=REPO) |
| 1358 | outs.append(json.loads(Path(jf).read_text())); os.unlink(jf) |
| 1359 | sink = open(a.out, "w") if a.out else None |
| 1360 | for o in outs: |
| 1361 | report_one(o); sink and report_one(o, sink) |
| 1362 | report_compare(outs); sink and report_compare(outs, sink) |
| 1363 | if a.json: |
| 1364 | Path(a.json).write_text(json.dumps(outs)) |
| 1365 | return 0 |
| 1366 | |
| 1367 | out = measure(a) |
| 1368 | if a.json: |
| 1369 | Path(a.json).write_text(json.dumps(out)) |
| 1370 | else: |
| 1371 | report_one(out) |
| 1372 | return 0 |
| 1373 | |
| 1374 | |
| 1375 | if __name__ == "__main__": |
| 1376 | raise SystemExit(main()) |