#!/usr/bin/env python3
"""Reproduce write skew in an isolated, disposable PostgreSQL cluster.
Requires PostgreSQL binaries (initdb, pg_ctl, psql) on PATH; Python stdlib only.
Never connects to an existing database. Uses a private Unix socket, no TCP.
Run: python3 ssi-write-skew.py
"""
import json
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
from typing import Any


class Session:
    def __init__(self, socket):
        self.p = subprocess.Popen(
            ['psql', '-X', '-qAt', '-h', socket, '-p', '55439', '-d', 'postgres',
             '-v', 'VERBOSITY=sqlstate'],
            stdin=subprocess.PIPE, stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT, text=True, bufsize=1,
            env={**os.environ, 'PGCONNECT_TIMEOUT': '5'},
        )
        self.run("SET statement_timeout = '5s'; SET lock_timeout = '2s';")

    def run(self, sql):
        assert self.p.stdin is not None and self.p.stdout is not None
        self.p.stdin.write(sql + '\n\\echo __DONE__\n')
        self.p.stdin.flush()
        lines = []
        while True:
            line = self.p.stdout.readline()
            if not line:
                raise RuntimeError('psql closed unexpectedly: ' + '\n'.join(lines))
            if line.strip() == '__DONE__':
                return '\n'.join(lines)
            lines.append(line.rstrip())

    def close(self):
        assert self.p.stdin is not None
        self.p.stdin.close()
        self.p.wait(timeout=10)


def main():
    # Avoid macOS locale initialization spawning threads in the postmaster.
    os.environ["LC_ALL"] = "C"
    for name in ('initdb', 'pg_ctl', 'psql'):
        if not shutil.which(name):
            raise SystemExit(f'Missing PostgreSQL executable: {name}')
    with tempfile.TemporaryDirectory(prefix='ssi-', dir=os.environ.get('TMPDIR')) as tmp:
        data = str(Path(tmp) / 'data')
        log = str(Path(tmp) / 'postgres.log')
        subprocess.run(['initdb', '-D', data, '-A', 'trust', '--no-locale', '-E', 'UTF8'],
                       check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
        started = subprocess.run(['pg_ctl', '-D', data, '-l', log, '-o',
                                  f"-h '' -k {tmp} -p 55439 -c shared_memory_type=mmap", '-w', 'start'],
                                 stdout=subprocess.DEVNULL)
        if started.returncode:
            raise RuntimeError(Path(log).read_text())
        sessions = []
        try:
            admin, a, b = [Session(tmp) for _ in range(3)]
            sessions = [admin, a, b]
            version = admin.run('SHOW server_version;')
            admin.run('CREATE TABLE on_call (name text PRIMARY KEY, active boolean NOT NULL);')
            results = []
            for isolation in ('REPEATABLE READ', 'SERIALIZABLE'):
                for run in range(1, 4):
                    admin.run("TRUNCATE on_call; INSERT INTO on_call VALUES ('Alice', true), ('Bob', true);")
                    a.run(f'BEGIN ISOLATION LEVEL {isolation};')
                    b.run(f'BEGIN ISOLATION LEVEL {isolation};')
                    reads = [a.run('SELECT count(*) FROM on_call WHERE active;'),
                             b.run('SELECT count(*) FROM on_call WHERE active;')]
                    assert reads == ['2', '2'], reads
                    writes = [a.run("UPDATE on_call SET active = false WHERE name = 'Alice' AND (SELECT count(*) FROM on_call WHERE active) > 1;"),
                              b.run("UPDATE on_call SET active = false WHERE name = 'Bob' AND (SELECT count(*) FROM on_call WHERE active) > 1;")]
                    assert writes == ['', ''], writes
                    commits = [a.run('COMMIT;'), b.run('COMMIT;')]
                    remaining = int(admin.run('SELECT count(*) FROM on_call WHERE active;'))
                    if isolation == 'REPEATABLE READ':
                        assert commits == ['', ''] and remaining == 0, (commits, remaining)
                    else:
                        assert commits[0] == '' and '40001' in commits[1] and remaining == 1, (commits, remaining)
                    result: dict[str, Any] = dict(isolation=isolation, run=run, reads=reads,
                                  commits=['ok' if not x else x for x in commits], remaining=remaining)
                    if isolation == 'SERIALIZABLE':
                        b.run('BEGIN ISOLATION LEVEL SERIALIZABLE;')
                        retry_read = b.run('SELECT count(*) FROM on_call WHERE active;')
                        retry_write = b.run("UPDATE on_call SET active = false WHERE name = 'Bob' AND (SELECT count(*) FROM on_call WHERE active) > 1 RETURNING name;")
                        assert retry_read == '1' and retry_write == '', (retry_read, retry_write)
                        assert b.run('COMMIT;') == ''
                        result['retry'] = dict(count=int(retry_read), updated=0, commit='ok')
                    results.append(result)
            # A single rw-antidependency is allowed: A reads the old Bob,
            # B changes Bob, then B commits before A. Serial order can be A, B.
            admin.run('UPDATE on_call SET active = true;')
            a.run('BEGIN ISOLATION LEVEL SERIALIZABLE;')
            assert a.run("SELECT active FROM on_call WHERE name = 'Bob';") == 't'
            b.run('BEGIN ISOLATION LEVEL SERIALIZABLE;')
            assert b.run("UPDATE on_call SET active = false WHERE name = 'Bob';") == ''
            assert b.run('COMMIT;') == ''
            assert a.run('COMMIT;') == ''
            print(json.dumps(dict(postgres=version, write_skew=results,
                                  single_rw_edge=dict(commit_order=['B', 'A'], both_committed=True)), indent=2))
        finally:
            for session in sessions:
                session.close()
            subprocess.run(['pg_ctl', '-D', data, '-m', 'fast', '-w', 'stop'],
                           check=True, stdout=subprocess.DEVNULL)


if __name__ == '__main__':
    main()
