forked from mtusi2026/mtusi2026lab2
157 lines
6.0 KiB
Python
157 lines
6.0 KiB
Python
"""Compare keyset and OFFSET on uneven histories, then verify a logical restore."""
|
|
|
|
import argparse
|
|
import json
|
|
import math
|
|
import shlex
|
|
import subprocess
|
|
import time
|
|
from pathlib import Path
|
|
from uuid import uuid4
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
SAMPLE_CHATS = (1, 2, 10, 100)
|
|
SAMPLE_ROWS = (1, 50001, 119999, 120000)
|
|
REPEATS = 5
|
|
|
|
|
|
def db(*args, content=None):
|
|
result = subprocess.run(
|
|
["docker", "compose", "exec", "-T", "db", *args],
|
|
cwd=ROOT, input=content, capture_output=True, check=True, timeout=90,
|
|
)
|
|
return result.stdout
|
|
|
|
|
|
def sql(database, text):
|
|
return db("psql", "-X", "-qAt", "-v", "ON_ERROR_STOP=1", "-U", "messenger",
|
|
"-d", database, content=text.encode()).decode().strip()
|
|
|
|
|
|
def explain(database, statement):
|
|
plan = sql(database, "EXPLAIN (ANALYZE, BUFFERS, WAL, FORMAT JSON) " + statement)
|
|
return json.loads(plan)[0]
|
|
|
|
|
|
def time_call(action):
|
|
started = time.perf_counter()
|
|
value = action()
|
|
return value, round(1000 * (time.perf_counter() - started), 3)
|
|
|
|
|
|
def signature(database):
|
|
groups = sql(database, "SELECT chat_id, count(*) FROM history GROUP BY 1 ORDER BY 1;")
|
|
ids = ",".join(map(str, SAMPLE_ROWS))
|
|
rows = sql(database, f"SELECT id, chat_id, md5(body) FROM history WHERE id IN ({ids}) ORDER BY id;")
|
|
return {"per_chat": groups.splitlines(), "sample_rows": rows.splitlines(),
|
|
"count": int(sql(database, "SELECT count(*) FROM history;"))}
|
|
|
|
|
|
def seed(database):
|
|
sql(database, """
|
|
CREATE TABLE history (
|
|
id bigint PRIMARY KEY, chat_id int NOT NULL,
|
|
created_at timestamptz NOT NULL, body text NOT NULL
|
|
);
|
|
INSERT INTO history
|
|
SELECT n,
|
|
CASE WHEN n <= 72000 THEN 1 WHEN n <= 90000 THEN 2 ELSE 3 + n % 98 END,
|
|
timestamptz '2025-01-01T00:00:00Z' + n * interval '1 millisecond',
|
|
repeat(md5(n::text), 4)
|
|
FROM generate_series(1,120000) AS n;
|
|
ANALYZE history;
|
|
""")
|
|
|
|
|
|
def sample_plan(database, statement):
|
|
explain(database, statement)
|
|
return [explain(database, statement) for _ in range(REPEATS)]
|
|
|
|
|
|
def read_bench(database):
|
|
measurements = {}
|
|
for chat_id in SAMPLE_CHATS:
|
|
order = "ORDER BY created_at, id"
|
|
where = f"FROM history WHERE chat_id = {chat_id}"
|
|
count = int(sql(database, f"SELECT count(*) {where};"))
|
|
offset = max(1, math.floor(count * 0.8))
|
|
timestamp, position = sql(
|
|
database, f"SELECT created_at, id {where} {order} OFFSET {offset - 1} LIMIT 1;"
|
|
).split("|")
|
|
seek = f"AND (created_at,id) > ('{timestamp}'::timestamptz,{int(position)})"
|
|
statements = {
|
|
"offset": f"SELECT * {where} {order} OFFSET {offset} LIMIT 50;",
|
|
"keyset": f"SELECT * {where} {seek} {order} LIMIT 50;",
|
|
}
|
|
if sql(database, statements["offset"]) != sql(database, statements["keyset"]):
|
|
raise AssertionError("offset and keyset differ on an unchanged history")
|
|
measurements[str(chat_id)] = {"rows": count, "offset": offset, "execution": {
|
|
name: sample_plan(database, statement) for name, statement in statements.items()
|
|
}}
|
|
return measurements
|
|
|
|
|
|
def write_bench(database):
|
|
# Roll back so all measurements use exactly the same logical data.
|
|
statement = """
|
|
BEGIN;
|
|
EXPLAIN (ANALYZE, BUFFERS, WAL, FORMAT JSON)
|
|
INSERT INTO history
|
|
SELECT 120000+n, 1, clock_timestamp(), repeat(md5(n::text),4)
|
|
FROM generate_series(1,2000) n;
|
|
ROLLBACK;
|
|
"""
|
|
return [json.loads(sql(database, statement))[0] for _ in range(REPEATS)]
|
|
|
|
|
|
def run():
|
|
suffix = uuid4().hex[:10]
|
|
source, target = f"hist_lab2_{suffix}", f"restore_lab2_{suffix}"
|
|
created = []
|
|
try:
|
|
for database in (source, target):
|
|
db("createdb", "-U", "messenger", database)
|
|
created.append(database)
|
|
seed(source)
|
|
baseline = {"read": read_bench(source), "write": write_bench(source)}
|
|
sql(source, "CREATE INDEX history_page ON history(chat_id, created_at, id); ANALYZE history;")
|
|
indexed = {"read": read_bench(source), "write": write_bench(source)}
|
|
original = signature(source)
|
|
dump, backup_ms = time_call(lambda: db("pg_dump", "-U", "messenger", "-Fc", source))
|
|
sql(source, "INSERT INTO history VALUES (120001,1,clock_timestamp(),'post-backup marker');")
|
|
_, restore_ms = time_call(lambda: db(
|
|
"pg_restore", "--exit-on-error", "-U", "messenger", "-d", target, content=dump
|
|
))
|
|
restored = signature(target)
|
|
if original != restored or int(sql(target, "SELECT count(*) FROM history WHERE id=120001;")) != 0:
|
|
raise AssertionError("restore differs from the backup snapshot")
|
|
return {
|
|
"hypothesis": "Composite index bounds keyset read work at the cost of extra write I/O",
|
|
"server": sql(source, "SHOW server_version;"), "repeat_count": REPEATS,
|
|
"baseline_primary_key_only": baseline, "composite_index": indexed,
|
|
"backup": {"backup_ms": backup_ms, "restore_ms": restore_ms, "bytes": len(dump),
|
|
"same_counts_and_samples": True, "snapshot": restored,
|
|
"post_backup_marker_restored": False,
|
|
"source_rows_after_marker": signature(source)["count"]},
|
|
}
|
|
finally:
|
|
for database in reversed(created):
|
|
db("dropdb", "-U", "messenger", database)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--output", type=Path, default=ROOT / "evidence" / "history-experiment.json")
|
|
args = parser.parse_args()
|
|
try:
|
|
result = run()
|
|
except subprocess.CalledProcessError as exc:
|
|
raise SystemExit(f"Failed: {shlex.join(exc.cmd[3:])}\n{exc.stderr.decode(errors='replace')}") from None
|
|
args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
|
|
print(f"Observed {result['backup']['snapshot']['count']} restored rows. Raw plans: {args.output}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|