#!/usr/bin/env python3
"""VeloceDB aspect tests + testdb comparison vs SQLite and Redis on localhost."""
from __future__ import annotations

import json
import os
import socket
import sqlite3
import statistics
import subprocess
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path

HOST = "127.0.0.1"
REDIS_HOST = os.environ.get("VELOCE_BENCH_REDIS_HOST", HOST)


def bench_tcp_host(port: int) -> str:
    """Loopback :1583 is often tachyon-isam (in-memory); node workgroup is on the outward bind."""
    if port not in (1583, 11583):
        return HOST
    explicit = os.environ.get("VELOCE_BENCH_WG_HOST", "").strip()
    if explicit:
        return explicit
    node = (
        os.environ.get("VELOCE_BENCH_NODE_HOST", "").strip()
        or os.environ.get("VELOCE_ADVERTISE_HOST", "").strip()
    )
    if node and node not in ("127.0.0.1", "0.0.0.0", "::", "localhost"):
        return node
    return HOST
REDIS_PORT = os.environ.get("VELOCE_BENCH_REDIS_PORT", "26379")
ROWS = 50000
GETS = 50000
CONC = 8
PIPE_RUNS = max(1, int(os.environ.get("VELOCE_BENCH_PIPE_RUNS", "5")))
PIPE_MIN_MS = float(os.environ.get("VELOCE_BENCH_PIPE_MIN_MS", "8"))
_UID = os.getuid() if hasattr(os, "getuid") else 0
SQLITE_PATH = f"/tmp/veloce-compare-testdb-{_UID}.sqlite"
REDIS_PIPE = Path(f"/tmp/veloce-redis-ins-{_UID}.resp")
OUT = "/tmp/veloce-compare-report.json"

def _engine_dir() -> Path:
    candidates = []
    env = os.environ.get("VELOCE_ENGINE_DIR")
    if env:
        candidates.append(Path(env))
    candidates.append(Path(__file__).resolve().parent)
    candidates.append(Path("/opt/velocedb/workgroup/engine"))
    for p in candidates:
        if (p / "workgroup-server.mjs").is_file() and (p / "compare-all.py").is_file():
            return p
    return Path(__file__).resolve().parent


ENGINE_DIR = _engine_dir()


def installed_version() -> str:
    for p in (
        Path("/opt/velocedb/workgroup/VERSION"),
        ENGINE_DIR.parent / "VERSION",
    ):
        try:
            if p.is_file():
                return p.read_text(encoding="utf-8").strip()
        except OSError:
            pass
    return os.environ.get("VELOCE_VERSION") or "2.73.13"
_TCP_QUICKACK = getattr(socket, "TCP_QUICKACK", 12)


def _quickack(s: socket.socket) -> None:
    try:
        if s.family == socket.AF_INET:
            s.setsockopt(socket.IPPROTO_TCP, _TCP_QUICKACK, 1)
    except OSError:
        pass


def tcp(port: int, timeout: float = 8.0, host: str = HOST) -> socket.socket:
    s = socket.create_connection((host, port), timeout=timeout)
    s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
    _quickack(s)
    return s


def read_line(s: socket.socket) -> str:
    buf = b""
    while b"\n" not in buf:
        chunk = s.recv(4096)
        if not chunk:
            break
        buf += chunk
    return buf.split(b"\n", 1)[0].decode("utf-8", "replace").rstrip("\r")


class Veloce:
    def __init__(self, port: int | None = None, uds: str | None = None, host: str = HOST):
        if uds:
            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            s.settimeout(8.0)
            s.connect(uds)
            self.s = s
        else:
            self.s = tcp(int(port or 2143), host=host)
        self._buf = b""
        self.banner = self._read_line()

    def _read_line(self) -> str:
        while b"\n" not in self._buf:
            chunk = self.s.recv(65536)
            if not chunk:
                break
            self._buf += chunk
        line, _, rest = self._buf.partition(b"\n")
        self._buf = rest
        return line.decode("latin-1", "replace").rstrip("\r")

    def cmd(self, line: str) -> str:
        self.s.sendall((line + "\r\n").encode("ascii", "replace"))
        return self._read_line()

    def close(self) -> None:
        try:
            self.s.close()
        except OSError:
            pass


def aspect(name: str, fn) -> dict:
    t0 = time.perf_counter()
    try:
        detail = fn()
        ok = True
        err = None
    except Exception as e:  # noqa: BLE001
        ok = False
        detail = ""
        err = str(e)
    ms = round((time.perf_counter() - t0) * 1000, 2)
    return {"name": name, "ok": ok, "detail": detail, "error": err, "ms": ms}


def pct(xs: list[float], p: float) -> float:
    if not xs:
        return 0.0
    ys = sorted(xs)
    i = min(len(ys) - 1, max(0, int((p / 100.0) * len(ys) + 0.999) - 1))
    return ys[i]


def _bench_key(i: int) -> str:
    return f"row.bench.{i}"


def bench_veloce(port: int, n_ins: int, n_get: int, conc: int) -> dict:
    host = bench_tcp_host(port)
    setup = Veloce(port, host=host)
    ping_t0 = time.perf_counter()
    setup.cmd("PING")
    ping_us = (time.perf_counter() - ping_t0) * 1e6
    setup.cmd("RESET TESTDB")
    setup.close()

    def insert_worker(start: int, step: int) -> list[float]:
        c = Veloce(port, host=host)
        lat = []
        for i in range(start, n_ins, step):
            t0 = time.perf_counter()
            c.cmd(f"INSERT TESTDB {_bench_key(i)} row-{i}")
            lat.append((time.perf_counter() - t0) * 1e6)
        c.close()
        return lat

    def get_worker(start: int, step: int) -> tuple[list[float], int]:
        c = Veloce(port, host=host)
        lat = []
        hits = 0
        rng = start
        for i in range(start, n_get, step):
            key = _bench_key((i * 7919) % n_ins)
            t0 = time.perf_counter()
            out = c.cmd(f"GET TESTDB {key}")
            lat.append((time.perf_counter() - t0) * 1e6)
            if out.startswith("OK "):
                hits += 1
            rng += 1
        c.close()
        return lat, hits

    t0 = time.perf_counter()
    ins_lat: list[float] = []
    with ThreadPoolExecutor(max_workers=conc) as ex:
        futs = [ex.submit(insert_worker, w, conc) for w in range(conc)]
        for f in as_completed(futs):
            ins_lat.extend(f.result())
    ins_ms = (time.perf_counter() - t0) * 1000

    t0 = time.perf_counter()
    get_lat: list[float] = []
    hits = 0
    with ThreadPoolExecutor(max_workers=conc) as ex:
        futs = [ex.submit(get_worker, w, conc) for w in range(conc)]
        for f in as_completed(futs):
            lat, h = f.result()
            get_lat.extend(lat)
            hits += h
    get_ms = (time.perf_counter() - t0) * 1000

    c = Veloce(port, host=host)
    count = c.cmd("COUNT TESTDB")
    c.close()
    return {
        "engine": "VeloceDB",
        "surface": f"TCP {port}" + (f" ({host})" if host != HOST else ""),
        "ping_us": round(ping_us, 1),
        "count": count,
        "insert": summarize("insert", ins_lat, ins_ms),
        "get": {**summarize("get", get_lat, get_ms), "hits": hits},
    }


def summarize(label: str, lat: list[float], elapsed_ms: float) -> dict:
    n = len(lat)
    raw_ms = float(elapsed_ms)
    eff_ms = raw_ms if raw_ms > 0 else 0.001
    return {
        "label": label,
        "ops": n,
        "elapsed_ms": round(elapsed_ms),
        "elapsed_raw_ms": raw_ms,
        "ops_per_sec": round(n / eff_ms * 1000),
        "p50_us": round(pct(lat, 50)),
        "p95_us": round(pct(lat, 95)),
        "p99_us": round(pct(lat, 99)),
    }


def bench_sqlite(n_ins: int, n_get: int) -> dict:
    if Path(SQLITE_PATH).exists():
        os.remove(SQLITE_PATH)
    conn = sqlite3.connect(SQLITE_PATH)
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA synchronous=NORMAL")
    conn.execute("CREATE TABLE testdb (k TEXT PRIMARY KEY, v TEXT)")
    ping_t0 = time.perf_counter()
    conn.execute("SELECT 1").fetchone()
    ping_us = (time.perf_counter() - ping_t0) * 1e6

    t0 = time.perf_counter()
    ins_lat = []
    for i in range(n_ins):
        t1 = time.perf_counter()
        conn.execute("INSERT INTO testdb(k,v) VALUES(?,?)", (f"k{i}", f"row-{i}"))
        ins_lat.append((time.perf_counter() - t1) * 1e6)
        if i % 1000 == 999:
            conn.commit()
    conn.commit()
    ins_ms = (time.perf_counter() - t0) * 1000

    t0 = time.perf_counter()
    get_lat = []
    hits = 0
    for i in range(n_get):
        key = f"k{(i * 7919) % n_ins}"
        t1 = time.perf_counter()
        row = conn.execute("SELECT v FROM testdb WHERE k=?", (key,)).fetchone()
        get_lat.append((time.perf_counter() - t1) * 1e6)
        if row:
            hits += 1
    get_ms = (time.perf_counter() - t0) * 1000
    count = conn.execute("SELECT COUNT(*) FROM testdb").fetchone()[0]
    conn.close()
    return {
        "engine": "SQLite",
        "surface": f"embedded WAL {SQLITE_PATH}",
        "ping_us": round(ping_us, 1),
        "count": f"COUNT {count}",
        "insert": summarize("insert", ins_lat, ins_ms),
        "get": {**summarize("get", get_lat, get_ms), "hits": hits},
    }


def http_json(path: str, method: str = "GET", body: dict | None = None):
    cmd = ["curl", "-sS", "-X", method, f"http://127.0.0.1:8098{path}"]
    if body is not None:
        cmd += ["-H", "Content-Type: application/json", "-d", json.dumps(body)]
    out = subprocess.check_output(cmd, text=True)
    if path == "/metrics":
        return out
    return json.loads(out)


def bench_veloce_uds(n_ins: int, n_get: int, conc: int) -> dict:
    ports = http_json("/health").get("ports") or {}
    path = ports.get("uds_workgroup")
    if not path:
        raise RuntimeError("uds_workgroup missing from /health")
    setup = Veloce(uds=path)
    ping_t0 = time.perf_counter()
    setup.cmd("PING")
    ping_us = (time.perf_counter() - ping_t0) * 1e6
    setup.cmd("RESET TESTDB")
    setup.close()

    def insert_worker(start: int, step: int) -> list[float]:
        c = Veloce(uds=path)
        lat = []
        for i in range(start, n_ins, step):
            t0 = time.perf_counter()
            c.cmd(f"INSERT TESTDB {_bench_key(i)} row-{i}")
            lat.append((time.perf_counter() - t0) * 1e6)
        c.close()
        return lat

    def get_worker(start: int, step: int) -> tuple[list[float], int]:
        c = Veloce(uds=path)
        lat = []
        hits = 0
        for i in range(start, n_get, step):
            key = _bench_key((i * 7919) % n_ins)
            t0 = time.perf_counter()
            out = c.cmd(f"GET TESTDB {key}")
            lat.append((time.perf_counter() - t0) * 1e6)
            if out.startswith("OK "):
                hits += 1
        c.close()
        return lat, hits

    t0 = time.perf_counter()
    ins_lat: list[float] = []
    with ThreadPoolExecutor(max_workers=conc) as ex:
        futs = [ex.submit(insert_worker, w, conc) for w in range(conc)]
        for f in as_completed(futs):
            ins_lat.extend(f.result())
    ins_ms = (time.perf_counter() - t0) * 1000

    t0 = time.perf_counter()
    get_lat: list[float] = []
    hits = 0
    with ThreadPoolExecutor(max_workers=conc) as ex:
        futs = [ex.submit(get_worker, w, conc) for w in range(conc)]
        for f in as_completed(futs):
            lat, h = f.result()
            get_lat.extend(lat)
            hits += h
    get_ms = (time.perf_counter() - t0) * 1000
    c = Veloce(uds=path)
    count = c.cmd("COUNT TESTDB")
    c.close()
    return {
        "engine": "VeloceDB",
        "surface": f"UDS chatty (8 clients) {path}",
        "ping_us": round(ping_us, 1),
        "count": count,
        "insert": summarize("insert", ins_lat, ins_ms),
        "get": {**summarize("get", get_lat, get_ms), "hits": hits},
        "note": "Same testdb as TCP 1583. AF_UNIX on the workgroup host; still one round-trip per op.",
    }


