#!/usr/bin/env python3
"""Synthetic cache-publication race lab; Python 3.11+, standard library.

A child captures source revision 1 and its body in one SELECT, then waits on
IPC. The parent acts as B: it commits source 2 and cache 2 before releasing A.
Four cases compare late publication, a source guard, and cache-row deletion.
These are local database writes, not responses served to users. This bounded
exercise makes no distributed freshness, authorization, or load claim.
No network, credentials, timing sleeps, packages, or database-path arguments.
"""
import argparse
import multiprocessing as mp
from pathlib import Path
import sqlite3
import sys
import tempfile
import json

CASES = ("naive", "guarded", "row-only-deleted", "guarded-deleted")
REVISION_1 = {"revision": 1, "body": "Revision 1: inspect the inlet."}
REVISION_2 = {"revision": 2, "body": "Revision 2: inspect the outlet."}
CHILD_TIMEOUT = 10


def require(condition, message):
    if not condition:
        raise RuntimeError(message)


def connect(path):
    db = sqlite3.connect(path, isolation_level=None, timeout=2)
    db.execute("PRAGMA synchronous=FULL")
    return db


def initialize(path):
    db = connect(path)
    try:
        db.executescript("""
            CREATE TABLE source (
                item_id INTEGER PRIMARY KEY, revision INTEGER NOT NULL,
                body TEXT NOT NULL);
            CREATE TABLE cache (
                item_id INTEGER PRIMARY KEY, revision INTEGER NOT NULL,
                body TEXT NOT NULL);
        """)
        db.execute("INSERT INTO source VALUES (1,?,?)", tuple(REVISION_1.values()))
    finally:
        db.close()


def row_value(row):
    return {"revision": row[0], "body": row[1]} if row else None


def observe(path):
    db = connect(path)
    try:
        return {"source": row_value(db.execute("SELECT revision,body FROM source WHERE item_id=1").fetchone()),
                "cache": row_value(db.execute("SELECT revision,body FROM cache WHERE item_id=1").fetchone())}
    finally:
        db.close()


def capture_source(path):
    db = connect(path)
    try:
        # Revision and body are captured coherently, not in separate reads.
        return row_value(db.execute("SELECT revision,body FROM source WHERE item_id=1").fetchone())
    finally:
        db.close()  # Release the read connection before waiting; B can commit.


def commit_b(path):
    db = connect(path)
    try:
        db.execute("BEGIN IMMEDIATE")
        try:
            db.execute("UPDATE source SET revision=?,body=? WHERE item_id=1", tuple(REVISION_2.values()))
            db.execute("INSERT INTO cache SELECT item_id,revision,body FROM source WHERE item_id=1")
            db.execute("COMMIT")
        except BaseException:
            if db.in_transaction:
                db.execute("ROLLBACK")
            raise
    finally:
        db.close()


def delete_cache(path):
    db = connect(path)
    try:
        require(db.execute("DELETE FROM cache WHERE item_id=1").rowcount == 1, "cache_deletion_missing")
    finally:
        db.close()


def publish_a(path, snapshot, policy):
    db = connect(path)
    try:
        # For the correct policy the authoritative check and conditional write
        # share this transaction; no writer can advance source between them.
        db.execute("BEGIN IMMEDIATE")
        try:
            comparison_revision = None
            allowed = True
            if policy == "authoritative-source":
                current = db.execute("SELECT revision FROM source WHERE item_id=1").fetchone()
                comparison_revision = current[0] if current else None
                allowed = comparison_revision == snapshot["revision"]
            elif policy == "cache-row-only":
                current = db.execute("SELECT revision FROM cache WHERE item_id=1").fetchone()
                comparison_revision = current[0] if current else None
                # Teaching defect: a deleted row loses the only comparison.
                allowed = current is None or comparison_revision <= snapshot["revision"]
            cursor = db.execute("""
                INSERT INTO cache(item_id,revision,body) SELECT 1,?,? WHERE ?
                ON CONFLICT(item_id) DO UPDATE SET
                    revision=excluded.revision,body=excluded.body
            """,
                (snapshot["revision"], snapshot["body"], allowed))
            rowcount = cursor.rowcount
            db.execute("COMMIT")
        except BaseException:
            if db.in_transaction:
                db.execute("ROLLBACK")
            raise
        return {"policy": policy, "decision": "published" if rowcount else "rejected_stale",
                "rowcount": rowcount, "comparison_revision": comparison_revision}
    finally:
        db.close()


def receive_message(channel):
    require(channel.poll(CHILD_TIMEOUT), "ipc_message_timed_out")
    try:
        return channel.recv()
    except EOFError as error:
        raise RuntimeError("owned_child_channel_closed_early") from error


