Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 41 minutes ago History
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
3what would each candidate fix buy?
4
5Drives object_server.app in-process (no sockets) with POST creates against a
6seeded 10k-row append collection, to steady state (the events log reaches its
71000-row cap), then times more creates. Variants are applied by monkeypatching
8THIS 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"""
23from __future__ import annotations
24
25import argparse
26import asyncio
27import functools
28import json
29import os
30import statistics
31import subprocess
32import sys
33import tempfile
34import time
35from pathlib import Path
36
37REPO = Path(__file__).resolve().parents[3]
38HERE = Path(__file__).resolve().parent
39BODY = json.dumps({"title": "t", "qty": "1", "status": "open", "owner": "o", "note": "n"}).encode()
40
41
42def 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
52def 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
86async 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
110def 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
159if __name__ == "__main__":
160 raise SystemExit(main())