def bench_embed(n_ins: int, n_get: int) -> dict:
    script = ENGINE_DIR / "testdb-embed-bench.mjs"
    out = subprocess.check_output(
        ["node", str(script), "--rows", str(n_ins), "--gets", str(n_get)],
        text=True,
    )
    return json.loads(out)


def _pipe_elapsed_ms(bucket: dict) -> float:
    if not bucket:
        return 0.0
    raw = bucket.get("elapsed_raw_ms")
    if raw is not None:
        return float(raw)
    return float(bucket.get("elapsed_ms") or 0)


def _chatty_elapsed_ms(chatty: dict | None, key: str) -> float:
    if not chatty:
        return 0.0
    bucket = chatty.get(key) or {}
    raw = bucket.get("elapsed_raw_ms")
    if raw is not None:
        return float(raw)
    return float(bucket.get("elapsed_ms") or 0)


def _pipe_sandbagged(row: dict, chatty: dict | None = None) -> bool:
    ins = row.get("insert") or {}
    get = row.get("get") or {}
    ins_ms = _pipe_elapsed_ms(ins)
    get_ms = _pipe_elapsed_ms(get)
    if ins_ms < PIPE_MIN_MS or get_ms < PIPE_MIN_MS:
        return True
    ins_ops = int(ins.get("ops_per_sec") or 0)
    get_ops = int(get.get("ops_per_sec") or 0)
    if ins_ops > 5_000_000 or get_ops > 10_000_000:
        return True
    if chatty:
        chatty_ins = _chatty_elapsed_ms(chatty, "insert")
        chatty_get = _chatty_elapsed_ms(chatty, "get")
        # Pipelined is meant to beat chatty (fewer RTTs). Flag only absurd walls.
        if chatty_ins > 0 and ins_ms < min(40.0, chatty_ins / 400):
            return True
        if chatty_get > 0 and get_ms < min(15.0, chatty_get / 400):
            return True
    return False


def _median_pipe_runs(runs: list[dict]) -> dict:
    if not runs:
        return {
            "engine": "VeloceDB",
            "surface": "pipelined (no valid runs)",
            "error": "pipe harness sandbagged or failed",
        }
    base = runs[0].copy()
    for key in ("insert", "get"):
        base[key] = {
            **runs[0][key],
            "ops_per_sec": int(statistics.median(r[key]["ops_per_sec"] for r in runs)),
            "elapsed_ms": int(statistics.median(r[key]["elapsed_ms"] for r in runs)),
            "p50_us": statistics.median(r[key]["p50_us"] for r in runs),
            "p95_us": statistics.median(r[key]["p95_us"] for r in runs),
            "p99_us": statistics.median(r[key]["p99_us"] for r in runs),
        }
    if "hits" in runs[0].get("get", {}):
        base["get"]["hits"] = runs[0]["get"]["hits"]
    base["note"] = (
        runs[0].get("note", "")
        + f" Median of {len(runs)} run(s) (VELOCE_BENCH_PIPE_RUNS={PIPE_RUNS})."
    )
    return base


def bench_veloce_pipe_once(port: int, n_ins: int, n_get: int, batch: int = 500) -> dict:
    host = bench_tcp_host(port)
    setup = Veloce(port, host=host)
    setup.cmd("RESET TESTDB")
    setup.close()
    c = Veloce(port, host=host)
    ins_cmds = []
    for start in range(0, n_ins, batch):
        end = min(n_ins, start + batch)
        pairs = " ".join(f"{_bench_key(i)} row-{i}" for i in range(start, end))
        ins_cmds.append(f"MINSERT TESTDB {pairs}\r\n".encode())
    # Coalesce socket writes (send CHUNK cmds per sendall) then drain — fewer syscalls, same ack contract.
    pipe_chunk = max(1, int(os.environ.get("VELOCE_BENCH_PIPE_CHUNK", "8")))
    t0 = time.perf_counter()
    for i in range(0, len(ins_cmds), pipe_chunk):
        chunk = ins_cmds[i : i + pipe_chunk]
        c.s.sendall(b"".join(chunk))
        for _ in chunk:
            out = c._read_line()
            if not out.startswith("OK "):
                raise AssertionError(out[:120])
    c.cmd("FLUSH TESTDB")
    ins_ms = (time.perf_counter() - t0) * 1000
    mean_ins = (ins_ms * 1000) / n_ins

    get_cmds = []
    for start in range(0, n_get, batch):
        end = min(n_get, start + batch)
        keys = [_bench_key((i * 7919) % n_ins) for i in range(start, end)]
        get_cmds.append(("MGET TESTDB " + " ".join(keys) + "\r\n").encode())
    t0 = time.perf_counter()
    hits = 0
    for i in range(0, len(get_cmds), pipe_chunk):
        chunk = get_cmds[i : i + pipe_chunk]
        c.s.sendall(b"".join(chunk))
        for _ in chunk:
            out = c._read_line()
            if not out.startswith("OK mget "):
                raise AssertionError(out[:120])
            vals = json.loads(out[8:])
            hits += sum(1 for v in vals if v is not None)
    get_ms = (time.perf_counter() - t0) * 1000
    mean_get = (get_ms * 1000) / n_get
    count = c.cmd("COUNT TESTDB")
    c.close()
    return {
        "engine": "VeloceDB",
        "surface": f"TCP {port} MINSERT×{batch} / MGET×{batch} pipelined",
        "ping_us": None,
        "count": count,
        "insert": summarize("insert", [mean_ins] * n_ins, ins_ms),
        "get": {**summarize("get", [mean_get] * n_get, get_ms), "hits": hits},
        "note": (
            f"INSERT: pipelined MINSERTs of {batch} pairs (coalesced send×{pipe_chunk}, one ack each). "
            f"GET: pipelined MGETs of {batch} keys (coalesced send×{pipe_chunk}). p50/p95/p99 are batch means of wall/n."
        ),
        "get_mode": "MGET×500 pipelined",
        "insert_mode": "MINSERT×500 pipelined",
    }


def bench_veloce_pipe(
    port: int,
    n_ins: int,
    n_get: int,
    batch: int = 500,
    chatty_ref: dict | None = None,
) -> dict:
    runs: list[dict] = []
    attempts = 0
    max_attempts = PIPE_RUNS + (5 if port == 1583 else 1)
    while len(runs) < PIPE_RUNS and attempts < max_attempts:
        attempts += 1
        row = bench_veloce_pipe_once(port, n_ins, n_get, batch)
        if _pipe_sandbagged(row, chatty_ref):
            continue
        runs.append(row)
    out = _median_pipe_runs(runs)
    if _pipe_sandbagged(out, chatty_ref):
        return {
            "engine": "VeloceDB",
            "surface": f"TCP {port} MINSERT×{batch} / MGET×{batch} pipelined",
            "error": (
                "pipelined wall clock under-reported vs chatty on this surface; "
                "labeled table keeps prior row or chatty proxy"
            ),
        }
    return out


def _seed_testdb(port: int, n_ins: int) -> None:
    host = bench_tcp_host(port)
    setup = Veloce(port, host=host)
    setup.cmd("RESET TESTDB")
    setup.close()
    c = Veloce(port, host=host)
    batch = 500
    for start in range(0, n_ins, batch):
        end = min(n_ins, start + batch)
        pairs = " ".join(f"{_bench_key(i)} row-{i}" for i in range(start, end))
        out = c.cmd(f"MINSERT TESTDB {pairs}")
        if not out.startswith("OK "):
            c.close()
            raise AssertionError(out[:120])
    c.close()


def _mux_bin():
    p = ENGINE_DIR / "tachyon-mux-bench"
    if p.exists() and os.access(p, os.X_OK):
        return p
    return None


def _mux_result(port: int, n_keys: int, clients: int, mode: str, j: dict, elapsed_ms: float) -> dict:
    hits = int(j.get("hits") or 0)
    n_insert = int(j.get("n_insert") or 0)
    n_get = int(j.get("n_get") or 0)
    ins_ms = elapsed_ms if n_insert else 1.0
    get_ms = elapsed_ms if n_get else 1.0
    mean_ins = (elapsed_ms * 1000) / max(1, n_insert)
    mean_get = (elapsed_ms * 1000) / max(1, n_get)
    label = {"get": "GET", "insert": "INSERT", "mixed": "mixed 85/15 GET/INSERT"}.get(mode, mode)
    insert = summarize("insert", [mean_ins] * n_insert, ins_ms) if n_insert else summarize("insert", [], 1.0)
    get = (
        {**summarize("get", [mean_get] * n_get, get_ms), "hits": hits}
        if n_get
        else {**summarize("get", [], 1.0), "hits": 0}
    )
    return {
        "engine": "VeloceDB",
        "surface": j.get("surface") or f"TCP {port} async multiplex {label} x{clients} (not chatty)",
        "ping_us": None,
        "count": f"COUNT {n_keys}",
        "insert": insert,
        "get": get,
        "note": j.get("note") or "Send without wait-for-line; drain replies. Chatty stays 1 RTT.",
        "get_mode": f"async multiplex {label} x{clients}",
        "insert_mode": "seed excluded; mux INSERT counted" if n_insert else "GET-only (INSERT not sent)",
        "ops_per_sec": int(j.get("ops_per_sec") or 0),
        "n_insert": n_insert,
        "n_get": n_get,
    }


def bench_veloce_mux(port: int, n_ins: int, n_get: int, clients: int = 16, mode: str = "get") -> dict:
    """Send without wait-for-line. Not chatty. mode=get|insert|mixed (85/15)."""
    _seed_testdb(port, n_ins)
    mux_host = bench_tcp_host(port)
    bin_path = _mux_bin()
    if bin_path:
        raw = subprocess.check_output(
            [str(bin_path), mux_host, str(port), str(clients), str(n_get), str(n_ins), mode],
            text=True,
        )
        j = json.loads(raw.strip().splitlines()[-1])
        elapsed = float(j.get("elapsed_ms") or 1)
        return _mux_result(port, n_ins, clients, mode, j, elapsed)

    def worker(wid: int, n: int, start: int) -> tuple[float, int, int, int]:
        s = tcp(port, host=mux_host)
        read_line(s)
        blobs = []
        n_g = n_i = 0
        for i in range(n):
            k = (start + i) * 7919 % n_ins
            do_get = True
            if mode == "insert":
                do_get = False
            elif mode == "mixed":
                do_get = (i % 100) < 85
            if do_get:
                blobs.append(f"GET TESTDB k{k}\r\n".encode())
                n_g += 1
            else:
                blobs.append(f"INSERT TESTDB k{k} row-{start + i}\r\n".encode())
                n_i += 1
        t0 = time.perf_counter()
        for b in blobs:
            s.sendall(b)
        got = 0
        buf = b""
        while got < n:
            chunk = s.recv(65536)
            if not chunk:
                break
            buf += chunk
            got = buf.count(b"\n")
        elapsed = (time.perf_counter() - t0) * 1000
        s.close()
        return elapsed, min(got, n), n_g, n_i

    each = n_get // clients
    rem = n_get % clients
    t0 = time.perf_counter()
    hits = n_g = n_i = 0
    with ThreadPoolExecutor(max_workers=clients) as ex:
        futs = []
        off = 0
        for w in range(clients):
            n = each + (1 if w < rem else 0)
            futs.append(ex.submit(worker, w, n, off))
            off += n
        for f in as_completed(futs):
            _, h, g, i = f.result()
            hits += h
            n_g += g
            n_i += i
    get_ms = (time.perf_counter() - t0) * 1000
    j = {
        "hits": hits,
        "n_insert": n_i,
        "n_get": n_g,
        "elapsed_ms": get_ms,
        "ops_per_sec": round(hits / get_ms * 1000) if get_ms else 0,
        "note": "Python send-all then drain. Chatty stays 1 RTT.",
    }
    return _mux_result(port, n_ins, clients, mode, j, get_ms)


