"""Weekly small measurements, 2026-11-25 (second run, folder 2026-11-25b). PostgreSQL 18.6 lab, port 5418."""
import os, sys, json, statistics, subprocess, time
sys.path.insert(0, os.path.expanduser("~/products/c13/minis"))
from lab import *
import lab

HERE = os.path.dirname(os.path.abspath(__file__))
setup(os.path.join(HERE, "results.json"))
start()
save_env()

TABLES = "w_a, w_b, w_s, w_z, w_cz, w_load, w_hot1, w_hot2, w_bl, w_ix, w_bool, w_j"


def sess(cmds):
    """Run several statements in ONE psql session; return stdout lines."""
    args = []
    for c in cmds:
        args += ["-c", c]
    p = subprocess.run(lab.BASE + args, capture_output=True, text=True)
    if p.returncode != 0:
        raise RuntimeError(p.stderr)
    return p.stdout.strip().splitlines()


def plan_json(sql, prefix_cmds=()):
    out = sess(list(prefix_cmds) + ["EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, FORMAT JSON) " + sql])
    k = out.index("[")
    return json.loads("\n".join(out[k:]))[0]


def nodes(p):
    yield p
    for c in p.get("Plans", []):
        yield from nodes(c)


def find(p, typ):
    return [n for n in nodes(p) if n["Node Type"] == typ]


def walltime(cmds, n=3):
    xs = []
    for _ in range(n):
        t = time.perf_counter(); sess(cmds); xs.append(round(time.perf_counter() - t, 3))
    return {"median_s": round(statistics.median(xs), 3), "runs_s": xs}


psql(f"DROP TABLE IF EXISTS {TABLES} CASCADE")

# 1. work_mem and hash join batches
psql("CREATE TABLE w_a (id int, v int); CREATE TABLE w_b (id int, w int);"
     "INSERT INTO w_a SELECT g, g%1000 FROM generate_series(1,2000000) g;"
     "INSERT INTO w_b SELECT g, g%777 FROM generate_series(1,2000000) g;"
     "VACUUM ANALYZE w_a; VACUUM ANALYZE w_b")
hj = {"rows_each": 2000000, "parallel": "max_parallel_workers_per_gather=0"}
qj = "SELECT count(*), sum(w_b.w) FROM w_a JOIN w_b USING (id)"
for wm in ["4MB", "64MB", "256MB"]:
    pre = ["SET max_parallel_workers_per_gather = 0", f"SET work_mem = '{wm}'"]
    xs = []
    for _ in range(4):
        j = plan_json(qj, pre); xs.append(j)
    xs = xs[1:]
    h = find(xs[-1]["Plan"], "Hash")
    hj[wm] = {"median_ms": round(statistics.median(x["Execution Time"] for x in xs), 3),
              "runs_ms": [round(x["Execution Time"], 3) for x in xs],
              "join_node": [n["Node Type"] for n in nodes(xs[-1]["Plan"]) if "Join" in n["Node Type"]],
              "hash_batches": h[0].get("Hash Batches") if h else None,
              "peak_memory_kb": h[0].get("Peak Memory Usage") if h else None,
              "temp_written_blocks": xs[-1]["Plan"].get("Temp Written Blocks", 0)}
save("work_mem_hashjoin", hj)
psql("DROP TABLE w_a, w_b")

# 2. generic plan with skewed data
psql("CREATE TABLE w_s (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, k int NOT NULL, pad text);"
     "INSERT INTO w_s (k, pad) SELECT CASE WHEN g % 2 = 0 THEN 0 ELSE 1 + g % 1000 END, repeat('x', 40) FROM generate_series(1,2000000) g;"
     "CREATE INDEX w_s_k ON w_s (k); VACUUM ANALYZE w_s")
gp = {"rows": 2000000, "common_value_rows": int(q1("select count(*) from w_s where k = 0")),
      "rare_value_rows": int(q1("select count(*) from w_s where k = 7"))}
prep = "PREPARE q(int) AS SELECT count(*), max(pad) FROM w_s WHERE k = $1"
for mode in ["auto", "force_custom_plan"]:
    res = []
    for _ in range(4):
        cmds = ["SET max_parallel_workers_per_gather = 0", f"SET plan_cache_mode = {mode}", prep] + \
               [f"EXECUTE q({v})" for v in (7, 8, 9, 10, 11, 12)]
        j = plan_json("EXECUTE q(0)", cmds)
        res.append(j)
    res = res[1:]
    gp[mode] = {"median_ms": round(statistics.median(x["Execution Time"] for x in res), 3),
                "runs_ms": [round(x["Execution Time"], 3) for x in res],
                "nodes": [n["Node Type"] for n in nodes(res[-1]["Plan"])],
                "plan_rows_estimate": [n.get("Plan Rows") for n in nodes(res[-1]["Plan"])]}
