File size: 19,719 Bytes
f8975ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#!/usr/bin/env python3
"""Run the six durability experiments on a Linux machine and write the raw results.

  run_experiments.py --go ./dspike-go --rust ./dspike-rust --tools ./tools --out ./results [--only 01,03]

Each experiment has a pass bar, written here before it runs, and writes results/NN-name/result.json plus the
raw output it judged. Nothing outside the scratch directory and the user's own systemd units is touched.
Experiment 04 needs `yjob` and its unit template installed for the user (tools/yjob, tools/yjob@.service).

These experiments kill processes. They do not cut the power: what survives a power cut depends on the
file system and the drive as well, and is not measured here.
"""
from __future__ import annotations

import argparse
import json
import os
import platform
import random
import re
import shutil
import signal
import sqlite3
import statistics
import subprocess
import sys
import tempfile
import time
from pathlib import Path

LANGS = ("go", "rust")
WRITER = '''
import sqlite3, sys, time
c = sqlite3.connect(sys.argv[1]); c.execute("PRAGMA journal_mode=WAL"); c.execute("create table if not exists t(x)")
import os
while not os.path.exists(sys.argv[2]):      # until told to stop: about a hundred commits a second, so the file stays small
    c.executemany("insert into t values(?)", [(i,) for i in range(500)]); c.commit(); time.sleep(0.005)
'''


def sh(cmd: list[str] | str, **kw) -> subprocess.CompletedProcess:
    return subprocess.run(cmd, shell=isinstance(cmd, str), capture_output=True, text=True, **kw)


def save(out: Path, name: str, bar: str, verdict: str, data: dict, raw: dict[str, str] | None = None) -> None:
    d = out / name
    d.mkdir(parents=True, exist_ok=True)
    for fname, text in (raw or {}).items():
        (d / fname).write_text(text)
    doc = {"experiment": name, "pass_bar": bar, "verdict": verdict, "ran": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), **data}
    (d / "result.json").write_text(json.dumps(doc, indent=1) + "\n")
    print(f"{name}: {verdict}")


def calls(trace: str) -> list[str]:
    """The sync and rename calls of a strace file, in order, as short words."""
    got = []
    for line in trace.splitlines():
        m = re.match(r"^\d+\s+(fsync|fdatasync|rename|renameat|renameat2)\(", line)
        if m:
            got.append("rename" if m.group(1).startswith("rename") else m.group(1))
    return got


# ---- 01 ---------------------------------------------------------------------------------------------------
def exp01(bins: dict[str, str], work: Path, out: Path) -> None:
    bar = ("append: the file is synced (fsync or fdatasync) before the program exits. replace: the temporary file is "
           "synced, then renamed over the target, then the directory is synced, in that order. Both languages.")
    data, raw, ok = {}, {}, True
    for lang in LANGS:
        ta, tr = work / f"trace.{lang}.append", work / f"trace.{lang}.replace"
        sh(["strace", "-f", "-e", "trace=fsync,fdatasync,rename,renameat,renameat2", "-o", str(ta), bins[lang], "append", str(work / f"log.{lang}"), "a line"])
        sh(["strace", "-f", "-e", "trace=fsync,fdatasync,rename,renameat,renameat2", "-o", str(tr), bins[lang], "replace", str(work / f"state.{lang}.json"), '{"v":1}'])
        a, r = calls(ta.read_text()), calls(tr.read_text())
        good = bool(a) and a[-1] in ("fsync", "fdatasync") and r[-3:] == ["fsync", "rename", "fsync"]
        ok &= good
        data[lang] = {"append": a, "replace": r, "meets_bar": good}
        raw[f"strace-{lang}-append.txt"] = re.sub(str(work), "SCRATCH", ta.read_text())
        raw[f"strace-{lang}-replace.txt"] = re.sub(str(work), "SCRATCH", tr.read_text())
    save(out, "01-system-calls", bar, "pass" if ok else "fail", {"calls": data}, raw)


