#!/usr/bin/env python3
"""Original CPU process lab: replicated outputs versus input-feature partitions.

Run: python3 gpu-collective-lab.py (Python 3.11+, standard library only).
Two real CPU workers per case exchange synthetic messages through local pipes.
No GPU, NCCL, PyTorch, network, packages, model or production workload is used.
The coordinator illustrates a reduce followed by broadcast; it is not an NCCL
implementation/wire protocol and makes no speedup, bandwidth or GPU claims.
Workers also hold the full fictional fixture to compute their own reference.
This arithmetic/IPC demonstration proves no distributed memory savings and is
not a tensor-parallel framework. python-number is a teaching numeric label,
not a hardware dtype.

Changed-copy experiment: predict then change INPUT_VECTOR[0] from 2 to 4 in a
separate copy. Rank 0's partial and the full answer change; rank 1's partial
stays [10, 14]. Keep the same weights, partition and reference calculation.
"""
import hashlib
import json
import math
import multiprocessing
import os
from pathlib import Path
import sys
import time

INPUT_VECTOR = [2, 3, 5, 7]
WEIGHTS = [[1, 0, 2, 0], [0, 1, 0, 2]]
GROUP = [0, 1]
DTYPE = "python-number"


def finite_number(value):
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        return False
    try:
        return math.isfinite(value)
    except OverflowError:
        return False


def validate_input(vector):
    if not isinstance(vector, list) or len(vector) != 4 or not all(finite_number(value) for value in vector):
        raise ValueError("INPUT_VECTOR must contain exactly four finite numbers; booleans are not numbers in this protocol.")


def full_reference(vector):
    # Compute directly from every matrix column, independent of partial sums.
    return [sum(weight * value for weight, value in zip(row, vector)) for row in WEIGHTS]


def operation_for(case):
    return "replica-matvec" if case == "replicas" else "sum-allreduce" if case in ("sum-allreduce", "mismatched-count") else "partition-matvec"


def worker(connection, rank, case, vector):
    try:
        validate_input(vector)
        reference = full_reference(vector)
        columns = [0, 1, 2, 3] if case == "replicas" else [0, 1] if rank == 0 else [2, 3]
        values = [sum(row[column] * vector[column] for column in columns) for row in WEIGHTS]
        if case == "mismatched-count" and rank == 1:
            values = values[:1]
        sent = {"kind": "contribution", "group": GROUP, "rank": rank, "pid": os.getpid(),
                "operation": operation_for(case), "step": 1, "count": len(values), "dtype": DTYPE,
                "columns": columns, "values": values}
        connection.send(sent)
        if not connection.poll(6):
            raise TimeoutError("Coordinator reply deadline exceeded")
        received = connection.recv()
        if received.get("kind") == "broadcast":
            if received.get("group") != GROUP or received.get("rank") != rank or received.get("operation") != "sum-allreduce" or received.get("step") != 2 or received.get("dtype") != DTYPE or received.get("count") != 2:
                raise ValueError("Invalid broadcast metadata")
            output = received.get("values")
            if not isinstance(output, list) or len(output) != 2 or not all(finite_number(value) for value in output):
                raise ValueError("Invalid broadcast vector")
            basis = "broadcast-result"
        elif received.get("kind") == "complete":
            output, basis = values, "local-output"
        elif received.get("kind") == "refused":
            output, basis = None, "no-result-refused"
        else:
            raise ValueError("Unknown coordinator reply")
        comparison = {"basis": basis, "shape_matches": None if output is None else len(output) == len(reference),
                      "values_match": None if output is None else output == reference}
        connection.send({"kind": "worker-report", "rank": rank, "pid": os.getpid(), "sent": sent,
                         "received": received, "full_reference": reference, "comparison": comparison})
    except Exception as error:
        try:
            connection.send({"kind": "worker-error", "rank": rank, "pid": os.getpid(), "error": type(error).__name__ + ": " + str(error)})
        except (BrokenPipeError, EOFError, OSError):
            pass
        raise
    finally:
        connection.close()


def validate_contributions(messages, processes, operation):
    # This small authored protocol validates exact membership and metadata before
    # any combining. It is teaching code, not an untrusted IPC security boundary.
    if set(messages) != {0, 1}:
        return "group-mismatch"
    keys = {"kind", "group", "rank", "pid", "operation", "step", "count", "dtype", "columns", "values"}
    for rank in GROUP:
        message = messages[rank]
        if not isinstance(message, dict) or set(message) != keys:
            return "invalid-contribution"
        if message["kind"] != "contribution" or message["group"] != GROUP or type(message["rank"]) is not int or message["rank"] != rank or message["pid"] != processes[rank].pid:
            return "group-mismatch"
        if message["operation"] != operation or message["step"] != 1 or message["dtype"] != DTYPE:
            return "metadata-mismatch"
        if type(message["count"]) is not int or message["count"] != 2 or not isinstance(message["values"], list) or len(message["values"]) != message["count"]:
            return "count-mismatch"
        if not all(finite_number(value) for value in message["values"]):
            return "invalid-numeric-value"
        expected_columns = [0, 1, 2, 3] if operation == "replica-matvec" else [0, 1] if rank == 0 else [2, 3]
        if message["columns"] != expected_columns:
            return "partition-mismatch"
    return None