gp["rare_custom"] = runs("SELECT count(*), max(pad) FROM w_s WHERE k = 7", 3, "SET max_parallel_workers_per_gather = 0; ")
save("generic_plan_skew", gp)
psql("DROP TABLE w_s")

# 3. statistics target on a skewed column
psql("SELECT setseed(0.42); CREATE TABLE w_z (v int);"
     "INSERT INTO w_z SELECT floor(power(random(), 3) * 20000)::int FROM generate_series(1,2000000);"
     "ALTER TABLE w_z SET (autovacuum_enabled = false)")
# pick values by frequency rank
ranked = psql("SELECT v, count(*) FROM w_z GROUP BY v ORDER BY count(*) DESC, v").splitlines()
picks = {"rank_50": ranked[49], "rank_250": ranked[249], "rank_2000": ranked[1999]}
st = {"rows": 2000000, "distinct": len(ranked), "picks": {}}
for name, line in picks.items():
    v, c = line.split("|")
    st["picks"][name] = {"value": int(v), "actual": int(c)}
for target in [100, 1000]:
    psql(f"ALTER TABLE w_z ALTER COLUMN v SET STATISTICS {target}")
    st[str(target)] = {}
    for name, p in st["picks"].items():
        ests = []
        for _ in range(3):
            psql("ANALYZE w_z")
            j = json.loads(psql(f"EXPLAIN (FORMAT JSON) SELECT * FROM w_z WHERE v = {p['value']}"))[0]
            ests.append(j["Plan"]["Plan Rows"])
        st[str(target)][name] = ests
    st[str(target)]["mcv_count"] = int(q1("select coalesce(array_length(most_common_vals::text::int[],1),0) from pg_stats where tablename='w_z' and attname='v'"))
save("stats_target", st)
psql("DROP TABLE w_z")

# 4. extended statistics: city and zip
psql("CREATE TABLE w_cz (zip int, city int);"
     "INSERT INTO w_cz SELECT g % 10000, (g % 10000) / 100 FROM generate_series(1,1000000) g;"
     "ANALYZE w_cz")
qz = "SELECT * FROM w_cz WHERE city = 5 AND zip = 523"
ez = {"rows": 1000000, "actual": int(q1("select count(*) from w_cz where city = 5 and zip = 523"))}
ez["estimate_before"] = json.loads(psql("EXPLAIN (FORMAT JSON) " + qz))[0]["Plan"]["Plan Rows"]
psql("CREATE STATISTICS w_cz_dep (dependencies) ON city, zip FROM w_cz; ANALYZE w_cz")
ez["estimate_after"] = json.loads(psql("EXPLAIN (FORMAT JSON) " + qz))[0]["Plan"]["Plan Rows"]
qg = "SELECT city, zip, count(*) FROM w_cz GROUP BY city, zip"
ez["group_estimate_before_ndistinct"] = json.loads(psql("EXPLAIN (FORMAT JSON) " + qg))[0]["Plan"]["Plan Rows"]
psql("CREATE STATISTICS w_cz_nd (ndistinct) ON city, zip FROM w_cz; ANALYZE w_cz")
ez["group_estimate_after_ndistinct"] = json.loads(psql("EXPLAIN (FORMAT JSON) " + qg))[0]["Plan"]["Plan Rows"]
ez["group_actual"] = int(q1("select count(*) from (select distinct city, zip from w_cz) s"))
save("extended_stats", ez)
psql("DROP TABLE w_cz")

# 5. analyze after a bulk load
psql("CREATE TABLE w_load (id bigint, v int, pad text) WITH (autovacuum_enabled = false);"
     "CREATE INDEX w_load_v ON w_load (v); ANALYZE w_load;"
     "INSERT INTO w_load SELECT g, g % 10, repeat('x', 40) FROM generate_series(1,2000000) g")
ql = "SELECT count(*), max(pad) FROM w_load WHERE v = 3"
pre = "SET max_parallel_workers_per_gather = 0; "
al = {"rows": 2000000, "actual": int(q1("select count(*) from w_load where v = 3"))}
jb = json.loads(psql("EXPLAIN (FORMAT JSON) " + ql))[0]["Plan"]
al["before"] = runs(ql, 3, pre); al["before"]["nodes"] = [n["Node Type"] for n in nodes(jb)]
al["before"]["estimate"] = [n.get("Plan Rows") for n in nodes(jb)]
al["has_stats_before"] = int(q1("select count(*) from pg_stats where tablename='w_load'"))
psql("ANALYZE w_load")
ja = json.loads(psql("EXPLAIN (FORMAT JSON) " + ql))[0]["Plan"]
al["after"] = runs(ql, 3, pre); al["after"]["nodes"] = [n["Node Type"] for n in nodes(ja)]
al["after"]["estimate"] = [n.get("Plan Rows") for n in nodes(ja)]
save("analyze_after_load", al)
psql("DROP TABLE w_load")