# ---- 02 ---------------------------------------------------------------------------------------------------
def judge_copy(path: Path) -> tuple[str, int]:
    try:
        c = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
        if c.execute("PRAGMA integrity_check").fetchone()[0] != "ok":
            return "fails the integrity check", 0
        n = c.execute("select count(*) from t").fetchone()[0]
        c.close()
        return ("whole" if n % 500 == 0 else "holds part of a transaction"), n
    except sqlite3.Error as e:
        return f"does not open ({str(e)[:40]})", 0


def exp02(bins: dict[str, str], work: Path, out: Path, rounds: int = 50) -> None:
    bar = (f"All {rounds} copies taken by each program while another process commits batches of 500 rows: open, pass "
           "integrity_check, and hold only whole batches; and the writer is alive and committing through every series. "
           "The two plain file copies are controls and have no bar.")
    live = work / "live.db"
    stop = work / "stop-writer"
    writer = subprocess.Popen([sys.executable, "-c", WRITER, str(live), str(stop)])
    time.sleep(1.5)
    data: dict[str, dict] = {}
    ok = True

    def live_rows() -> int:
        c = sqlite3.connect(f"file:{live}?mode=ro", uri=True)
        n = c.execute("select count(*) from t").fetchone()[0]
        c.close()
        return n

    def series(name: str, make) -> None:
        nonlocal ok
        kinds: dict[str, int] = {}
        behind = []
        first = live_rows()
        for i in range(rounds):
            before = live_rows()
            copy = work / f"copy.{name}.db"
            for f in (copy, Path(str(copy) + "-wal"), Path(str(copy) + "-shm")):
                f.unlink(missing_ok=True)
            make(copy)
            kind, n = judge_copy(copy)
            kinds[kind] = kinds.get(kind, 0) + 1
            if kind == "whole":
                behind.append(max(0, before - n))
        alive = writer.poll() is None
        ok &= alive                                    # a series taken after the writer died proves nothing
        data[name] = {"copies": rounds, "outcomes": kinds, "writer_alive_throughout": alive,
                      "rows_committed_during_the_series": live_rows() - first,
                      "committed_rows_missing_from_whole_copies_median": int(statistics.median(behind)) if behind else None,
                      "committed_rows_missing_max": max(behind) if behind else None}
        if name in LANGS:
            ok &= kinds == {"whole": rounds}

    for lang in LANGS:
        series(lang, lambda copy, b=bins[lang]: sh([b, "stage", str(live), str(copy)]))
    series("control-cp-main-file-only", lambda copy: shutil.copyfile(live, copy))

    def cp_both(copy: Path) -> None:
        shutil.copyfile(live, copy)
        time.sleep(0.002)
        if Path(str(live) + "-wal").exists():
            shutil.copyfile(str(live) + "-wal", str(copy) + "-wal")
    series("control-cp-main-file-then-log", cp_both)
    stop.write_text("stop")
    writer.wait(timeout=30)
    save(out, "02-copy-under-a-writer", bar, "pass" if ok else "fail", {"series": data, "rows_committed_at_the_end": live_rows()})