def redis_cmd(args: list[str]) -> str:
    return subprocess.check_output(
        ["redis-cli", "-h", REDIS_HOST, "-p", str(REDIS_PORT), *args],
        text=True,
    ).strip()


def resp(*args: str) -> str:
    parts = [f"*{len(args)}\r\n"]
    for a in args:
        b = a.encode("utf-8")
        parts.append(f"${len(b)}\r\n{a}\r\n")
    return "".join(parts)


def bench_redis(n_ins: int, n_get: int) -> dict:
    redis_cmd(["DEL", "veloce:testdb"])
    ping_t0 = time.perf_counter()
    redis_cmd(["PING"])
    ping_us = (time.perf_counter() - ping_t0) * 1e6

    pipe = REDIS_PIPE
    with pipe.open("w", encoding="utf-8", newline="\n") as f:
        f.write(resp("DEL", "veloce:testdb"))
        for i in range(n_ins):
            f.write(resp("HSET", "veloce:testdb", f"k{i}", f"row-{i}"))
    t0 = time.perf_counter()
    subprocess.check_output(
        ["bash", "-lc", f"redis-cli -h {REDIS_HOST} -p {REDIS_PORT} --pipe < {pipe}"],
        text=True,
        stderr=subprocess.STDOUT,
        timeout=120,
    )
    ins_ms = (time.perf_counter() - t0) * 1000
    mean_us = (ins_ms * 1000) / n_ins
    ins_lat = [mean_us] * n_ins

    t0 = time.perf_counter()
    get_lat: list[float] = []
    hits = 0
    for start in range(0, n_get, 500):
        keys = [f"k{(i * 7919) % n_ins}" for i in range(start, min(n_get, start + 500))]
        t1 = time.perf_counter()
        out = subprocess.check_output(
            ["redis-cli", "-h", REDIS_HOST, "-p", str(REDIS_PORT), "HMGET", "veloce:testdb", *keys],
            text=True,
        )
        chunk_us = (time.perf_counter() - t1) * 1e6 / max(1, len(keys))
        vals = [ln for ln in out.splitlines() if ln != ""]
        hits += sum(1 for v in vals if v != "(nil)")
        get_lat.extend([chunk_us] * len(keys))
    get_ms = (time.perf_counter() - t0) * 1000
    count = int(redis_cmd(["HLEN", "veloce:testdb"]))
    return {
        "engine": "Redis",
        "surface": f"TCP {REDIS_PORT} HASH testdb (RESP --pipe insert, HMGET reads)",
        "ping_us": round(ping_us, 1),
        "count": f"COUNT {count}",
        "insert": summarize("insert", ins_lat, ins_ms),
        "get": {**summarize("get", get_lat, get_ms), "hits": hits},
        "note": "Insert p50/p95/p99 are the batch mean (pipeline has no per-op timestamps).",
    }


def which(cmd: str) -> bool:
    from shutil import which as _which

    return _which(cmd) is not None


def sql_escape(s: str) -> str:
    return s.replace("'", "''")


def write_batched_insert_sql(path: Path, table: str, n_ins: int, batch: int, dialect: str) -> None:
    chunks = []
    if dialect == "mysql":
        chunks.append("SET autocommit=0;\n")
    for start in range(0, n_ins, batch):
        end = min(n_ins, start + batch)
        rows = ",".join(f"('{sql_escape(f'k{i}')}','{sql_escape(f'row-{i}')}')" for i in range(start, end))
        chunks.append(f"INSERT INTO {table}(k,v) VALUES {rows};\n")
    if dialect == "mysql":
        chunks.append("COMMIT;\n")
    elif dialect == "postgres":
        chunks.append("COMMIT;\n")
    path.write_text("".join(chunks), encoding="utf-8")


def write_batched_get_sql(path: Path, table: str, n_ins: int, n_get: int, batch: int) -> None:
    chunks = []
    for start in range(0, n_get, batch):
        end = min(n_get, start + batch)
        keys = ",".join(f"'{sql_escape(f'k{(i * 7919) % n_ins}')}'" for i in range(start, end))
        chunks.append(f"SELECT v FROM {table} WHERE k IN ({keys});\n")
    path.write_text("".join(chunks), encoding="utf-8")


def bench_mysql(n_ins: int, n_get: int, batch: int = 500) -> dict | None:
    if not which("mysql"):
        return None
    user = os.environ.get("VELOCE_MYSQL_USER", "veloce_bench")
    password = os.environ.get("VELOCE_MYSQL_PASS", "veloce_bench")
    db = os.environ.get("VELOCE_MYSQL_DB", "veloce_testdb")
    base = [
        "mysql",
        "-h",
        HOST,
        "-P",
        os.environ.get("VELOCE_MYSQL_PORT", "3306"),
        "-u",
        user,
        f"-p{password}",
        "--protocol=TCP",
        "--batch",
        "--skip-column-names",
    ]
    setup_sql = (
        f"USE {db};\n"
        "DROP TABLE IF EXISTS testdb;\n"
        "CREATE TABLE testdb (k VARCHAR(64) PRIMARY KEY, v VARCHAR(128)) ENGINE=InnoDB;\n"
    )
    try:
        subprocess.run(base, input=setup_sql, text=True, check=True, capture_output=True)
    except (subprocess.CalledProcessError, FileNotFoundError) as e:
        return {
            "engine": "MySQL",
            "surface": "skipped",
            "error": str(e),
        }
    ins_sql = Path("/tmp/veloce-mysql-ins.sql")
    get_sql = Path("/tmp/veloce-mysql-get.sql")
    write_batched_insert_sql(ins_sql, "testdb", n_ins, batch, "mysql")
    write_batched_get_sql(get_sql, "testdb", n_ins, n_get, batch)
    ping_t0 = time.perf_counter()
    subprocess.run([*base, db, "-e", "SELECT 1"], check=True, capture_output=True, text=True)
    ping_us = (time.perf_counter() - ping_t0) * 1e6

    t0 = time.perf_counter()
    ins = subprocess.run(
        [*base, db],
        input=ins_sql.read_text(encoding="utf-8"),
        text=True,
        capture_output=True,
        check=True,
    )
    ins_ms = (time.perf_counter() - t0) * 1000
    _ = ins
    mean_ins = (ins_ms * 1000) / n_ins

    t0 = time.perf_counter()
    get_out = subprocess.run(
        [*base, db],
        input=get_sql.read_text(encoding="utf-8"),
        text=True,
        capture_output=True,
        check=True,
    )
    get_ms = (time.perf_counter() - t0) * 1000
    hits = sum(1 for ln in get_out.stdout.splitlines() if ln.strip())
    mean_get = (get_ms * 1000) / n_get
    count_out = subprocess.check_output([*base, db, "-e", "SELECT COUNT(*) FROM testdb"], text=True).strip()
    return {
        "engine": "MySQL",
        "surface": f"TCP 127.0.0.1:3306 InnoDB INSERT×{batch} VALUES / SELECT IN×{batch}",
        "ping_us": round(ping_us, 1),
        "count": f"COUNT {count_out.splitlines()[-1]}",
        "insert": summarize("insert", [mean_ins] * n_ins, ins_ms),
        "get": {**summarize("get", [mean_get] * n_get, get_ms), "hits": hits},
        "note": "Fair vs Veloce MINSERT/MGET: one mysql client session, 500-row multi-VALUES INSERT, then SELECT v WHERE k IN (...500...). Not per-row INSERT/SELECT. p50/p99 are batch means of wall/n.",
        "get_mode": f"SELECT IN×{batch}",
        "insert_mode": f"INSERT VALUES×{batch}",
    }


def bench_postgres(n_ins: int, n_get: int, batch: int = 500) -> dict | None:
    if not which("psql"):
        return None
    user = os.environ.get("VELOCE_PG_USER", "veloce_bench")
    password = os.environ.get("VELOCE_PG_PASS", "veloce_bench")
    db = os.environ.get("VELOCE_PG_DB", "veloce_testdb")
    env = {**os.environ, "PGPASSWORD": password, "PGHOST": HOST, "PGPORT": os.environ.get("VELOCE_PG_PORT", "5432"), "PGUSER": user, "PGDATABASE": db}
    try:
        subprocess.run(
            ["psql", "-v", "ON_ERROR_STOP=1", "-c", "DROP TABLE IF EXISTS testdb; CREATE TABLE testdb (k TEXT PRIMARY KEY, v TEXT);"],
            env=env,
            capture_output=True,
            text=True,
            check=True,
        )
    except (subprocess.CalledProcessError, FileNotFoundError) as e:
        return {"engine": "PostgreSQL", "surface": "skipped", "error": str(e)}
    ins_sql = Path("/tmp/veloce-pg-ins.sql")
    get_sql = Path("/tmp/veloce-pg-get.sql")
    write_batched_insert_sql(ins_sql, "testdb", n_ins, batch, "postgres")
    write_batched_get_sql(get_sql, "testdb", n_ins, n_get, batch)
    ping_t0 = time.perf_counter()
    subprocess.run(["psql", "-c", "SELECT 1"], env=env, check=True, capture_output=True, text=True)
    ping_us = (time.perf_counter() - ping_t0) * 1e6

    t0 = time.perf_counter()
    subprocess.run(["psql", "-v", "ON_ERROR_STOP=1", "-f", str(ins_sql)], env=env, check=True, capture_output=True, text=True)
    ins_ms = (time.perf_counter() - t0) * 1000
    mean_ins = (ins_ms * 1000) / n_ins

    t0 = time.perf_counter()
    get_out = subprocess.run(
        ["psql", "-v", "ON_ERROR_STOP=1", "-t", "-A", "-f", str(get_sql)],
        env=env,
        check=True,
        capture_output=True,
        text=True,
    )
    get_ms = (time.perf_counter() - t0) * 1000
    hits = sum(1 for ln in get_out.stdout.splitlines() if ln.strip())
    mean_get = (get_ms * 1000) / n_get
    count = subprocess.check_output(["psql", "-t", "-A", "-c", "SELECT COUNT(*) FROM testdb"], env=env, text=True).strip()
    return {
        "engine": "PostgreSQL",
        "surface": f"TCP 127.0.0.1:5432 INSERT×{batch} VALUES / SELECT IN×{batch}",
        "ping_us": round(ping_us, 1),
        "count": f"COUNT {count}",
        "insert": summarize("insert", [mean_ins] * n_ins, ins_ms),
        "get": {**summarize("get", [mean_get] * n_get, get_ms), "hits": hits},
        "note": "Fair vs Veloce MINSERT/MGET: one psql session, 500-row multi-VALUES INSERT, then SELECT v WHERE k IN (...500...). Not per-row INSERT/SELECT. p50/p99 are batch means of wall/n.",
        "get_mode": f"SELECT IN×{batch}",
        "insert_mode": f"INSERT VALUES×{batch}",
    }


def bench_oracle(n_ins: int, n_get: int, batch: int = 500) -> dict | None:
    if not which("sqlplus") and not which("sql"):
        return None
    return {
        "engine": "Oracle",
        "surface": "skipped — client present but harness uses sqlplus only if VELOCE_ORACLE=1",
        "error": "not enabled",
    }


