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.
committed_prefix.py · 6.5 KB · 166 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """Experiment: faster replacements for object_records._committed_prefix_len. |
| 3 | |
| 4 | _committed_prefix_len is a pure-Python, one-character-at-a-time loop, and |
| 5 | _repair_torn_tail runs it over the WHOLE records.tsv on every append-mode |
| 6 | write whenever the id->offset sidecar cache is not warm (which, for any |
| 7 | collection under DBBASIC_RECORDS_CACHE_MAX_ROWS, is the usual case). |
| 8 | |
| 9 | Candidates, all returning the same thing (the length of the prefix that ends |
| 10 | at the last "\\n" outside a quoted field): |
| 11 | |
| 12 | original the repo's loop, over str |
| 13 | parity pure Python on bytes: the loop's quote state is just "is the |
| 14 | number of '"' seen so far odd?" ('""' inside a quote is two |
| 15 | toggles = no change), so rfind('\\n') + bytes.count('"') run at C |
| 16 | speed with no Rust at all |
| 17 | rust dbbasic_storage.committed_prefix_len (PyO3), if built |
| 18 | c c/dbbasic_storage_c (plain C extension), if built: the same |
| 19 | forward state machine as rust, and the parity idea in C |
| 20 | |
| 21 | python experiments/committed_prefix.py [--rows 100000] [--fuzz 300000] |
| 22 | |
| 23 | Nothing here is imported by the server; it only measures and cross-checks. |
| 24 | """ |
| 25 | from __future__ import annotations |
| 26 | |
| 27 | import argparse |
| 28 | import random |
| 29 | import sys |
| 30 | import time |
| 31 | from pathlib import Path |
| 32 | |
| 33 | REPO = Path(__file__).resolve().parents[3] |
| 34 | sys.path.insert(0, str(REPO)) |
| 35 | sys.path.insert(0, str(Path(__file__).resolve().parents[1])) |
| 36 | |
| 37 | import object_records # noqa: E402 |
| 38 | |
| 39 | current = object_records._committed_prefix_len # what the server runs now (the parity fix, on str) |
| 40 | |
| 41 | |
| 42 | def _load_original(): |
| 43 | """The per-character loop this all started from, straight from git HEAD (the working tree has the fix).""" |
| 44 | import importlib.util |
| 45 | import subprocess |
| 46 | import tempfile |
| 47 | src = subprocess.run(["git", "show", "HEAD:object_records.py"], cwd=REPO, capture_output=True, text=True, check=True).stdout |
| 48 | f = Path(tempfile.mkdtemp()) / "object_records_head.py" |
| 49 | f.write_text(src) |
| 50 | spec = importlib.util.spec_from_file_location("object_records_head", f) |
| 51 | mod = importlib.util.module_from_spec(spec) |
| 52 | spec.loader.exec_module(mod) |
| 53 | return mod._committed_prefix_len |
| 54 | |
| 55 | |
| 56 | original = _load_original() |
| 57 | |
| 58 | |
| 59 | def parity_bytes(data: bytes) -> int: |
| 60 | """Byte offset just past the last newline that sits outside a quoted |
| 61 | field. O(n) total: quotes are counted once per segment, never twice.""" |
| 62 | tail_quotes = 0 # quotes in data[end:] |
| 63 | total = data.count(b'"') |
| 64 | end = len(data) |
| 65 | while True: |
| 66 | i = data.rfind(b"\n", 0, end) |
| 67 | if i < 0: |
| 68 | return 0 |
| 69 | tail_quotes += data.count(b'"', i + 1, end) |
| 70 | if (total - tail_quotes) % 2 == 0: # even quotes before i: not inside a field |
| 71 | return i + 1 |
| 72 | end = i |
| 73 | |
| 74 | |
| 75 | try: |
| 76 | import dbbasic_storage # built by: maturin develop (see rust/dbbasic_storage) |
| 77 | rust_bytes = dbbasic_storage.committed_prefix_len |
| 78 | except ImportError: |
| 79 | rust_bytes = None |
| 80 | |
| 81 | |
| 82 | try: |
| 83 | sys.path.insert(0, str(REPO / "c" / "dbbasic_storage_c" / "build")) |
| 84 | import dbbasic_storage_c # built by: c/dbbasic_storage_c/build.sh |
| 85 | c_parity, c_forward = dbbasic_storage_c.committed_prefix_len, dbbasic_storage_c.committed_prefix_len_forward |
| 86 | except ImportError: |
| 87 | c_parity = c_forward = None |
| 88 | |
| 89 | |
| 90 | def char_to_byte(text: str, k: int) -> int: |
| 91 | return len(text[:k].encode("utf-8", errors="surrogateescape")) |
| 92 | |
| 93 | |
| 94 | def fuzz(n: int) -> int: |
| 95 | rng = random.Random(2026) |
| 96 | alphabet = ['a', 'b', '\t', '\n', '\n', '"', '"', 'é', '🚀', '\r', ' '] |
| 97 | bad = 0 |
| 98 | for _ in range(n): |
| 99 | text = "".join(rng.choice(alphabet) for _ in range(rng.randrange(0, 40))) |
| 100 | want = char_to_byte(text, original(text)) |
| 101 | data = text.encode("utf-8") |
| 102 | got = {"parity": parity_bytes(data), "current": char_to_byte(text, current(text))} |
| 103 | if rust_bytes: |
| 104 | got["rust"] = rust_bytes(data) |
| 105 | if c_parity: |
| 106 | got["c parity"] = c_parity(data) |
| 107 | got["c forward"] = c_forward(data) |
| 108 | for name, v in got.items(): |
| 109 | if v != want: |
| 110 | bad += 1 |
| 111 | if bad <= 5: |
| 112 | print(f"MISMATCH {name}: text={text!r} want={want} got={v}") |
| 113 | return bad |
| 114 | |
| 115 | |
| 116 | def best_of(fn, arg, repeat=5) -> float: |
| 117 | best = 1e9 |
| 118 | for _ in range(repeat): |
| 119 | t = time.perf_counter() |
| 120 | fn(arg) |
| 121 | best = min(best, time.perf_counter() - t) |
| 122 | return best * 1000 |
| 123 | |
| 124 | |
| 125 | def main() -> int: |
| 126 | ap = argparse.ArgumentParser() |
| 127 | ap.add_argument("--rows", type=int, default=100000) |
| 128 | ap.add_argument("--fuzz", type=int, default=300000) |
| 129 | args = ap.parse_args() |
| 130 | |
| 131 | print(f"fuzz: {args.fuzz} random strings (quotes, newlines, multi-byte, emoji, CR) ...", flush=True) |
| 132 | bad = fuzz(args.fuzz) |
| 133 | print("fuzz result:", "ALL IDENTICAL to the original" if bad == 0 else f"{bad} MISMATCHES") |
| 134 | if bad: |
| 135 | return 1 |
| 136 | |
| 137 | # A realistic file: the same rows the benchmark seeds, plus quoted multi-line cells. |
| 138 | import storage_bench |
| 139 | import tempfile |
| 140 | d = Path(tempfile.mkdtemp()) |
| 141 | p = storage_bench.seed(d, "bench", args.rows, "append") |
| 142 | with p.open("a", newline="") as f: |
| 143 | f.write('\tq1\t"has a ""quote"" and\na newline"\t1\topen\to\tn\n') |
| 144 | data = p.read_bytes() |
| 145 | text = data.decode("utf-8", errors="surrogateescape") |
| 146 | want = char_to_byte(text, original(text)) |
| 147 | print(f"\nfile: {len(data)/1e6:.1f} MB, {args.rows} rows (+1 multi-line quoted row)") |
| 148 | rows = [("original (git HEAD: python loop, str)", best_of(original, text, 3), char_to_byte(text, original(text))), |
| 149 | ("python fix in the server (parity, str)", best_of(current, text, 20), char_to_byte(text, current(text))), |
| 150 | ("python parity on bytes", best_of(parity_bytes, data, 20), parity_bytes(data))] |
| 151 | if rust_bytes: |
| 152 | rows.append(("rust (pyo3, memchr2 forward)", best_of(rust_bytes, data, 20), rust_bytes(data))) |
| 153 | if c_parity: |
| 154 | rows.append(("c (forward state machine)", best_of(c_forward, data, 20), c_forward(data))) |
| 155 | rows.append(("c (parity, walk back)", best_of(c_parity, data, 20), c_parity(data))) |
| 156 | base = rows[0][1] |
| 157 | for name, ms, got in rows: |
| 158 | print(f" {name:<40} {ms:9.3f} ms {base / ms:8.1f}x {'ok' if got == want else 'WRONG ANSWER'}") |
| 159 | print("\n(the original also pays a decode before and an encode after, which the byte versions skip)") |
| 160 | t = time.perf_counter(); text2 = data.decode("utf-8", errors="surrogateescape"); char_to_byte(text2, original(text2)); full = (time.perf_counter() - t) * 1000 |
| 161 | print(f" whole original path incl. decode/encode: {full:.1f} ms") |
| 162 | return 0 |
| 163 | |
| 164 | |
| 165 | if __name__ == "__main__": |
| 166 | raise SystemExit(main()) |