# ---- 03 ---------------------------------------------------------------------------------------------------
def exp03(bins: dict[str, str], work: Path, out: Path, rounds: int = 500) -> None:
    bar = (f"In {rounds} rounds for each program, a replace of a 100 kB file killed with SIGKILL after a random delay never "
           "leaves the target missing, empty or half written: it always holds the old or the new content, whole. "
           "Temporary files left behind are counted, not judged. The in-place writer is a control and has no bar.")
    pad = "x" * 100_000
    data: dict[str, dict] = {}
    ok = True
    rng = random.Random(20261003)

    def whole(path: Path) -> bool:
        try:
            return len(json.loads(path.read_text())["pad"]) == len(pad)
        except (OSError, ValueError, KeyError):
            return False

    for lang in LANGS:
        target = work / f"kill.{lang}.json"
        target.write_text(json.dumps({"v": 0, "pad": pad}))
        broken = finished = 0
        for i in range(1, rounds + 1):
            p = subprocess.Popen([bins[lang], "replace", str(target), json.dumps({"v": i, "pad": pad})])
            time.sleep(rng.uniform(0, 0.004))
            p.kill()
            finished += p.wait() == 0
            broken += not whole(target)
        left = len(list(work.glob(f"kill.{lang}.json.tmp*")))
        data[lang] = {"rounds": rounds, "target_broken": broken, "replaces_that_finished_before_the_kill": finished, "temporary_files_left": left}
        ok &= broken == 0
    # control: the same content written in place, synced but not atomic
    src, target = work / "payload.json", work / "kill.inplace.json"
    src.write_text(json.dumps({"v": 1, "pad": pad}))
    target.write_text(src.read_text())
    broken = 0
    for _ in range(rounds):
        p = subprocess.Popen(["dd", f"if={src}", f"of={target}", "bs=1024", "oflag=dsync", "status=none"])
        time.sleep(rng.uniform(0, 0.02))
        p.kill()
        p.wait()
        broken += not whole(target)
        if not whole(target):
            target.write_text(src.read_text())
    data["control-write-in-place-with-sync"] = {"rounds": rounds, "target_broken": broken}
    save(out, "03-kill-during-replace", bar, "pass" if ok else "fail", {"series": data, "payload_bytes": len(pad)})


# ---- 04 ---------------------------------------------------------------------------------------------------
def journal(unit: str, since: float) -> list[str]:
    r = sh(["journalctl", "--user", "-u", unit, "--since", f"@{int(since)}", "--no-pager", "-o", "json"])
    lines = []
    for raw in r.stdout.splitlines():
        try:
            d = json.loads(raw)
            t = time.strftime("%H:%M:%S", time.gmtime(int(d["__REALTIME_TIMESTAMP"]) / 1e6))
            lines.append(f"{t} {d.get('MESSAGE', '')}")
        except (ValueError, KeyError):
            continue
    return lines


def exp04(work: Path, out: Path, yjob: str) -> None:
    bar = ("A job whose command fails on its first run is run again without anyone asking, finishes, and its unit is then "
           "disabled. A job that is stopped while running stays enabled, so the next boot starts it. A real power-off "
           "is not part of this run.")
    jobs = Path.home() / "runbook" / "jobs"
    started = time.time()
    script = work / "fails-once.sh"
    script.write_text(f"#!/usr/bin/env bash\nf={work}/count; n=$(( $(cat $f 2>/dev/null || echo 0) + 1 )); echo $n > $f\n"
                      '[ $n -ge 2 ] || { echo "attempt $n: failing on purpose"; exit 7; }\necho "attempt $n: working"; sleep 3; echo "attempt $n: done"\n')
    script.chmod(0o755)
    a, b = "exp-fails-once", "exp-stopped"
    for n in (a, b):
        sh([yjob, "cancel", n])
    sh([yjob, "add", "--quiet", a, "--", str(script)])
    deadline = time.time() + 400
    while (jobs / f"{a}.sh").exists() and time.time() < deadline:
        time.sleep(5)
    log_a = journal(f"yjob@{a}.service", started)
    finished = not (jobs / f"{a}.sh").exists()
    took = round(time.time() - started)
    enabled_after = sh(["systemctl", "--user", "is-enabled", f"yjob@{a}.service"]).stdout.strip()
    attempts = int((work / "count").read_text().strip()) if (work / "count").exists() else 0
    long = work / "long.sh"
    long.write_text("#!/usr/bin/env bash\necho started; sleep 600\n")
    long.chmod(0o755)
    t2 = time.time()
    sh([yjob, "add", "--quiet", b, "--", str(long)])
    time.sleep(3)
    sh(["systemctl", "--user", "stop", f"yjob@{b}.service"])
    time.sleep(2)
    stopped_enabled = sh(["systemctl", "--user", "is-enabled", f"yjob@{b}.service"]).stdout.strip()
    stopped_active = sh(["systemctl", "--user", "is-active", f"yjob@{b}.service"]).stdout.strip()
    still_queued = (jobs / f"{b}.sh").exists()
    log_b = journal(f"yjob@{b}.service", t2)
    sh([yjob, "cancel", b])
    ok = finished and attempts == 2 and enabled_after == "disabled" and stopped_enabled == "enabled" and still_queued
    save(out, "04-durable-job", bar, "pass" if ok else "fail", {
        "fails_once": {"attempts": attempts, "finished": finished, "unit_after_success": enabled_after, "seconds_until_finished": took,
                       "retry_delay_of_the_unit_seconds": 120},
        "stopped": {"unit_after_stop": stopped_enabled, "state_after_stop": stopped_active, "still_queued": still_queued},
        "not_run": "a job continuing after a real power-off of the machine"},
        {"journal-fails-once.txt": "\n".join(log_a) + "\n", "journal-stopped.txt": "\n".join(log_b) + "\n"})