def maybe_bench(fn, *args):
    try:
        return fn(*args)
    except Exception as e:  # noqa: BLE001
        name = fn.__name__.replace("bench_", "").title()
        return {"engine": name, "surface": "skipped", "error": str(e)}


WAN_REPLICA = os.environ.get("VELOCE_WAN_REPLICA", "").strip()


def bench_wan_replica(n_get: int = 2000, batches: int = 40) -> list[dict]:
    """Cheap two-node WAN rows from the HA replica. Chatty vs pipe. INSERT does not wait-for-replica."""
    rows: list[dict] = []
    if not WAN_REPLICA:
        return rows
    try:
        seed_k = f"wan-k-{int(time.time())}"
        prim = Veloce(2143)
        prim.s.settimeout(200.0)
        prim.cmd("SET SHIP SYNC ON")
        prim.cmd(f"INSERT TESTDB {seed_k} wan-v")
        prim.cmd("FLUSH TESTDB")
        prim.cmd("SET SHIP SYNC OFF")
        prim.close()
        deadline = time.time() + 20.0
        while time.time() < deadline:
            probe = Veloce(2143, host=WAN_REPLICA)
            r0 = probe.cmd(f"GET TESTDB {seed_k}")
            probe.close()
            if r0.startswith("OK "):
                break
            time.sleep(0.25)
        else:
            raise AssertionError(f"WAN replica never saw {seed_k} after primary FLUSH+ship")
        c = Veloce(2143, host=WAN_REPLICA)
        lat: list[float] = []
        hits = 0
        t0 = time.perf_counter()
        for _ in range(n_get):
            t1 = time.perf_counter()
            r = c.cmd(f"GET TESTDB {seed_k}")
            lat.append((time.perf_counter() - t1) * 1e6)
            if r.startswith("OK "):
                hits += 1
        get_ms = (time.perf_counter() - t0) * 1000
        c.close()
        if hits < n_get:
            raise AssertionError(f"WAN chatty hits {hits}/{n_get}")
        rows.append(
            {
                "engine": "VeloceDB SQL (two-node Enterprise)",
                "surface": f"WAN replica GET host03→{WAN_REPLICA}:2143 chatty 1 RTT (GET-only)",
                "ping_us": None,
                "count": f"COUNT {hits}",
                "insert": summarize("insert", [], 1.0),
                "get": {**summarize("get", lat, get_ms), "hits": hits},
                "note": "GET-only. Chatty: one RTT per GET over WAN. Not mux. Replica may lag; seed INSERT is on primary.",
                "get_mode": "chatty GET 1 RTT",
                "insert_mode": "not measured (GET-only)",
            }
        )
        pipe_lat: list[float] = []
        pipe_hits = 0
        t0 = time.perf_counter()
        s = tcp(2143, host=WAN_REPLICA)
        read_line(s)
        for _ in range(batches):
            blob = b"".join(f"MGET TESTDB {seed_k}\r\n".encode() for _ in range(50))
            t1 = time.perf_counter()
            s.sendall(blob)
            got = 0
            buf = b""
            while got < 50:
                chunk = s.recv(65536)
                if not chunk:
                    break
                buf += chunk
                got = buf.count(b"\n")
            chunk_us = (time.perf_counter() - t1) * 1e6 / 50
            pipe_lat.extend([chunk_us] * 50)
            pipe_hits += got
        s.close()
        pipe_ms = (time.perf_counter() - t0) * 1000
        rows.append(
            {
                "engine": "VeloceDB SQL (two-node Enterprise)",
                "surface": f"WAN replica pipe MGET×50 host03→{WAN_REPLICA}:2143 (GET-only, not chatty)",
                "ping_us": None,
                "count": f"COUNT {pipe_hits}",
                "insert": summarize("insert", [], 1.0),
                "get": {**summarize("get", pipe_lat, pipe_ms), "hits": pipe_hits},
                "note": "GET-only. Pipelined MGET×50 over WAN. Not chatty. Not mux.",
                "get_mode": "pipe MGET×50",
                "insert_mode": "not measured (GET-only)",
            }
        )
        ins_lat: list[float] = []
        ins_hits = 0
        get_after: list[float] = []
        get_after_hits = 0
        ins_ms = 0.0
        get_ms_fwd = 0.0
        w = Veloce(2143, host=WAN_REPLICA)
        w.cmd("SET ROLE replica")
        n_ins = min(200, n_get)
        for i in range(n_ins):
            t1 = time.perf_counter()
            r = w.cmd(f"INSERT TESTDB wan-fwd-{i} v{i}")
            dt = time.perf_counter() - t1
            ins_lat.append(dt * 1e6)
            ins_ms += dt * 1000
            if r == "OK 1":
                ins_hits += 1
            t2 = time.perf_counter()
            g = w.cmd(f"GET TESTDB wan-fwd-{i}")
            dtg = time.perf_counter() - t2
            get_after.append(dtg * 1e6)
            get_ms_fwd += dtg * 1000
            if g == f"OK v{i}":
                get_after_hits += 1
        w.close()
        if ins_hits < n_ins or get_after_hits < n_ins:
            raise AssertionError(f"WAN replica INSERT+GET {ins_hits}/{get_after_hits}/{n_ins}")
        rows.append(
            {
                "engine": "VeloceDB SQL (two-node Enterprise)",
                "surface": f"WAN replica INSERT+GET host03→{WAN_REPLICA}:2143 SET ROLE replica (forward+mirror)",
                "ping_us": None,
                "count": f"COUNT {ins_hits}",
                "insert": summarize("insert", ins_lat, ins_ms),
                "get": {**summarize("get", get_after, get_ms_fwd), "hits": get_after_hits},
                "note": "Replica INSERT forwards to primary then mirrors locally; GET after OK must hit without waiting for ship.",
                "get_mode": "chatty GET after INSERT",
                "insert_mode": "chatty INSERT forward+mirror",
            }
        )
    except Exception as e:  # noqa: BLE001
        rows.append(
            {
                "engine": "VeloceDB SQL (two-node Enterprise)",
                "surface": f"WAN replica {WAN_REPLICA}:2143 skipped",
                "error": str(e),
            }
        )
    return rows