# 6. HOT and indexed columns
ho = {"rows": 1000000, "fillfactor": 80, "updated_rows": 100000}
for t, col in [("w_hot1", "c"), ("w_hot2", "b")]:
    psql(f"CREATE TABLE {t} (id bigint PRIMARY KEY, b int, c int) WITH (fillfactor = 80, autovacuum_enabled = false);"
         f"INSERT INTO {t} SELECT g, g, g FROM generate_series(1,1000000) g;"
         f"CREATE INDEX {t}_b ON {t} (b); VACUUM ANALYZE {t}")
    sz0 = {"table": round(int(q1(f"select pg_relation_size('{t}')")) / 1e6, 1),
           "b_index": round(int(q1(f"select pg_relation_size('{t}_b')")) / 1e6, 1),
           "pkey": round(int(q1(f"select pg_relation_size('{t}_pkey')")) / 1e6, 1)}
    lsn = wal_lsn()
    tt = timed(f"UPDATE {t} SET {col} = {col} + 1 WHERE id % 10 = 0")
    wal = wal_mb_since(lsn)
    time.sleep(2)
    psql("SELECT pg_stat_force_next_flush()")
    time.sleep(1)
    hot = q1(f"select n_tup_upd || ',' || n_tup_hot_upd from pg_stat_user_tables where relname = '{t}'")
    sz1 = {"table": round(int(q1(f"select pg_relation_size('{t}')")) / 1e6, 1),
           "b_index": round(int(q1(f"select pg_relation_size('{t}_b')")) / 1e6, 1),
           "pkey": round(int(q1(f"select pg_relation_size('{t}_pkey')")) / 1e6, 1)}
    ho["update_" + col] = {"seconds": tt, "wal_mb": wal, "n_tup_upd": int(hot.split(",")[0]),
                           "n_tup_hot_upd": int(hot.split(",")[1]), "size_before_mb": sz0, "size_after_mb": sz1}
    psql(f"DROP TABLE {t}")
save("hot_indexed_column", ho)

# 7. index bloat after random deletes, and REINDEX
psql("SELECT setseed(0.7); CREATE TABLE w_bl (id bigint, r double precision) WITH (autovacuum_enabled = false);"
     "INSERT INTO w_bl SELECT g, random() FROM generate_series(1,2000000) g;"
     "CREATE INDEX w_bl_r ON w_bl (r); VACUUM ANALYZE w_bl")
bl = {"rows": 2000000, "index_before_mb": round(int(q1("select pg_relation_size('w_bl_r')")) / 1e6, 1)}
qb = "SELECT count(*) FROM w_bl WHERE r BETWEEN 0.5 AND 0.51"
bl["range_before"] = runs(qb, 3)
psql("DELETE FROM w_bl WHERE id % 10 <> 0; VACUUM w_bl")
bl["rows_left"] = int(q1("select count(*) from w_bl"))
bl["index_after_delete_vacuum_mb"] = round(int(q1("select pg_relation_size('w_bl_r')")) / 1e6, 1)
bl["range_after_delete"] = runs(qb, 3)
bl["reindex_s"] = timed("REINDEX INDEX w_bl_r")
bl["index_after_reindex_mb"] = round(int(q1("select pg_relation_size('w_bl_r')")) / 1e6, 1)
bl["range_after_reindex"] = runs(qb, 3)
save("index_bloat_reindex", bl)
psql("DROP TABLE w_bl")

# 8-10. CREATE INDEX / REINDEX, with and without CONCURRENTLY; maintenance_work_mem
psql("SELECT setseed(0.3); CREATE TABLE w_ix (id bigint, r bigint) WITH (autovacuum_enabled = false);"
     "INSERT INTO w_ix SELECT g, (random() * 1e12)::bigint FROM generate_series(1,5000000) g;"
     "VACUUM ANALYZE w_ix")
ix = {"rows": 5000000, "column": "random bigint",
      "max_parallel_maintenance_workers": q1("show max_parallel_maintenance_workers"),
      "maintenance_work_mem_default": q1("show maintenance_work_mem")}