# ---- 05 ---------------------------------------------------------------------------------------------------
FAKE = '''
import http.server, sys, time
T0 = time.time(); BUSY = float(sys.argv[2])
class H(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        n = 1 if time.time() - T0 < BUSY else 0
        body = f"yllm_queue_depth {n}\\nyllm_slots_in_use {n}\\nyllm_embed_slots_in_use 0\\n".encode()
        self.send_response(200); self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
    def log_message(self, *a): pass
http.server.HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
'''


def exp05(work: Path, out: Path, steps: str) -> None:
    bar = ("drain: with a service that is busy for 7 s it returns within 3 s of the service becoming idle, exit 0; with a "
           "service still busy when the limit of 5 s passes it stops at the limit, exit 1; with no service answering it "
           "does not wait. checkpoint: after a writer exits without closing its database, the write-ahead log is "
           "emptied and every committed row is in the main file.")
    port = 18999
    cases = {}

    def drain(busy: float | None, wait: int) -> dict:
        srv = subprocess.Popen([sys.executable, "-c", FAKE, str(port), str(busy)]) if busy is not None else None
        time.sleep(1.0)
        t = time.time()
        r = sh([steps, "drain"], env={**os.environ, "GATEWAY": f"http://127.0.0.1:{port}", "WAIT": str(wait)})
        took = round(time.time() - t, 1)
        if srv:
            srv.kill()
            srv.wait()
        time.sleep(0.3)
        return {"exit": r.returncode, "seconds": took, "said": r.stdout.strip()}

    cases["busy 7 s then idle, limit 30 s"] = drain(7, 30)
    cases["busy past the limit of 5 s"] = drain(60, 5)
    cases["no service answering"] = drain(None, 5)
    db = work / "unclean.db"
    sh([sys.executable, "-c", f'''
import sqlite3, os
c = sqlite3.connect("{db}"); c.execute("PRAGMA journal_mode=WAL"); c.execute("PRAGMA wal_autocheckpoint=0")
c.execute("create table t(x)"); c.executemany("insert into t values(?)", [(i,) for i in range(20000)]); c.commit()
os._exit(0)
'''])
    wal_before = os.path.getsize(str(db) + "-wal") if os.path.exists(str(db) + "-wal") else 0
    main_before = os.path.getsize(db)
    r = sh([steps, "checkpoint"], env={**os.environ, "GATEWAY": "http://127.0.0.1:1", "DBS": f"{db} {work}/missing.db"})
    wal_after = os.path.getsize(str(db) + "-wal") if os.path.exists(str(db) + "-wal") else 0
    rows = sqlite3.connect(db).execute("select count(*) from t").fetchone()[0]
    cp = {"log_bytes_before": wal_before, "log_bytes_after": wal_after, "main_file_bytes_before": main_before,
          "main_file_bytes_after": os.path.getsize(db), "rows": rows, "said": re.sub(str(work), "SCRATCH", r.stdout.strip())}
    c1, c2, c3 = cases.values()
    ok = (c1["exit"] == 0 and 5 <= c1["seconds"] <= 10 and c2["exit"] == 1 and 4 <= c2["seconds"] <= 9 and c3["exit"] == 0
          and c3["seconds"] < 2 and wal_before > 0 and wal_after == 0 and rows == 20000)
    save(out, "05-drain-and-checkpoint", bar, "pass" if ok else "fail", {"drain": cases, "checkpoint": cp})