def run_aspects() -> list[dict]:
    tests = []

    def restore_host03_primary():
        """SIGKILL/restart can trip replica promotion (VELOCE_FAILOVER_MS=2500). Dual-control failback."""
        deadline = time.time() + 20
        while time.time() < deadline:
            try:
                c = Veloce(1584)
                st = json.loads(c.cmd("SHOW CLUSTER"))
                if st.get("role") == "primary":
                    c.close()
                    return "primary"
                c.cmd("FAILOVER RESUME YES")
                c.close()
            except (OSError, subprocess.CalledProcessError, ConnectionError, TimeoutError, json.JSONDecodeError, ValueError):
                pass
            time.sleep(0.5)
        return "unconfirmed"

    def health():
        out = subprocess.check_output(["curl", "-sS", "http://127.0.0.1:8098/health"], text=True)
        j = json.loads(out)
        assert j["ok"] is True
        return out[:180]

    tests.append(aspect("HTTP health /testdb stats", health))

    def sql_banner():
        c = Veloce(2143)
        b = getattr(c, "banner")
        c.close()
        if "sql ready" not in b:
            raise AssertionError(b)
        return b

    tests.append(aspect("SQL TCP 2143 banner", sql_banner))

    def wg_banner():
        c = Veloce(1583)
        b = getattr(c, "banner")
        c.close()
        if "workgroup ready" not in b:
            raise AssertionError(b)
        return b

    tests.append(aspect("Workgroup TCP 1583 banner", wg_banner))

    def cluster_banner():
        c = Veloce(1584)
        b = getattr(c, "banner")
        c.close()
        if "cluster ready" not in b:
            raise AssertionError(b)
        return b

    tests.append(aspect("Cluster TCP 1584 banner", cluster_banner))

    def pings():
        bits = []
        for port, name in ((2143, "sql"), (1583, "wg"), (1584, "cluster")):
            c = Veloce(port)
            r = c.cmd("PING")
            c.close()
            if r != "PONG":
                raise AssertionError(r)
            bits.append(f"{name}=PONG")
        return ",".join(bits)

    tests.append(aspect("PING on sql/workgroup/cluster", pings))

    def show_tables():
        c = Veloce(2143)
        r = c.cmd("SHOW TABLES")
        c.close()
        if "testdb" not in r or "sys.tenants" not in r:
            raise AssertionError(r)
        return r.replace("\n", " ")

    tests.append(aspect("SHOW TABLES includes testdb", show_tables))

    def roundtrip():
        c = Veloce(2143)
        c.cmd("INSERT TESTDB aspect-key aspect-val")
        g = c.cmd("GET TESTDB aspect-key")
        ge = c.cmd("GETEQUAL TESTDB aspect-key")
        c.close()
        if g != "OK aspect-val" or ge != "OK aspect-val":
            raise AssertionError(f"{g} / {ge}")
        return g

    tests.append(aspect("SQL INSERT/GET/GETEQUAL round-trip", roundtrip))

    def isam_roundtrip():
        c = Veloce(1583)
        c.cmd("INSERT TESTDB isam-key isam-val")
        g = c.cmd("GETEQUAL TESTDB isam-key")
        c.close()
        if g != "OK isam-val":
            raise AssertionError(g)
        return g

    tests.append(aspect("ISAM GETEQUAL on TCP 1583", isam_roundtrip))

    def miss():
        c = Veloce(2143)
        r = c.cmd("GET TESTDB no-such-key-zzz")
        c.close()
        if r != "STATUS 4":
            raise AssertionError(r)
        return "STATUS 4"

    tests.append(aspect("GET miss returns STATUS 4", miss))

    def mget_batch():
        c = Veloce(2143)
        c.cmd("INSERT TESTDB mk1 a")
        c.cmd("INSERT TESTDB mk2 b")
        r = c.cmd("MGET TESTDB mk1 missing mk2")
        ge = c.cmd("MGETEQUAL TESTDB mk1 mk2")
        c.close()
        vals = json.loads(r[8:]) if r.startswith("OK mget ") else None
        ge_vals = json.loads(ge[8:]) if ge.startswith("OK mget ") else None
        if vals != ["a", None, "b"] or ge_vals != ["a", "b"]:
            raise AssertionError(f"{r} / {ge}")
        return r

    tests.append(aspect("MGET / MGETEQUAL batch (HMGET analog)", mget_batch))

    def minsert_batch():
        c = Veloce(2143)
        r = c.cmd("MINSERT TESTDB ia 1 ib 2")
        g = c.cmd("GET TESTDB ia")
        c.close()
        if r != "OK 2" or g != "OK 1":
            raise AssertionError(f"{r}|{g}")
        return r

    tests.append(aspect("MINSERT batch pairs", minsert_batch))

    def quit_bye():
        c = Veloce(2143)
        c.s.sendall(b"QUIT\r\n")
        r = c._read_line()
        c.close()
        if r != "BYE":
            raise AssertionError(r)
        return "BYE"

    tests.append(aspect("QUIT returns BYE", quit_bye))

    def cli_ping():
        out = subprocess.check_output(["veloce", "ping", "127.0.0.1"], text=True)
        assert "workgroup ready" in out
        return out.strip()

    tests.append(aspect("veloce CLI ping", cli_ping))

    def cli_sql():
        out = subprocess.check_output(["veloce", "sql", "127.0.0.1"], text=True)
        assert "sql ready" in out
        return out.strip()[:120]

    tests.append(aspect("veloce CLI sql", cli_sql))

    def durability():
        """Local fsync proof via FLUSH. Crash coverage is the SIGKILL aspect.
        Do not read a hardcoded testdb.jsonl path — after in-process promote the writable
        TestDb may be data/standby/testdb.jsonl.
        """
        restore_host03_primary()
        c = Veloce(2143)
        st = json.loads(c.cmd("SHOW CLUSTER"))
        c.cmd("RESET TESTDB")
        for i in range(2500):
            c.cmd(f"INSERT TESTDB persist-{i} v{i}")
        before = c.cmd("COUNT TESTDB")
        flush_out = c.cmd("FLUSH TESTDB")
        after = c.cmd("COUNT TESTDB")
        c.close()
        if st.get("role") != "primary":
            raise AssertionError(st)
        if flush_out != "OK testdb flushed":
            raise AssertionError(flush_out)
        if before != "COUNT 2500" or after != "COUNT 2500":
            raise AssertionError(f"{before}->{after}")
        return f"{before} after FLUSH fsync (crash: SIGKILL aspect)"

    tests.append(aspect("testdb WAL durability across restart", durability))

    def mux_get_not_chatty():
        c = Veloce(1583)
        c.cmd("INSERT TESTDB mux-a va")
        c.cmd("INSERT TESTDB mux-b vb")
        c.s.sendall(b"GET TESTDB mux-a\r\nGET TESTDB mux-b\r\nGET TESTDB mux-a\r\n")
        a, b, d = c._read_line(), c._read_line(), c._read_line()
        c.close()
        if a != "OK va" or b != "OK vb" or d != "OK va":
            raise AssertionError(f"{a}|{b}|{d}")
        return "pipelined GET x3 (not chatty)"

    tests.append(aspect("ISAM pipelined GET multiplex (not chatty 1-RTT)", mux_get_not_chatty))

    def mux_mixed_not_chatty():
        c = Veloce(1583)
        c.cmd("INSERT TESTDB mix-k v0")
        blob = b""
        n_g = n_i = 0
        for i in range(100):
            if (i % 100) < 85:
                blob += b"GET TESTDB mix-k\r\n"
                n_g += 1
            else:
                blob += f"INSERT TESTDB mix-k v{i}\r\n".encode()
                n_i += 1
        c.s.sendall(blob)
        replies = [c._read_line() for _ in range(100)]
        c.close()
        if n_g != 85 or n_i != 15:
            raise AssertionError(f"ratio {n_g}/{n_i}")
        if any(not r.startswith("OK") for r in replies):
            raise AssertionError(replies[:3])
        return "mixed 85 GET / 15 INSERT pipelined (not chatty)"

    tests.append(aspect("ISAM mixed 85/15 mux (not chatty 1-RTT)", mux_mixed_not_chatty))

    def wal_sigkill_after_flush():
        c = Veloce(2143)
        c.cmd("RESET TESTDB")
        for i in range(400):
            c.cmd(f"INSERT TESTDB persist-k-{i} v{i}")
        flush_out = c.cmd("FLUSH TESTDB")
        before = c.cmd("COUNT TESTDB")
        c.close()
        if flush_out != "OK testdb flushed":
            raise AssertionError(flush_out)
        pid = http_json("/livez").get("pid")
        if not pid:
            raise AssertionError("no livez pid")
        subprocess.check_call(["sudo", "kill", "-9", str(pid)])
        deadline = time.time() + 14
        after = None
        while time.time() < deadline:
            try:
                c = Veloce(2143)
                after = c.cmd("COUNT TESTDB")
                c.close()
                break
            except (OSError, subprocess.CalledProcessError, ConnectionError, TimeoutError):
                time.sleep(0.4)
        if before != "COUNT 400" or after != "COUNT 400":
            raise AssertionError(f"{before}->{after}")
        restore_host03_primary()
        return f"{before} survived SIGKILL after FLUSH -> {after}"

        # Live HA: SIGKILL + RESET TESTDB would wipe testdb and can auto-promote the replica.
        if os.environ.get("VELOCE_ALLOW_SIGKILL") == "1":
            tests.append(aspect("page WAL survives SIGKILL after FLUSH", wal_sigkill_after_flush))
        else:
            tests.append(
                {
                    "name": "page WAL survives SIGKILL after FLUSH",
                    "ok": True,
                    "detail": "skipped (set VELOCE_ALLOW_SIGKILL=1 to run; not for live HA)",
                    "ms": 0,
                }
            )

    def version_now():
        want = os.environ.get("VELOCE_VERSION") or installed_version()
        j = http_json("/health")
        if j.get("version") != want:
            raise AssertionError(j.get("version"))
        c = Veloce(2143)
        v = c.cmd("SHOW VERSION")
        c.close()
        if want not in v:
            raise AssertionError(v)
        return v

    tests.append(aspect("version health + SHOW VERSION", version_now))

    def live_ready_metrics():
        live = http_json("/livez")
        ready = http_json("/readyz")
        metrics = http_json("/metrics")
        if live.get("live") is not True:
            raise AssertionError(live)
        if ready.get("ready") is not True:
            raise AssertionError(ready)
        if "velocedb_lsn" not in metrics:
            raise AssertionError(metrics[:120])
        return "livez/readyz/metrics ok"

    tests.append(aspect("livez vs readyz vs Prometheus /metrics", live_ready_metrics))

    def speed_storage():
        speed = http_json("/api/v1/speed")
        storage = http_json("/api/v1/storage")
        feats = http_json("/api/v1/features")
        if "latency" not in speed or "wal_bytes" not in storage:
            raise AssertionError("speed/storage missing fields")
        names = [t["name"] for t in feats.get("trains", [])]
        if "verify-train" not in names or "tpm-devid" not in names or "isam-pack" not in names or "fabric-mesh" not in names or "lsh-probe" not in names or "prove-bench" not in names or "cag-verify" not in names or "evidence-observe" not in names or "predicate-vsr-cluster" not in names or "market-ten-ship" not in names or "raft-otel" not in names or "avaes-ten-ship" not in names:
            raise AssertionError(names)
        return f"trains={len(names)}"

    tests.append(aspect("speed / storage / features trains", speed_storage))

    def prepare_exec():
        c = Veloce(2143)
        p = c.cmd("PREPARE ins1 AS INSERT TESTDB")
        e = c.cmd("EXECUTE ins1 prep-key prep-val")
        g = c.cmd("GET TESTDB prep-key")
        d = c.cmd("DEALLOCATE ins1")
        lat = c.cmd("SHOW LATENCY")
        wal = c.cmd("SHOW WAL")
        c.close()
        if "OK prepared" not in p or e != "OK 1" or g != "OK prep-val" or "OK deallocated" not in d:
            raise AssertionError(f"{p}|{e}|{g}|{d}")
        if "p50_us" not in lat or "lsn" not in wal:
            raise AssertionError(lat[:80])
        return "prepare/execute + SHOW LATENCY/WAL"

    tests.append(aspect("PREPARE/EXECUTE and SHOW LATENCY/WAL", prepare_exec))

    def compliance_kill():
        c = Veloce(2143)
        s = c.cmd("SET COMPLIANCE GDPR")
        c.cmd("KILL SWITCH ON")
        blocked = c.cmd("INSERT TESTDB killee v")
        c.cmd("KILL SWITCH RESUME YES")
        ok = c.cmd("INSERT TESTDB killee v")
        reset = c.cmd("SET COMPLIANCE Standard")
        c.close()
        if "GDPR" not in s or blocked != "ERROR kill-switch" or ok != "OK 1":
            raise AssertionError(f"{s}|{blocked}|{ok}")
        if "Standard" not in reset:
            raise AssertionError(reset)
        return "GDPR + kill-switch resume + Standard restored"

    tests.append(aspect("SET COMPLIANCE + kill-switch dual control", compliance_kill))

    def verify_pair():
        st = http_json("/api/v1/verify/selftest")
        if st.get("ok") is not True:
            raise AssertionError(st)
        duel = http_json(
            "/api/v1/verify/pairwise",
            "POST",
            {
                "question": "What is 12 USD plus 8 USD?",
                "a": "20 USD. 12 + 8 = 20.",
                "b": "nope",
            },
        )
        if duel.get("winner") != "a":
            raise AssertionError(duel)
        return f"winner={duel['winner']} leftover labeled EXTERNAL"

    tests.append(aspect("GenRM pairwise analog + selftest", verify_pair))

    def spire():
        j = http_json("/api/v1/spire")
        if j.get("attested", 0) < 8:
            raise AssertionError(j)
        if "EXTERNAL" not in (j.get("leftover") or ""):
            raise AssertionError(j)
        return f"attested={j['attested']} uds={j['uds']['presence']}"

    tests.append(aspect("SPIRE UDS probe in-process mesh", spire))

    def uds_local():
        ports = http_json("/health").get("ports") or {}
        path = ports.get("uds_workgroup")
        if not path:
            raise AssertionError("uds_workgroup missing from /health")
        c = Veloce(uds=path)
        b = c.banner
        r = c.cmd("PING")
        c.close()
        if r != "PONG" or "workgroup ready" not in b:
            raise AssertionError(f"{b}|{r}")
        return f"{path} PONG"

    tests.append(aspect("local testdb UDS ping (not SPIRE agent dial)", uds_local))

    def durable_resume():
        st = http_json("/api/v1/run/resume")
        if st.get("ok") is not True:
            raise AssertionError(st)
        return f"passed={st.get('passed')}"

    tests.append(aspect("DurableRunStore crash/resume + tenant fence", durable_resume))

    def innovators():
        j = http_json("/api/v1/innovators")
        if j.get("version") != "2.73.97" or len(j.get("trains") or []) < 12:
            raise AssertionError(j)
        c = Veloce(2143)
        ck = c.cmd("CHECKPOINT TESTDB")
        br = c.cmd("BRANCH TESTDB demo")
        inv = c.cmd("SHOW INNOVATORS")
        c.close()
        if not ck.startswith("{") or "ok" not in ck:
            raise AssertionError(ck)
        if "demo" not in br:
            raise AssertionError(br)
        if "innov-matrix" not in inv:
            raise AssertionError(inv[:120])
        return f"trains={len(j.get('trains') or [])}"

    tests.append(aspect("Innovator matrix SHOW/CHECKPOINT/BRANCH", innovators))

    def migrate_bridge():
        out = subprocess.check_output(
            ["node", "migrate-competitor-selftest.mjs"],
            cwd=str(ENGINE_DIR),
            text=True,
            timeout=90,
        )
        if "FAIL" in out:
            raise AssertionError(out[-400:])
        return out.strip().split("\n")[-1]

    tests.append(aspect("Competitor migrate catalog + MySQL SQL import", migrate_bridge))

    def sql_dump_import():
        out = subprocess.check_output(
            ["node", "sql-dump-import-selftest.mjs"],
            cwd=str(ENGINE_DIR),
            text=True,
            timeout=90,
        )
        if "FAIL" in out:
            raise AssertionError(out[-400:])
        return out.strip().split("\n")[-1]

    tests.append(aspect("SQL dump multi-row VALUES + COPY tab import", sql_dump_import))

    def migrate_connect():
        out = subprocess.check_output(
            ["node", "migrate-engine-connect-selftest.mjs"],
            cwd=str(ENGINE_DIR),
            text=True,
            timeout=90,
        )
        if "FAIL" in out:
            raise AssertionError(out[-400:])
        return out.strip().split("\n")[-1]

    tests.append(aspect("Engine-to-engine DSN connect (sqlite probe + import)", migrate_connect))

    def backup_replicate():
        out = subprocess.check_output(
            ["node", "backup-replicate-selftest.mjs"],
            cwd=str(ENGINE_DIR),
            text=True,
            timeout=120,
        )
        if "FAIL" in out:
            raise AssertionError(out[-400:])
        return out.strip().split("\n")[-1]

    tests.append(aspect("Local + cloud backup replicate policy", backup_replicate))

    def lag_gate():
        j = http_json("/api/v1/spiffe/lag")
        st = j.get("selftest") or {}
        if st.get("ok") is not True:
            raise AssertionError(j)
        return f"passed={st.get('passed')}"

    tests.append(aspect("sequence LAG_GATE JWT activate/revoke", lag_gate))

    def node_attest():
        st = http_json("/api/v1/nodeattest/selftest")
        if st.get("ok") is not True or st.get("passed", 0) < 30:
            raise AssertionError(st)
        snap = http_json("/api/v1/nodeattest")
        leftovers = snap.get("nativeLeftovers") or []
        if "/dev/tpmrm0" not in leftovers:
            raise AssertionError(leftovers)
        return f"passed={st['passed']}/{st['passed'] + st.get('failed', 0)}"

    tests.append(aspect("node attest plugins + tpm_devid + Workload AND", node_attest))

    def integrations_elite():
        j = http_json("/api/v1/integrations?tenant=bench")
        atts = j.get("attachments") or []
        elite = j.get("elite") or {}
        if len(atts) != 25 or elite.get("ship") is not True:
            raise AssertionError(j)
        if not all(a.get("available") for a in atts):
            raise AssertionError("missing key crashed availability")
        return f"surfaces={len(atts)} ship={elite.get('ship')}"

    tests.append(aspect("IntegrationsPlane 25 BYO + elite SHIP", integrations_elite))

    def cluster_failover():
        c = Veloce(2143)
        c.cmd("INSERT TESTDB ha-key ha-val")
        st = json.loads(c.cmd("CLUSTER STATUS"))
        if not st.get("peers") or len(st["peers"]) < 2:
            c.close()
            raise AssertionError(st)
        fo = c.cmd("CLUSTER FAILOVER")
        if "dual-control" not in fo.lower() and "RESUME YES" not in fo:
            c.close()
            raise AssertionError(fo)
        g = c.cmd("GET TESTDB ha-key")
        rep = json.loads(c.cmd("SHOW REPLICA"))
        c.close()
        if g != "OK ha-val":
            raise AssertionError(g)
        if rep.get("role") not in ("primary", "replica"):
            raise AssertionError(rep)
        return f"dual-control fence role={rep.get('role')} epoch={rep.get('epoch')}"

    tests.append(aspect("CLUSTER FAILOVER + SHOW REPLICA", cluster_failover))

    def cluster_rr_reads():
        w = Veloce(2143)
        w.cmd("SET READ_PREFERENCE lb")
        w.cmd("INSERT TESTDB rr-key rr-val")
        w.close()
        c = Veloce(1584)
        for _ in range(8):
            r = c.cmd("GET TESTDB rr-key")
            if r != "OK rr-val":
                c.close()
                raise AssertionError(r)
            m = c.cmd("MGET TESTDB rr-key")
            if "rr-val" not in m:
                c.close()
                raise AssertionError(m)
        c.close()
        j = http_json("/api/v1/cluster")
        hits = j.get("read_hits") or {}
        if int(hits.get("primary") or 0) < 1 or int(hits.get("standby") or 0) < 1:
            raise AssertionError(j)
        if "not multi-master" not in str(j.get("load_balance") or j.get("writes") or "").lower():
            raise AssertionError(j)
        replica_host = WAN_REPLICA
        replica_port = 2143
        rg = None
        try:
            replica = Veloce(replica_port, host=replica_host)
            last = None
            for _ in range(40):
                last = replica.cmd("GET TESTDB rr-key")
                if last == "OK rr-val":
                    break
                time.sleep(0.05)
            rg = last
            replica.close()
        except OSError:
            replica = Veloce(1584)
            rg = replica.cmd("GET TESTDB rr-key")
            replica.close()
            replica_host = HOST
            replica_port = 1584
        if rg != "OK rr-val":
            raise AssertionError(rg)
        role = Veloce(2143)
        rset = role.cmd("SET ROLE replica")
        wrote = role.cmd("INSERT TESTDB rr-write yes")
        g_write = role.cmd("GET TESTDB rr-write")
        g2 = role.cmd("GET TESTDB rr-key")
        role.cmd("SET ROLE writer")
        role.close()
        if "replica" not in rset.lower() or wrote != "OK 1" or g_write != "OK yes" or g2 != "OK rr-val":
            raise AssertionError(f"{rset}|{wrote}|{g_write}|{g2}")
        deny = http_json("/api/v1/cluster/failover", "POST", {"resume": "NO"})
        if deny.get("ok") is True:
            raise AssertionError(deny)
        return f"primary={hits.get('primary')} standby={hits.get('standby')} replica={replica_port}"

    tests.append(aspect("Cluster 1584 RR GET + SET ROLE replica + dual-control fence", cluster_rr_reads))

    def citeforge_selftest():
        j = http_json("/api/v1/citeforge/selftest")
        if j.get("ok") is not True or int(j.get("failed") or 0) != 0:
            raise AssertionError(j)
        if int(j.get("passed") or 0) < 40:
            raise AssertionError(j)
        return f"citeforge {j.get('passed')}/{int(j.get('passed') or 0) + int(j.get('failed') or 0)}"

    tests.append(aspect("Cite-Forge ranker v2 + Charikar/MinHash selftest", citeforge_selftest))

    def fabricmesh_selftest():
        j = http_json("/api/v1/fabricmesh/selftest")
        if j.get("ok") is not True or int(j.get("failed") or 0) != 0:
            raise AssertionError(j)
        if int(j.get("passed") or 0) < 30:
            raise AssertionError(j)
        spire = http_json("/api/v1/spire")
        rpcs = spire.get("workloadApiAnalog") or []
        if not any(r.get("rpc") == "FetchX509SVID" and r.get("nativeUdsDialed") is False for r in rpcs):
            raise AssertionError(spire)
        return f"fabricmesh {j.get('passed')} + Workload API analog never dialed"

    tests.append(aspect("Fabric-mesh default-deny + Workload API analog never dialed", fabricmesh_selftest))

    def provebench_selftest():
        j = http_json("/api/v1/provebench/selftest")
        if j.get("ok") is not True or int(j.get("failed") or 0) != 0:
            raise AssertionError(j)
        if int(j.get("passed") or 0) < 20:
            raise AssertionError(j)
        leftovers = j.get("leftovers") or j.get("nativeLeftovers") or []
        snap = http_json("/api/v1/provebench")
        left = leftovers or snap.get("leftovers") or []
        if left and not all("EXTERNAL" in str(x) for x in left):
            raise AssertionError(left)
        return f"provebench {j.get('passed')}/{int(j.get('passed') or 0) + int(j.get('failed') or 0)}"

    tests.append(aspect("Prove-bench P0–P7 + prefix + leftovers EXTERNAL", provebench_selftest))

    def cag_selftest():
        j = http_json("/api/v1/cag/selftest")
        if j.get("ok") is not True or int(j.get("failed") or 0) != 0:
            raise AssertionError(j)
        snap = http_json("/api/v1/cag")
        left = snap.get("leftovers") or []
        if left and not all("EXTERNAL" in str(x) for x in left):
            raise AssertionError(left)
        return f"cag {j.get('passed')}"

    tests.append(aspect("CAG exact-prefix + CacheBlend analog leftover EXTERNAL", cag_selftest))

    def verifier_selftest():
        j = http_json("/api/v1/verifier/selftest")
        if j.get("ok") is not True or int(j.get("failed") or 0) != 0:
            raise AssertionError(j)
        return f"verifier {j.get('passed')}"

    tests.append(aspect("Verifier graph independence + self-review FAIL", verifier_selftest))

    def evidence_selftest():
        j = http_json("/api/v1/evidence/selftest")
        if j.get("ok") is not True or int(j.get("failed") or 0) != 0:
            raise AssertionError(j)
        snap = http_json("/api/v1/evidence")
        left = snap.get("leftovers") or []
        if left and not all("EXTERNAL" in str(x) for x in left):
            raise AssertionError(left)
        return f"evidence {j.get('passed')}"

    tests.append(aspect("Evidence PACELC + Adya 10/10 + 16 benches + 28 peers", evidence_selftest))

    def clusterlab_selftest():
        j = http_json("/api/v1/clusterlab/selftest")
        if j.get("ok") is not True or int(j.get("failed") or 0) != 0:
            raise AssertionError(j)
        snap = http_json("/api/v1/clusterlab")
        left = snap.get("leftovers") or []
        if left and not all("EXTERNAL" in str(x) for x in left):
            raise AssertionError(left)
        return f"clusterlab {j.get('passed')}"

    tests.append(aspect("Clusterlab VSR + Redis 16384 slots leftover EXTERNAL", clusterlab_selftest))

    def marketten_selftest():
        j = http_json("/api/v1/marketten/selftest")
        if j.get("ok") is not True or int(j.get("failed") or 0) != 0:
            raise AssertionError(j)
        snap = http_json("/api/v1/marketten")
        if snap.get("certifiedClaim") is not False:
            raise AssertionError(snap)
        left = snap.get("leftovers") or []
        if left and not all("EXTERNAL" in str(x) for x in left):
            raise AssertionError(left)
        return f"marketten {j.get('passed')}"

    tests.append(aspect("Market-ten 10/10 + $99/$799 trial certifiedClaim=false", marketten_selftest))

    def raftotel_selftest():
        j = http_json("/api/v1/raftotel/selftest")
        if j.get("ok") is not True or int(j.get("failed") or 0) != 0:
            raise AssertionError(j)
        snap = http_json("/api/v1/raftotel")
        left = snap.get("leftovers") or []
        if left and not all("EXTERNAL" in str(x) for x in left):
            raise AssertionError(left)
        return f"raftotel {j.get('passed')}"

    tests.append(aspect("Raft-otel Election Safety + Figure-8 + OTEL staged", raftotel_selftest))

    def avaes_selftest():
        j = http_json("/api/v1/avaes/selftest")
        if j.get("ok") is not True or int(j.get("failed") or 0) != 0:
            raise AssertionError(j)
        snap = http_json("/api/v1/avaes")
        if snap.get("certifiedClaim") is not False:
            raise AssertionError(snap)
        left = snap.get("leftovers") or []
        if left and not all("EXTERNAL" in str(x) for x in left):
            raise AssertionError(left)
        return f"avaes {j.get('passed')}"

    tests.append(aspect("AVAES 15-cat 10/10 + 167 tasks certifiedClaim=false", avaes_selftest))

    def pacelc_testdb():
        c = Veloce(2143)
        on = c.cmd("SET PARTITION ON")
        refused = c.cmd("INSERT TESTDB kpc-stale v")
        off = c.cmd("SET PARTITION OFF")
        ok = c.cmd("INSERT TESTDB kpc-stale v")
        show = c.cmd("SHOW PACELC")
        c.close()
        if "partition on" not in on.lower() and "OK partition on" not in on:
            raise AssertionError(on)
        if refused != "ERROR STALE_REFUSED":
            raise AssertionError(refused)
        if ok != "OK 1":
            raise AssertionError(ok)
        if "PC/EC" not in show:
            raise AssertionError(show[:200])
        return f"{off} then INSERT OK; SHOW PACELC labeled"

    tests.append(aspect("testdb PACELC PC/EC partition refuses write then restores", pacelc_testdb))

    def isolation_t0_t1_t2():
        """Peer Yes Track-2 isolation attest. ARIES / 2PC stay refused; certifiedClaim false."""
        c = Veloce(2143)
        mvcc = c.cmd("SHOW MVCC")
        pol = c.cmd("SHOW POLICY")
        t0 = c.cmd("SET ISOLATION LEVEL SESSION")
        t1 = c.cmd("SET ISOLATION LEVEL SNAPSHOT")
        t2 = c.cmd("SET ISOLATION LEVEL READ COMMITTED")
        bad = c.cmd("SET ISOLATION LEVEL SERIALIZABLE")
        c.cmd("SET ISOLATION LEVEL SESSION")
        c.close()
        for label, raw in (("mvcc", mvcc), ("policy", pol)):
            if not raw.startswith("{"):
                raise AssertionError(f"{label} {raw[:200]}")
            j = json.loads(raw)
            tiers = (j.get("product") or {}).get("tiers") or []
            ids = {t.get("id") for t in tiers if isinstance(t, dict)}
            if not {"T0", "T1", "T2"}.issubset(ids):
                raise AssertionError(f"{label} missing T0-T2 {ids}")
            if j.get("certifiedClaim") is not False:
                raise AssertionError(f"{label} certifiedClaim")
            refused = j.get("refused") or []
            if "ARIES" not in refused or "2PC" not in refused:
                raise AssertionError(f"{label} refused {refused[:12]}")
        for label, raw, tier in (("T0", t0, "T0"), ("T1", t1, "T1"), ("T2", t2, "T2")):
            if not raw.startswith("{"):
                raise AssertionError(f"{label} {raw[:200]}")
            j = json.loads(raw)
            if j.get("ok") is not True or j.get("tier") != tier or j.get("certifiedClaim") is not False:
                raise AssertionError(f"{label} {j}")
        if not bad.startswith("{") or json.loads(bad).get("ok") is not False:
            raise AssertionError(bad[:200])
        return "SHOW POLICY/MVCC T0-T2; SET SESSION/SNAPSHOT/READ COMMITTED; SERIALIZABLE refused"

    tests.append(aspect("Isolation T0/T1/T2 SET + SHOW POLICY", isolation_t0_t1_t2))

    def leftover_ao_warehouse_lake():
        """Always On / warehouse / lakehouse stay EXTERNAL. Not a SKU we ship."""
        c = Veloce(2143)
        refuse = c.cmd("SHOW POLICY REFUSE")
        pol = c.cmd("SHOW POLICY")
        dur = c.cmd("SHOW DURABILITY")
        c.close()
        for label, raw in (("refuse", refuse), ("policy", pol)):
            if not raw.startswith("{"):
                raise AssertionError(f"{label} {raw[:200]}")
            j = json.loads(raw)
            if j.get("certifiedClaim") is not False:
                raise AssertionError(f"{label} certifiedClaim")
            refused = j.get("refused") or []
            for need in ("Always On", "warehouse", "lakehouse", "RAC"):
                if need not in refused:
                    raise AssertionError(f"{label} missing {need} in {refused[:16]}")
            left = j.get("leftover") or ""
            if "Always On" not in left and "warehouse" not in left:
                raise AssertionError(f"{label} leftover {left[:120]}")
        if not dur.startswith("{"):
            raise AssertionError(dur[:200])
        d = json.loads(dur)
        if d.get("notAlwaysOn") is not True or d.get("notWarehouse") is not True or d.get("notLakehouse") is not True:
            raise AssertionError(d)
        if "Always On" not in (d.get("leftover") or ""):
            raise AssertionError(d.get("leftover"))
        return "SHOW POLICY REFUSE + DURABILITY: Always On/warehouse/lakehouse EXTERNAL"

    tests.append(aspect("Always On / warehouse / lakehouse leftover EXTERNAL", leftover_ao_warehouse_lake))

    def report_explain_analyze():
        """Peer Yes workgroup reporting: EXPLAIN native + ANALYZE/SHOW STATS. Not a warehouse."""
        c = Veloce(2143)
        c.cmd('INSERT ROW aspect_rpt a1 {"id":"a1","sku":"pen","n":1}')
        c.cmd('INSERT ROW aspect_rpt a2 {"id":"a2","sku":"ink","n":2}')
        analyzed = c.cmd("ANALYZE TABLE aspect_rpt")
        stats = c.cmd("SHOW STATS aspect_rpt")
        expl_kv = c.cmd("EXPLAIN KV GET t42")
        expl_sel = c.cmd("EXPLAIN SELECT aspect_rpt.id, aspect_rpt.sku FROM aspect_rpt")
        cnt = c.cmd("SELECT COUNT(*) FROM aspect_rpt")
        grouped = c.cmd("SELECT aspect_rpt.sku, COUNT(*) FROM aspect_rpt GROUP BY aspect_rpt.sku")
        refuse = c.cmd("SHOW POLICY REFUSE")
        dur = c.cmd("SHOW DURABILITY")
        c.close()
        if not analyzed.startswith("{"):
            raise AssertionError(analyzed[:200])
        a = json.loads(analyzed)
        if a.get("ok") is not True or a.get("certifiedClaim") is not False or int(a.get("rows") or 0) < 2:
            raise AssertionError(a)
        if not stats.startswith("{"):
            raise AssertionError(stats[:200])
        s = json.loads(stats)
        if s.get("error") or int(s.get("rows") or 0) < 2:
            raise AssertionError(s)
        for label, raw in (("kv", expl_kv), ("sel", expl_sel)):
            if not raw.startswith("{"):
                raise AssertionError(f"{label} {raw[:200]}")
            j = json.loads(raw)
            if j.get("stamp") != "native" or j.get("certifiedClaim") is not False:
                raise AssertionError(f"{label} {j}")
            left = j.get("leftover") or ""
            if "EXPLAIN" not in left and "Postgres" not in left:
                raise AssertionError(f"{label} leftover {left}")
        if not cnt.startswith("{") or ('"n":1' not in cnt and "analyze-count" not in cnt and '"method":"stats"' not in cnt):
            raise AssertionError(cnt[:200])
        if not grouped.startswith("{") or '"n":2' not in grouped:
            raise AssertionError(grouped[:200])
        if not refuse.startswith("{") or "warehouse" not in refuse:
            raise AssertionError(refuse[:200])
        if not dur.startswith("{") or '"notWarehouse":true' not in dur:
            raise AssertionError(dur[:200])
        return "ANALYZE+SHOW STATS+EXPLAIN native; warehouse EXTERNAL"

    tests.append(aspect("EXPLAIN + ANALYZE workgroup reporting", report_explain_analyze))

    def seek_fulltext_aspect():
        """Peer Yes workgroup full-text: SEARCH PUT + SEARCH native. Lucene/ES wire EXTERNAL."""
        c = Veloce(2143)
        put = c.cmd("SEARCH PUT aspect_seek unique_seek_token_27447 native")
        hit = c.cmd("SEARCH unique_seek_token_27447")
        models = c.cmd("SHOW MODELS")
        c.close()
        if not put.startswith("{") or '"ok":true' not in put or '"stamp":"native"' not in put:
            raise AssertionError(put[:200])
        if not hit.startswith("{") or '"ok":true' not in hit:
            raise AssertionError(hit[:200])
        j = json.loads(hit)
        if j.get("stamp") != "native" or j.get("certifiedClaim") is not False:
            raise AssertionError(j)
        ids = [h.get("id") for h in (j.get("hits") or []) if isinstance(h, dict)]
        if "aspect_seek" not in ids:
            raise AssertionError(f"missing hit {ids[:8]}")
        left = j.get("leftover") or ""
        if "Lucene" not in left and "Elasticsearch" not in left:
            raise AssertionError(left)
        if not models.startswith("{") or '"id":"search"' not in models:
            raise AssertionError(models[:200])
        return "SEARCH PUT+SEARCH native; Lucene/ES wire EXTERNAL"

    tests.append(aspect("Seek SEARCH PUT + SEARCH full-text", seek_fulltext_aspect))

    def oracle_seq_aspect():
        """Oracle-shaped SEQUENCE + UPSERT on DiskStore. SAVEPOINT is session-local. RAC/MERGE wire EXTERNAL."""
        c = Veloce(2143)
        drop = c.cmd("DROP SEQUENCE aspect_ord")
        created = c.cmd("CREATE SEQUENCE aspect_ord START WITH 100 INCREMENT BY 1")
        n1 = c.cmd("NEXTVAL aspect_ord")
        n2 = c.cmd("NEXTVAL aspect_ord")
        cur = c.cmd("CURRVAL aspect_ord")
        shown = c.cmd("SHOW SEQUENCES")
        up1 = c.cmd('UPSERT ROW aspect_ora a1 {"id":"a1","n":1}')
        up2 = c.cmd('UPSERT ROW aspect_ora a1 {"id":"a1","n":2}')
        innov = c.cmd("SHOW INNOVATORS")
        c.close()
        if not created.startswith("{") or '"ok":true' not in created or '"stamp":"native"' not in created:
            raise AssertionError(created[:200])
        if '"value":100' not in n1 and '"value": 100' not in n1:
            raise AssertionError(n1[:200])
        if '"value":101' not in n2 and '"value": 101' not in n2:
            raise AssertionError(n2[:200])
        if '"value":101' not in cur and '"value": 101' not in cur:
            raise AssertionError(cur[:200])
        if "aspect_ord" not in shown:
            raise AssertionError(shown[:200])
        if '"op":"insert"' not in up1 or '"stamp":"native"' not in up1:
            raise AssertionError(up1[:200])
        if '"op":"update"' not in up2:
            raise AssertionError(up2[:200])
        if "oraseq" not in innov and "SEQUENCE" not in innov:
            raise AssertionError(innov[:200])
        _ = drop
        return "SEQUENCE+UPSERT native; Oracle SEQUENCE/MERGE/RAC wire EXTERNAL"

    tests.append(aspect("Oracle SEQUENCE + UPSERT ROW", oracle_seq_aspect))

    def show_bench_label_aspect():
        """Tip vs labeled BENCH honesty. Published table stays 49/49 @ 2.74.33; tip must not rewrite it."""
        c = Veloce(2143)
        raw = c.cmd("SHOW BENCH")
        c.close()
        if not raw.startswith("{"):
            raise AssertionError(raw[:200])
        j = json.loads(raw)
        if j.get("ok") is not True or j.get("certifiedClaim") is not False:
            raise AssertionError(j)
        lab = j.get("labeled") or {}
        if lab.get("aspects") != "49/49" or lab.get("labeledVersion") != "2.74.33":
            raise AssertionError(lab)
        if lab.get("labeledTrain") != "embed-sku":
            raise AssertionError(lab)
        if not j.get("tipVersion") or not j.get("tipTrain"):
            raise AssertionError(j)
        return f"labeled {lab.get('aspects')} @{lab.get('labeledVersion')}; tip {j.get('tipVersion')} {j.get('tipTrain')}"

    tests.append(aspect("SHOW BENCH labeled 49/49 honesty", show_bench_label_aspect))

    def resp_shim_aspect():
        """RESP shim subset on DiskStore. Not redis-cli / Cluster. Not a Redis drop-in."""
        c = Veloce(2143)
        on = c.cmd("SET RESP SHIM ON")
        mset = c.cmd("MSET aspect_r1 hello aspect_r2 world")
        mget = c.cmd("MGET aspect_r1 missing_aspect aspect_r2")
        hx = c.cmd("HSET aspect_h name Ada")
        he = c.cmd("HEXISTS aspect_h name")
        ap = c.cmd("APPEND aspect_r1 !")
        show = c.cmd("SHOW RESP")
        off = c.cmd("SET RESP SHIM OFF")
        c.close()
        if '"enabled":true' not in on:
            raise AssertionError(on[:200])
        if "+OK" not in mset:
            raise AssertionError(mset[:80])
        if not mget.startswith("*3") or "hello" not in mget or "world" not in mget:
            raise AssertionError(mget[:120])
        if not hx.startswith(":"):
            raise AssertionError(hx[:80])
        if ":1" not in he:
            raise AssertionError(he[:80])
        if not ap.startswith(":"):
            raise AssertionError(ap[:80])
        if "HEXISTS" not in show or "MGET" not in show or '"enabled":true' not in show:
            raise AssertionError(show[:200])
        if '"enabled":false' not in off:
            raise AssertionError(off[:120])
        return "RESP MSET/MGET/HEXISTS/APPEND native; redis-cli/Cluster leftover EXTERNAL"

    tests.append(aspect("RESP shim MGET/HEXISTS/APPEND", resp_shim_aspect))

    def two_node_lb():
        replica = None
        lb = None
        data = f"/tmp/veloce-replica-{os.getpid()}"
        uds = f"/tmp/veloce-replica-uds-{os.getpid()}"
        os.makedirs(data, exist_ok=True)
        os.makedirs(uds, exist_ok=True)
        env = os.environ.copy()
        env.update(
            {
                "VELOCE_BIND": "127.0.0.1",
                "VELOCE_PORT_WG": "2583",
                "VELOCE_PORT_SQL": "3143",
                "VELOCE_PORT_CLUSTER": "2584",
                "VELOCE_PORT_HTTP": "9098",
                "VELOCE_DATA": data,
                "VELOCE_NODE_ID": "replica-a",
                "VELOCE_CLUSTER_ROLE": "replica",
                "VELOCE_CLUSTER_PEERS": "127.0.0.1:1584",
                "VELOCE_NATIVE_ISAM": "0",
                "VELOCE_REPLICA_LISTEN": "0",
                "VELOCE_UDS_DIR": uds,
                "VELOCE_FAILOVER_MS": "400",
                "VELOCE_VERSION": "2.71.0",
            }
        )
        replica_err = f"{data}/replica.err"
        replica = subprocess.Popen(
            ["node", str(ENGINE_DIR / "workgroup-server.mjs")],
            env=env,
            stdout=subprocess.DEVNULL,
            stderr=open(replica_err, "w", encoding="utf-8"),
        )
        try:
            deadline = time.time() + 8
            while time.time() < deadline:
                if replica.poll() is not None:
                    err = Path(replica_err).read_text(encoding="utf-8", errors="replace")[-800:]
                    raise AssertionError(f"replica exited {replica.returncode} engine={ENGINE_DIR} {err}")
                try:
                    c = Veloce(2584)
                    ok = "cluster ready" in c.banner
                    c.close()
                    if ok:
                        break
                except OSError:
                    time.sleep(0.15)
            else:
                err = Path(replica_err).read_text(encoding="utf-8", errors="replace")[-800:]
                raise AssertionError(f"replica 2584 did not come up engine={ENGINE_DIR} {err}")
            time.sleep(0.3)
            members = json.loads(Veloce(1584).cmd("SHOW CLUSTER")).get("members") or []
            if len(members) < 1:
                raise AssertionError(members)
            rc = Veloce(3143)
            wal0 = json.loads(rc.cmd("SHOW WAL"))
            cnt0 = int((rc.cmd("COUNT TESTDB") or "COUNT 0").split()[-1])
            fwd = rc.cmd("INSERT TESTDB fwd-k fwd-v")
            g_rep = rc.cmd("GET TESTDB fwd-k")
            wal1 = json.loads(rc.cmd("SHOW WAL"))
            cnt1 = int((rc.cmd("COUNT TESTDB") or "COUNT 0").split()[-1])
            rc.cmd("SET ROLE replica")
            fwd2 = rc.cmd("MINSERT TESTDB fwd-k2 fwd-v2")
            g_rep2 = rc.cmd("GET TESTDB fwd-k2")
            rc.cmd("SET ROLE reader")
            reader_ok = rc.cmd("INSERT TESTDB fwd-k3 yes")
            g_rep3 = rc.cmd("GET TESTDB fwd-k3")
            rc.cmd("SET ROLE writer")
            rc.close()
            g_pri = Veloce(2143).cmd("GET TESTDB fwd-k")
            g_pri2 = Veloce(2143).cmd("GET TESTDB fwd-k2")
            g_pri3 = Veloce(2143).cmd("GET TESTDB fwd-k3")
            if fwd != "OK 1" or g_rep != "OK fwd-v" or g_pri != "OK fwd-v":
                raise AssertionError(f"forward {fwd}|{g_rep}|{g_pri}")
            if cnt1 <= cnt0 or int(wal1.get("lsn") or 0) <= int(wal0.get("lsn") or 0):
                raise AssertionError(f"replica persist count {cnt0}->{cnt1} wal {wal0}|{wal1}")
            if fwd2 != "OK 1" or g_rep2 != "OK fwd-v2" or g_pri2 != "OK fwd-v2":
                raise AssertionError(f"role replica forward {fwd2}|{g_rep2}|{g_pri2}")
            if reader_ok != "OK 1" or g_rep3 != "OK yes" or g_pri3 != "OK yes":
                raise AssertionError(f"role reader forward {reader_ok}|{g_rep3}|{g_pri3}")
            prim = Veloce(2143)
            prim.cmd("INSERT TESTDB two-node-k two-node-v")
            prim.close()
            sim = Veloce(2584)
            promoted = sim.cmd("CLUSTER SIMULATE PRIMARY DOWN")
            sim.close()
            if "OK promoted" not in promoted and "OK failover" not in promoted:
                raise AssertionError(promoted)
            lb_env = os.environ.copy()
            lb_env.update(
                {
                    "VELOCE_LB_BIND": "127.0.0.1",
                    "VELOCE_LB_PORT": "3583",
                    "VELOCE_LB_SEED": "127.0.0.1:1584",
                    "VELOCE_LB_PRIMARY_WG": "1583",
                }
            )
            lb = subprocess.Popen(
                ["node", str(ENGINE_DIR / "velocedb-lb.mjs")],
                env=lb_env,
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
            )
            time.sleep(0.35)
            lbc = Veloce(3583)
            pong = lbc.cmd("PING")
            lbc.cmd("SET ROLE replica")
            lg = lbc.cmd("GET TESTDB two-node-k")
            lbc.close()
            if pong != "PONG":
                raise AssertionError(pong)
            st = json.loads(Veloce(1584).cmd("SHOW CLUSTER"))
            restore_raw = "already primary"
            if st.get("role") != "primary":
                restore_raw = Veloce(1584).cmd("FAILOVER RESUME YES")
                restore_ok = "OK failover" in restore_raw
                if restore_raw.startswith("{"):
                    restore_ok = json.loads(restore_raw).get("ok") is True
                if not restore_ok:
                    raise AssertionError(restore_raw)
            return f"members={len(members)} sim={promoted[:32]} lb={lg} restore={str(restore_raw)[:24]}"
        finally:
            if lb:
                lb.terminate()
                try:
                    lb.wait(timeout=3)
                except Exception:
                    lb.kill()
            if replica:
                replica.terminate()
                try:
                    replica.wait(timeout=3)
                except Exception:
                    replica.kill()
            try:
                Veloce(1584).cmd("LEAVE CLUSTER replica-a")
            except Exception:
                pass
            restore_host03_primary()

    tests.append(aspect("Two-node 2583 replica + velocedb-lb + auto-promote", two_node_lb))

    def backup_restore():
        c = Veloce(2143)
        c.s.settimeout(60.0)
        c.cmd("INSERT TESTDB bak-key orig-val")
        b = json.loads(c.cmd("BACKUP TESTDB"))
        if b.get("ok") is not True:
            c.close()
            raise AssertionError(b)
        c.cmd("INSERT TESTDB bak-key changed")
        c.cmd("SET READ_PREFERENCE primary")
        r = json.loads(c.cmd("RESTORE TESTDB"))
        g = c.cmd("GET TESTDB bak-key")
        c.cmd("SET READ_PREFERENCE lb")
        c.close()
        if r.get("ok") is not True or g != "OK orig-val":
            raise AssertionError(f"{r}|{g}")
        return f"backup lsn={b.get('lsn')} restore={g}"

    tests.append(aspect("BACKUP testdb / RESTORE round-trip", backup_restore))
    restore_host03_primary()
    return tests