ix["create_index"] = walltime(["CREATE INDEX w_ix_r ON w_ix (r)", "DROP INDEX w_ix_r"])
ix["create_index_concurrently"] = walltime(["CREATE INDEX CONCURRENTLY w_ix_r ON w_ix (r)", "DROP INDEX w_ix_r"])
psql("CREATE INDEX w_ix_r ON w_ix (r)")
ix["index_mb"] = round(int(q1("select pg_relation_size('w_ix_r')")) / 1e6, 1)
ix["reindex"] = walltime(["REINDEX INDEX w_ix_r"])
ix["reindex_concurrently"] = walltime(["REINDEX INDEX CONCURRENTLY w_ix_r"])
psql("DROP INDEX w_ix_r")
mw = {}
for m in ["1MB", "64MB", "1GB"]:
    for workers in [0, 2]:
        mw[f"{m}_workers{workers}"] = walltime([f"SET maintenance_work_mem = '{m}'",
                                                f"SET max_parallel_maintenance_workers = {workers}",
                                                "CREATE INDEX w_ix_r ON w_ix (r)", "DROP INDEX w_ix_r"])
ix["maintenance_work_mem"] = mw
save("index_build", ix)
psql("DROP TABLE w_ix")

# 11. boolean index
psql("CREATE TABLE w_bool (id bigint, half boolean, rare boolean, pad text);"
     "INSERT INTO w_bool SELECT g, g % 2 = 0, g % 100 = 0, repeat('x', 40) FROM generate_series(1,2000000) g;"
     "CREATE INDEX w_bool_half ON w_bool (half); CREATE INDEX w_bool_rare ON w_bool (rare); VACUUM ANALYZE w_bool")
pb = "SET max_parallel_workers_per_gather = 0; "
bo = {"rows": 2000000,
      "half_true": runs("SELECT count(*), max(pad) FROM w_bool WHERE half", 3, pb),
      "rare_true": runs("SELECT count(*), max(pad) FROM w_bool WHERE rare", 3, pb),
      "half_index_mb": round(int(q1("select pg_relation_size('w_bool_half')")) / 1e6, 1),
      "rare_index_mb": round(int(q1("select pg_relation_size('w_bool_rare')")) / 1e6, 1),
      "plan_half": psql("EXPLAIN (COSTS OFF) SELECT count(*), max(pad) FROM w_bool WHERE half"),
      "plan_rare": psql("EXPLAIN (COSTS OFF) SELECT count(*), max(pad) FROM w_bool WHERE rare")}
psql("DROP INDEX w_bool_half, w_bool_rare")
bo["rare_no_index"] = runs("SELECT count(*), max(pad) FROM w_bool WHERE rare", 3, pb)
save("boolean_index", bo)
psql("DROP TABLE w_bool")

# 12-13. jsonb: GIN jsonb_ops vs jsonb_path_ops, and an expression index
psql("CREATE TABLE w_j (id bigint, doc jsonb);"
     "INSERT INTO w_j SELECT g, jsonb_build_object('user', g % 10000, 'kind', (array['a','b','c','d'])[1 + g % 4], 'tags', jsonb_build_array('t' || (g % 50), 't' || (g % 7)), 'n', g) FROM generate_series(1,1000000) g;"
     "VACUUM ANALYZE w_j")
qc = "SELECT count(*) FROM w_j WHERE doc @> '{\"user\": 42}'"
qe = "SELECT count(*) FROM w_j WHERE doc->>'user' = '42'"
jj = {"rows": 1000000, "matching_rows": int(q1(qc)), "table_mb": round(int(q1("select pg_relation_size('w_j')")) / 1e6, 1)}
jj["no_index_containment"] = runs(qc, 3, pb)
for name, ddl in [("jsonb_ops", "CREATE INDEX w_j_i ON w_j USING gin (doc)"),
                  ("jsonb_path_ops", "CREATE INDEX w_j_i ON w_j USING gin (doc jsonb_path_ops)"),
                  ("btree_expr", "CREATE INDEX w_j_i ON w_j ((doc->>'user'))")]:
    t = timed(ddl); psql("ANALYZE w_j")
    jj[name] = {"build_s": t, "index_mb": round(int(q1("select pg_relation_size('w_j_i')")) / 1e6, 1),
                "containment": runs(qc, 3, pb), "arrow_equals": runs(qe, 3, pb)}
    psql("DROP INDEX w_j_i")
save("jsonb_indexes", jj)
psql("DROP TABLE w_j")

psql(f"DROP TABLE IF EXISTS {TABLES} CASCADE")
stop()
print("done")
