# /// script
# requires-python = ">=3.10"
# ///
# Copyright (c) 2026 Aayush Sharma · SPDX-License-Identifier: MIT
# https://thedataengineering.com/lab-code/LICENSE.txt
"""What does fsync really cost on your machine?

200-byte appends with no sync, with fsync after each, and (on macOS) with
F_FULLFSYNC, which also flushes the drive's own cache. The ratio is your
durability tax.
"""
import argparse, json, os, platform, tempfile, time

p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("--writes", type=int, default=2000, help="Appends per variant.")
p.add_argument("--path", default=os.path.join(tempfile.gettempdir(), "fsync-lab.log"), help="Log file (put it on the drive to test).")
p.add_argument("--json", help="Also write the results to this JSON file.")
args = p.parse_args()

def bench(mode):
    fd = os.open(args.path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
    rec = b"x" * 200
    t0 = time.perf_counter()
    for _ in range(args.writes):
        os.write(fd, rec)
        if mode == "fsync": os.fsync(fd)
        elif mode == "F_FULLFSYNC":
            import fcntl; fcntl.fcntl(fd, fcntl.F_FULLFSYNC)
    dt = time.perf_counter() - t0
    os.close(fd)
    return dt / args.writes * 1e6

modes = ["no sync", "fsync"] + (["F_FULLFSYNC"] if platform.system() == "Darwin" else [])
rows = [{"mode": m, "us_per_write": bench(m)} for m in modes]
base = rows[0]["us_per_write"]
for r in rows:
    r["x_no_sync"] = r["us_per_write"] / base
    print(f"{r['mode']:<12} {r['us_per_write']:9.1f} µs per write   ({r['x_no_sync']:7.0f}x no sync)")

if args.json:
    with open(args.json, "w") as f:
        json.dump({"tables": {"modes": rows}}, f)