def run_case(context, case, vector):
    connections, processes, worker_ends = {}, {}, []
    events = []
    result = {"id": case, "operation": operation_for(case)}
    deadline = time.monotonic() + 8

    def receive(rank):
        remaining = max(0, deadline - time.monotonic())
        if not connections[rank].poll(remaining):
            raise TimeoutError(f"Rank {rank} message deadline exceeded")
        message = connections[rank].recv()
        events.append({"direction": "worker-to-coordinator", "rank": rank, "message": message})
        if not isinstance(message, dict) or message.get("kind") == "worker-error":
            raise RuntimeError(f"Unexpected rank {rank} message: {message}")
        return message

    try:
        for rank in GROUP:
            parent_end, worker_end = context.Pipe(duplex=True)
            connections[rank] = parent_end
            worker_ends.append(worker_end)
            process = context.Process(target=worker, args=(worker_end, rank, case, vector), name=f"fixture-rank-{rank}")
            processes[rank] = process
            process.start()
            worker_end.close()
        messages = {rank: receive(rank) for rank in GROUP}
        refusal = validate_contributions(messages, processes, operation_for(case))
        combined = None
        if refusal is None and case == "sum-allreduce":
            combined = [messages[0]["values"][index] + messages[1]["values"][index] for index in range(2)]
            if not all(finite_number(value) for value in combined):
                refusal, combined = "nonfinite-reduction", None
        result["contributions"] = [{"rank": rank, "pid": processes[rank].pid, "columns": messages[rank].get("columns"), "message": messages[rank]} for rank in GROUP]
        result["reduction"] = {"performed": combined is not None, "result": combined, "refusal": refusal}
        for rank in GROUP:
            if refusal:
                reply = {"kind": "refused", "reason": refusal}
            elif combined is not None:
                reply = {"kind": "broadcast", "group": GROUP, "rank": rank, "operation": "sum-allreduce",
                         "step": 2, "count": 2, "dtype": DTYPE, "values": combined}
            else:
                reply = {"kind": "complete", "reason": "replicated-output-no-reduction" if case == "replicas" else "partials-returned-without-reduction"}
            connections[rank].send(reply)
            events.append({"direction": "coordinator-to-worker", "rank": rank, "message": reply})
        workers = [receive(rank) for rank in GROUP]
        for report in workers:
            rank = report.get("rank")
            if report.get("kind") != "worker-report" or rank not in GROUP or report.get("pid") != processes[rank].pid:
                raise RuntimeError("Invalid final worker report")
        for process in processes.values():
            process.join(timeout=max(0, deadline - time.monotonic()))
            if process.is_alive() or process.exitcode != 0:
                raise RuntimeError("Worker did not finish successfully within deadline")
        for report in workers:
            report["exit_code"] = processes[report["rank"]].exitcode
        result["workers"] = workers
    finally:
        # Bound cleanup even when a child is stuck or a protocol check fails.
        for end in worker_ends:
            end.close()
        for connection in connections.values():
            connection.close()
        for process in processes.values():
            if process.pid is not None:
                if process.is_alive():
                    process.terminate()
                process.join(timeout=1)
                if process.is_alive():
                    process.kill()
                    process.join(timeout=1)
        result["workers_finished"] = all(process.pid is not None and not process.is_alive() for process in processes.values())
        result["connections_closed"] = all(connection.closed for connection in connections.values())
        result["ipc_events"] = events
    return result


def run_lab():
    if sys.version_info < (3, 11):
        raise RuntimeError("Python 3.11+ is required.")
    validate_input(INPUT_VECTOR)
    context = multiprocessing.get_context("spawn")
    cases = [run_case(context, case, INPUT_VECTOR) for case in ("replicas", "partial-only", "sum-allreduce", "mismatched-count")]
    return {
        "lab": "Input-feature partitions and collective results · actual CPU process fixture",
        "python": sys.version.split()[0], "coordinator_pid": os.getpid(), "start_method": context.get_start_method(),
        "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
        "scope": "Two actual CPU worker processes per case and local Pipe IPC. Workers also hold the full fictional fixture for reference checks. No GPU, NCCL, Torch, network, packages, model, distributed memory savings or production performance was tested; this is not a tensor-parallel framework.",
        "input_vector": INPUT_VECTOR, "weights": WEIGHTS, "full_reference": full_reference(INPUT_VECTOR),
        "protocol": {"group": GROUP, "steps": {"contribution": 1, "broadcast": 2}, "dtype": DTYPE,
                     "note": "Original illustrative protocol; python-number is not a hardware dtype. Coordinator reduce then broadcast demonstrates sum-allreduce semantics, not an NCCL wire protocol or algorithm."},
        "note": "Outer success means the experiment finished, including unreduced partials that fail the reference and a refused count mismatch with no result broadcast.",
        "cases": cases, "all_workers_finished": all(case["workers_finished"] for case in cases),
    }


if __name__ == "__main__":
    if len(sys.argv) != 1:
        print(json.dumps({"error": "Usage: python3 gpu-collective-lab.py"}))
        sys.exit(2)
    try:
        print(json.dumps(run_lab(), indent=2, allow_nan=False))
    except Exception as error:
        print(json.dumps({"error": {"type": type(error).__name__, "message": str(error)}}))
        sys.exit(1)