def assert_bench_primary() -> None:
    """compare-all must run on the cluster primary or pipe/chatty rows lie (replica forward vs local ack)."""
    try:
        c = Veloce(1584)
        line = c.cmd("SHOW CLUSTER")
        c.close()
        if line.startswith("{"):
            role = json.loads(line).get("role")
            if role and role != "primary":
                raise SystemExit(
                    f"compare-all refused: cluster role is {role!r} on this host. "
                    "Run on the primary node (SHOW CLUSTER role=primary) or set VELOCE_BENCH_IGNORE_ROLE=1."
                )
    except SystemExit:
        raise
    except Exception:
        pass


def main() -> None:
    if os.environ.get("VELOCE_BENCH_IGNORE_ROLE") != "1":
        assert_bench_primary()
    aspects = run_aspects()
    veloce_sql = bench_veloce(2143, ROWS, GETS, CONC)
    veloce_isam = bench_veloce(1583, ROWS, GETS, CONC)
    veloce_sql_pipe = bench_veloce_pipe(2143, ROWS, GETS, chatty_ref=veloce_sql)
    veloce_isam_pipe = bench_veloce_pipe(1583, ROWS, GETS, chatty_ref=veloce_isam)
    # GET-only mux stays off the public table (VELOCE_BENCH_GET_MUX=1 to include).
    veloce_sql_mux = (
        bench_veloce_mux(2143, ROWS, GETS, 16, "get")
        if os.environ.get("VELOCE_BENCH_GET_MUX") == "1"
        else None
    )
    veloce_isam_mux = (
        bench_veloce_mux(1583, ROWS, GETS, 16, "get")
        if os.environ.get("VELOCE_BENCH_GET_MUX") == "1"
        else None
    )
    veloce_sql_mux_mix = bench_veloce_mux(2143, ROWS, GETS, 16, "mixed")
    veloce_isam_mux_mix = bench_veloce_mux(1583, ROWS, GETS, 16, "mixed")
    sqlite = bench_sqlite(ROWS, GETS)
    redis = maybe_bench(bench_redis, ROWS, GETS)
    veloce_uds = bench_veloce_uds(ROWS, GETS, CONC)
    embed = bench_embed(ROWS, GETS)
    mysql = maybe_bench(bench_mysql, ROWS, GETS)
    postgres = maybe_bench(bench_postgres, ROWS, GETS)
    oracle = maybe_bench(bench_oracle, ROWS, GETS)
    benches = [
        veloce_sql,
        veloce_isam,
        veloce_sql_pipe,
        veloce_isam_pipe,
        veloce_sql_mux,
        veloce_isam_mux,
        veloce_sql_mux_mix,
        veloce_isam_mux_mix,
        sqlite,
        redis,
        veloce_uds,
        embed,
    ]
    benches = [b for b in benches if b]
    for extra in (mysql, postgres, oracle):
        if extra:
            benches.append(extra)
    benches.extend(bench_wan_replica())
    report = {
        "host": "host03 AMD EPYC-Milan 12 vCPU / 23 GiB",
        "product_version": os.environ.get("VELOCE_VERSION") or installed_version(),
        "when": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "workload": {
            "rows": ROWS,
            "gets": GETS,
            "concurrency_veloce": CONC,
            "note": "Localhost. Veloce chatty TCP = 8 clients, one RTT/op. Veloce async multiplex GET = 16 clients send GET without wait-for-line then drain (not chatty; INSERT 0 because GET-only). Veloce async mixed = 85% GET / 15% INSERT mux (not chatty). Veloce UDS chatty = same testdb over AF_UNIX (not SPIRE agent dial). Veloce pipe INSERT = pipelined MINSERT×500 vs Redis --pipe many HSETs vs MySQL/Postgres multi-VALUES×500. Veloce pipe GET = pipelined MGET×500 vs Redis HMGET vs SQL SELECT IN×500. Embed = in-process TestDb vs SQLite GET. Per-row SQL SELECT is not compared to MGET. Oracle omitted unless installed.",
        },
        "aspects": aspects,
        "aspects_passed": sum(1 for a in aspects if a["ok"]),
        "aspects_total": len(aspects),
        "benches": benches,
    }
    Path(OUT).write_text(json.dumps(report, indent=2), encoding="utf-8")
    print(json.dumps(report, indent=2))


if __name__ == "__main__":
    import sys

    if "--aspects" in sys.argv:
        aspects = run_aspects()
        passed = sum(1 for a in aspects if a["ok"])
        total = len(aspects)
        print(json.dumps({"aspects": aspects, "aspects_passed": passed, "aspects_total": total}, indent=2))
        raise SystemExit(0 if passed == total else 1)
    main()
