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.
publish_path.py · 6.9 KB · 160 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """Experiment: why does an HTTP create get slower as writes accumulate, and |
| 3 | what would each candidate fix buy? |
| 4 | |
| 5 | Drives object_server.app in-process (no sockets) with POST creates against a |
| 6 | seeded 10k-row append collection, to steady state (the events log reaches its |
| 7 | 1000-row cap), then times more creates. Variants are applied by monkeypatching |
| 8 | THIS process only -- the server's source is not edited: |
| 9 | |
| 10 | original as shipped |
| 11 | +coerce object_state._coerce_value returns early for strings that |
| 12 | start with { [ or " (JSON), which can never be an int/float, |
| 13 | skipping two guaranteed exceptions per row. Exact semantics. |
| 14 | +tail-lookup _record_change_for_publish finds the newest change for the |
| 15 | record by reading the change log from its END instead of |
| 16 | parsing every line. Exact semantics for limit=1. |
| 17 | +memo-json ESTIMATE of caching parsed event rows: lru_cache around |
| 18 | object_events._load_json_object (callers share the dict, so |
| 19 | this bounds what caching could buy, it is not a drop-in). |
| 20 | |
| 21 | python experiments/publish_path.py [--warm 1300] [--measure 200] |
| 22 | """ |
| 23 | from __future__ import annotations |
| 24 | |
| 25 | import argparse |
| 26 | import asyncio |
| 27 | import functools |
| 28 | import json |
| 29 | import os |
| 30 | import statistics |
| 31 | import subprocess |
| 32 | import sys |
| 33 | import tempfile |
| 34 | import time |
| 35 | from pathlib import Path |
| 36 | |
| 37 | REPO = Path(__file__).resolve().parents[3] |
| 38 | HERE = Path(__file__).resolve().parent |
| 39 | BODY = json.dumps({"title": "t", "qty": "1", "status": "open", "owner": "o", "note": "n"}).encode() |
| 40 | |
| 41 | |
| 42 | def setup() -> Path: |
| 43 | tmp = Path(tempfile.mkdtemp()) |
| 44 | subprocess.run([sys.executable, str(HERE.parent / "seed_tsv.py"), str(tmp / "data"), str(tmp / "urls"), |
| 45 | "http://x", "10000"], check=True) |
| 46 | (tmp / "objects").mkdir() |
| 47 | os.environ.update(DBBASIC_OBJECTS_DIR=str(tmp / "objects"), DBBASIC_DATA_DIR=str(tmp / "data"), |
| 48 | DBBASIC_ADMIN_TOKEN="benchtoken", DBBASIC_COOKIE_SECURE="false") |
| 49 | return tmp |
| 50 | |
| 51 | |
| 52 | def tail_lookup(object_record_changes, json_mod): |
| 53 | """Newest change for (collection, record_id), reading the log backwards.""" |
| 54 | def latest(collection: str, record_id: str, base_dir): |
| 55 | path = object_record_changes.record_changes_file(collection, base_dir=base_dir) |
| 56 | if not path.exists(): |
| 57 | return None |
| 58 | # Cheap raw-bytes prefilter, only when it is certain to be sound: a plain |
| 59 | # ASCII id with nothing JSON would escape appears verbatim in its line. |
| 60 | # Anything else is checked by parsing every line (still newest-first). |
| 61 | needle = record_id.encode() if (record_id.isascii() and '"' not in record_id |
| 62 | and "\\" not in record_id) else None |
| 63 | with object_record_changes._file_lock(path), path.open("rb") as handle: |
| 64 | handle.seek(0, 2) |
| 65 | pos, chunk, buf = handle.tell(), 65536, b"" |
| 66 | while pos > 0: |
| 67 | step = min(chunk, pos) |
| 68 | pos -= step |
| 69 | handle.seek(pos) |
| 70 | buf = handle.read(step) + buf |
| 71 | lines = buf.split(b"\n") |
| 72 | buf = lines[0] if pos > 0 else b"" # first piece may be partial |
| 73 | for raw in reversed(lines[1:] if pos > 0 else lines): |
| 74 | if not raw.strip() or (needle is not None and needle not in raw): |
| 75 | continue |
| 76 | try: |
| 77 | entry = json_mod.loads(raw) |
| 78 | except ValueError: |
| 79 | continue |
| 80 | if isinstance(entry, dict) and entry.get("record_id") == record_id: |
| 81 | return entry |
| 82 | return None |
| 83 | return latest |
| 84 | |
| 85 | |
| 86 | async def drive(app, n: int) -> list[float]: |
| 87 | times = [] |
| 88 | for _ in range(n): |
| 89 | done = False |
| 90 | |
| 91 | async def receive(): |
| 92 | nonlocal done |
| 93 | if not done: |
| 94 | done = True |
| 95 | return {"type": "http.request", "body": BODY, "more_body": False} |
| 96 | await asyncio.sleep(3600) |
| 97 | |
| 98 | async def send(_m): pass |
| 99 | scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "POST", "scheme": "http", |
| 100 | "path": "/collections/bench_log/records", "raw_path": b"/collections/bench_log/records", |
| 101 | "query_string": b"", "root_path": "", "server": ("127.0.0.1", 1), "client": ("127.0.0.1", 5555), |
| 102 | "headers": [(b"authorization", b"Token benchtoken"), (b"content-type", b"application/json"), |
| 103 | (b"host", b"x"), (b"content-length", str(len(BODY)).encode())]} |
| 104 | t = time.perf_counter() |
| 105 | await app(scope, receive, send) |
| 106 | times.append((time.perf_counter() - t) * 1000) |
| 107 | return times |
| 108 | |
| 109 | |
| 110 | def main() -> int: |
| 111 | ap = argparse.ArgumentParser() |
| 112 | ap.add_argument("--warm", type=int, default=1300) |
| 113 | ap.add_argument("--measure", type=int, default=200) |
| 114 | args = ap.parse_args() |
| 115 | variant = os.environ.get("VARIANT") |
| 116 | if variant is None: # parent: run each variant in a fresh process so state never leaks between them |
| 117 | print(f"{'variant':<34} {'median ms/create':>17} {'p95':>8} {'vs original':>11}") |
| 118 | base = None |
| 119 | for v in ("original", "+coerce", "+coerce +tail-lookup", "+coerce +tail-lookup +memo-json"): |
| 120 | out = subprocess.run([sys.executable, __file__, "--warm", str(args.warm), "--measure", str(args.measure)], |
| 121 | env={**os.environ, "VARIANT": v}, capture_output=True, text=True) |
| 122 | if out.returncode: |
| 123 | print(out.stderr[-600:]); return 1 |
| 124 | med, p95 = (float(x) for x in out.stdout.split()) |
| 125 | base = base or med |
| 126 | print(f"{v:<34} {med:>17.2f} {p95:>8.2f} {base / med:>10.1f}x", flush=True) |
| 127 | return 0 |
| 128 | |
| 129 | setup() |
| 130 | sys.path.insert(0, str(REPO)) |
| 131 | import object_events, object_record_changes, object_server, object_state |
| 132 | if "+coerce" in variant: |
| 133 | orig = object_state._coerce_value |
| 134 | def coerce(value): |
| 135 | if value[:1] in ('{', '[', '"'): |
| 136 | return value |
| 137 | return orig(value) |
| 138 | object_state._coerce_value = coerce |
| 139 | if "+tail-lookup" in variant: |
| 140 | latest = tail_lookup(object_record_changes, json) |
| 141 | def record_change_for_publish(collection, record_id): |
| 142 | try: |
| 143 | return latest(collection, record_id, object_server._data_dir()) |
| 144 | except (OSError, ValueError): |
| 145 | return None |
| 146 | object_server._record_change_for_publish = record_change_for_publish |
| 147 | if "+memo-json" in variant: |
| 148 | object_events._load_json_object = functools.lru_cache(maxsize=8192)(object_events._load_json_object) |
| 149 | |
| 150 | async def go(): |
| 151 | await drive(object_server.app, args.warm) |
| 152 | t = await drive(object_server.app, args.measure) |
| 153 | t.sort() |
| 154 | print(statistics.median(t), t[int(len(t) * 0.95) - 1]) |
| 155 | asyncio.run(go()) |
| 156 | return 0 |
| 157 | |
| 158 | |
| 159 | if __name__ == "__main__": |
| 160 | raise SystemExit(main()) |