def late_publisher(path, policy, channel):
    try:
        snapshot = capture_source(path)
        channel.send({"phase": "captured", "snapshot": snapshot})
        require(receive_message(channel) == "publish", "unexpected_release_message")
        channel.send({"phase": "published", "publication": publish_a(path, snapshot, policy)})
    finally:
        channel.close()


def run_case(name):
    policy = ("unconditional" if name == "naive" else
              "cache-row-only" if name == "row-only-deleted" else "authoritative-source")
    deleted = name.endswith("-deleted")
    with tempfile.TemporaryDirectory(prefix="fde-cache-publication-") as directory:
        path = str(Path(directory) / "scratch.sqlite")
        initialize(path)
        context = mp.get_context("spawn")
        driver_channel, child_channel = context.Pipe()
        child = context.Process(target=late_publisher, args=(path, policy, child_channel))
        try:
            child.start()
            child_channel.close()
            first = receive_message(driver_channel)
            require(first["phase"] == "captured", "missing_snapshot_barrier")
            snapshot = first["snapshot"]
            require(snapshot == REVISION_1, "snapshot_body_revision_mismatch")
            commit_b(path)
            b_observation = observe(path)
            require(b_observation == {"source": REVISION_2, "cache": REVISION_2}, "b_did_not_commit_revision_2")
            if deleted:
                delete_cache(path)
            before_a = observe(path)["cache"]
            require(before_a == (None if deleted else REVISION_2), "unexpected_cache_before_release")
            driver_channel.send("publish")  # The barrier establishes order; no timing guess.
            completed = receive_message(driver_channel)
            require(completed["phase"] == "published", "missing_publication_result")
            child.join(CHILD_TIMEOUT)
            require(not child.is_alive() and child.exitcode == 0, "owned_child_did_not_finish")
            after = observe(path)
            publication = completed["publication"]
            protected = policy == "authoritative-source"
            expected_cache = (None if deleted else REVISION_2) if protected else REVISION_1
            require(after["source"] == REVISION_2, "authoritative_source_changed")
            require(after["cache"] == expected_cache, "unexpected_final_cache")
            require(publication["rowcount"] == (0 if protected else 1), "unexpected_publication_rowcount")
            db = connect(path)
            try:
                require(db.execute("PRAGMA integrity_check").fetchone()[0] == "ok", "scratch_integrity_failed")
            finally:
                db.close()
            return {"case": name, "process_roles": {"A": "owned child process", "B": "parent driver; separate SQLite connection"},
                    "captured_a": snapshot, "snapshot_body_matches_revision": True,
                    "b_after_commit": b_observation, "cache_deleted_after_b": deleted,
                    "cache_before_a": before_a, "publication": publication,
                    "authoritative_source_after": after["source"], "cache_after": after["cache"],
                    "child_exit": child.exitcode}
        finally:
            driver_channel.close()
            child_channel.close()
            if child.pid is not None:
                if child.is_alive():
                    child.kill()
                    child.join(2)
                require(not child.is_alive(), "owned_child_not_reaped")
                child.close()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    action = parser.add_mutually_exclusive_group(required=True)
    action.add_argument("--case", choices=CASES, help="run one named race case")
    action.add_argument("--all", action="store_true", help="run and verify all four cases")
    action.add_argument("--self-test", action="store_true", help="verify all four cases; print a compact result")
    args = parser.parse_args()
    names = CASES if args.all or args.self_test else (args.case,)
    reports = [run_case(name) for name in names]
    if args.self_test:
        # A guard that rejects every publication would pass the stale cases.
        # This positive control verifies that a matching source can publish.
        with tempfile.TemporaryDirectory(prefix="fde-cache-control-") as directory:
            path = str(Path(directory) / "scratch.sqlite")
            initialize(path)
            publication = publish_a(path, capture_source(path), "authoritative-source")
            require(publication["rowcount"] == 1, "matching_source_publication_rejected")
            require(observe(path) == {"source": REVISION_1, "cache": REVISION_1}, "matching_source_body_changed")
        result = {"self_test": "passed", "cases": list(names),
                  "verified": "coherent snapshot, IPC order, stale overwrite, authoritative rejection, deletion counterexample, bodies and rowcounts, matching-source acceptance"}
    else:
        result = {"basis": "actual controlled local process and temporary SQLite rows",
                  "scope": "cache publication only; no response-serving or distributed freshness claim", "cases": reports}
    print(json.dumps(result, indent=2))
    return 0


if __name__ == "__main__":
    sys.exit(main())