# ---- 06 ---------------------------------------------------------------------------------------------------
def exp06(work: Path, out: Path, stage: str) -> None:
    bar = ("A copy of a database whose writer holds an uncommitted row and whose changes are all still in the log: holds "
           "every committed row and not the uncommitted one, and passes quick_check. A file that is not a database is "
           "reported, exit 1, and leaves no file behind, not even a temporary one. A missing database is skipped.")
    live = work / "staged-live.db"
    w = sqlite3.connect(live)
    w.execute("PRAGMA journal_mode=WAL")
    w.execute("PRAGMA wal_autocheckpoint=0")
    w.execute("create table t(x)")
    w.executemany("insert into t values(?)", [(i,) for i in range(5000)])
    w.commit()
    w.execute("insert into t values(-1)")
    broken = work / "broken.db"
    broken.write_bytes(b"this is not a database, it only has the name" * 200)
    dest = work / "staged"
    r = sh([sys.executable, stage, str(dest), str(live), str(work / "missing.db"), str(broken)])
    files = sorted(p.name for p in dest.iterdir())
    copy = next((dest / f for f in files if f.endswith("staged-live.db")), None)
    rows = lowest = None
    check = ""
    if copy:
        c = sqlite3.connect(copy)
        rows, lowest = c.execute("select count(*), min(x) from t").fetchone()
        check = c.execute("PRAGMA quick_check").fetchone()[0]
    w.rollback()
    ok = r.returncode == 1 and len(files) == 1 and rows == 5000 and lowest == 0 and check == "ok"
    save(out, "06-consistent-sqlite-copy", bar, "pass" if ok else "fail", {
        "exit": r.returncode, "files_in_destination": len(files), "rows_in_copy": rows, "uncommitted_row_in_copy": lowest == -1,
        "quick_check": check, "log_bytes_of_the_live_database": os.path.getsize(str(live) + "-wal"),
        "reported": re.sub(str(work), "SCRATCH", r.stderr.strip())})


def environment(bins: dict[str, str]) -> dict:
    cpu = next((line.split(":", 1)[1].strip() for line in Path("/proc/cpuinfo").read_text().splitlines() if line.startswith("model name")), "")
    fs = sh("findmnt -no FSTYPE,OPTIONS -T .").stdout.strip()
    return {"kernel": platform.release(), "cpu": cpu, "file_system_of_the_scratch_directory": fs, "python_sqlite": sqlite3.sqlite_version,
            "systemd": sh("systemctl --version").stdout.splitlines()[0] if shutil.which("systemctl") else "",
            "binaries": {k: {"bytes": os.path.getsize(v)} for k, v in bins.items()}}


def main() -> int:
    ap = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0])
    ap.add_argument("--go", required=True)
    ap.add_argument("--rust", required=True)
    ap.add_argument("--tools", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--only", default="01,02,03,04,05,06")
    ap.add_argument("--yjob", default=str(Path.home() / "runbook/tools/yjob"))
    a = ap.parse_args()
    bins = {"go": os.path.abspath(a.go), "rust": os.path.abspath(a.rust)}
    out, tools = Path(a.out).resolve(), Path(a.tools).resolve()
    out.mkdir(parents=True, exist_ok=True)
    scratch_root = Path.home() / ".cache"
    scratch_root.mkdir(exist_ok=True)
    with tempfile.TemporaryDirectory(dir=scratch_root, prefix="durability-exp-") as tmp:
        work = Path(tmp)
        os.chdir(work)
        (out / "environment.json").write_text(json.dumps(environment(bins), indent=1) + "\n")
        only = set(a.only.split(","))
        if "01" in only:
            exp01(bins, work, out)
        if "02" in only:
            exp02(bins, work, out)
        if "03" in only:
            exp03(bins, work, out)
        if "04" in only:
            exp04(work, out, a.yjob)
        if "05" in only:
            exp05(work, out, str(tools / "quiesce-steps.sh"))
        if "06" in only:
            exp06(work, out, str(tools / "sqlite-stage.py"))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())