"""
models.py -- consistency models as checkers over a recorded history of reads and writes on replicated
registers: linearizability, sequential consistency, causal consistency, the per-key "regular/eventual"
property, and the four session guarantees. Each is a precise YES/NO question about what orderings could
explain the clients' observations.

[Questions this module answers]
  "One-copy semantics" (Lecture 19) and the "relaxed" models of Lectures 22
  and 25 are words; this module makes them exact. Given a trace of operations
  by several clients -- each with a real-time start and end, a value written
  or read -- which single order (if any) could have produced it under each
  model? The models form a hierarchy: linearizable => sequential => causal =>
  (eventual). A history may satisfy a weaker model but not a stronger one.

[The model as "is there a legal total order?"] For the strong models we ask
  whether the operations can be put in ONE total order that is legal for the
  data type (each read returns the value of the most recent write before it)
  AND respects a required partial order:
    linearizable  must respect REAL TIME: if a finished before b started, a is first.
    sequential    must respect each client's PROGRAM ORDER (not real time across clients).
    causal        must respect the HAPPENED-BEFORE order (program order + reads-from),
                  and different clients may see concurrent writes in different orders,
                  so it is checked PER CLIENT, not as one global order.

[The data type] A set of independent read/write REGISTERS, one per key, each
  starting at a given initial value. A write sets a key; a read returns a key.

[What is simplified] Brute force over permutations, so histories are small
  (up to ~9 operations). The point is to SEE the definitions decide cases, not
  to check big traces (that is the subject of tools like Jepsen's Knossos /
  Elle, which use far cleverer search).

[DS link] Supplement S2. Lamport 1979 (sequential consistency); Herlihy and Wing 1990
  (linearizability); Ahamad et al. 1995 (causal memory); Terry et al. 1994 (session guarantees);
  the happened-before relation is Supplement S1 (logical.py's idea, reproduced here).
"""

import itertools


# ----------------------------------------------------------------------------------------------
# A history is a list of operation dicts.
# ----------------------------------------------------------------------------------------------
# Each op: {"client", "kind": "w"/"r", "key", "value", "start", "end"}.
#   start < end are real-time instants (any comparable numbers); for a read, "value" is what it RETURNED.
# A client's PROGRAM ORDER is the order of its ops by start time.

def op_str(o):
    return "%s:%s(%s=%s)" % (o["client"], "W" if o["kind"] == "w" else "R", o["key"], o["value"])


def legal(order, initial):
    """Is a total order of ops legal for independent registers? Each read must return the value of the
    most recent earlier write to its key (or the key's initial value if none).

    [Parameters] order : list of ops; initial : dict key -> starting value (default 0 for any key).
    [Returns] True / False.
    """
    cur = dict(initial)
    for o in order:
        if o["kind"] == "w":
            cur[o["key"]] = o["value"]
        else:
            if cur.get(o["key"], 0) != o["value"]:
                return False
    return True


def _real_time_ok(order):
    """Does `order` respect real time: whenever a finished before b started, a precedes b?"""
    pos = {id(o): i for i, o in enumerate(order)}
    for a in order:
        for b in order:
            if a is not b and a["end"] <= b["start"] and pos[id(a)] > pos[id(b)]:
                return False
    return True


def _program_order_ok(order):
    """Does `order` keep each client's operations in their start-time (issue) order?"""
    by_client = {}
    for o in order:
        by_client.setdefault(o["client"], []).append(o["start"])
    return all(starts == sorted(starts) for starts in by_client.values())


def linearizable(history, initial=None):
    """Is there a legal total order respecting real time? [Returns] True / False.

    [Edge cases] Exponential; for histories up to ~9 ops. Ties in real time (overlapping ops) are free
      to order either way, which is what makes concurrency interesting.
    """
    initial = initial or {}
    for perm in itertools.permutations(history):
        if _real_time_ok(perm) and legal(perm, initial):
            return True
    return False


def sequential(history, initial=None):
    """Is there a legal total order respecting each client's program order (but not real time)?

    [Idea] Lamport 1979: the result is as if the operations were executed in SOME sequential order, and
      each client's operations appear in the order it issued them. Real time across clients is ignored.
    """
    initial = initial or {}
    for perm in itertools.permutations(history):
        if _program_order_ok(perm) and legal(perm, initial):
            return True
    return False


# ----------------------------------------------------------------------------------------------
# Causal consistency: per-client legal orders that respect happened-before
# ----------------------------------------------------------------------------------------------

def _happens_before(history):
    """Build -> on the operations: program order per client, plus reads-from (a read is after the write
    whose value it returned, if that write is unique). [Returns] a set of (i, j) index pairs (closure)."""
    n = len(history)
    edges = set()
    by_client = {}
    for i, o in enumerate(history):
        by_client.setdefault(o["client"], []).append(i)
    for ops in by_client.values():
        ops.sort(key=lambda i: history[i]["start"])
        for a, b in zip(ops, ops[1:]):
            edges.add((a, b))
    # reads-from: a read of value v on key k is after the (unique) write of v to k.
    for i, r in enumerate(history):
        if r["kind"] != "r":
            continue
        writes = [j for j, w in enumerate(history) if w["kind"] == "w" and w["key"] == r["key"] and w["value"] == r["value"]]
        if len(writes) == 1 and history[writes[0]]["value"] != 0:
            edges.add((writes[0], i))
    # transitive closure
    reach = {(a, b) for a, b in edges}
    changed = True
    while changed:
        changed = False
        for a, b in list(reach):
            for c, d in list(reach):
                if b == c and (a, d) not in reach:
                    reach.add((a, d))
                    changed = True
    return reach


def causal(history, initial=None):
    """Is the history causally consistent? [Returns] True / False.

    [Idea] Each CLIENT must see a legal serial order of all writes and its own reads that respects
      happened-before; different clients may order CONCURRENT writes differently. We check, per client,
      that some order of (all writes + that client's reads) is legal and respects ->.
    [Edge cases] Brute force per client; small histories only. Concurrent writes to the same key are
      what causal allows and sequential forbids.
    """
    initial = initial or {}
    hb = _happens_before(history)
    writes = [i for i, o in enumerate(history) if o["kind"] == "w"]
    clients = sorted({o["client"] for o in history})
    for c in clients:
        my_reads = [i for i, o in enumerate(history) if o["kind"] == "r" and o["client"] == c]
        subset = writes + my_reads
        ok = False
        for perm in itertools.permutations(subset):
            pos = {idx: p for p, idx in enumerate(perm)}
            if any((a, b) in hb and a in pos and b in pos and pos[a] > pos[b] for a in subset for b in subset):
                continue
            if legal([history[i] for i in perm], initial):
                ok = True
                break
        if not ok:
            return False
    return True


# ----------------------------------------------------------------------------------------------
# Session guarantees (Terry et al. 1994): properties of ONE client's session
# ----------------------------------------------------------------------------------------------

def read_your_writes(session):
    """Does every read see at least the client's own latest earlier write to that key?

    [Parameters] session : one client's ops in issue order. [Returns] True / False.
    [Idea] Terry et al.'s first session guarantee: a client never fails to see its own writes, even if
      those writes have not yet reached the replica it reads from (the replica must carry them forward).
    """
    my_last_write = {}
    for o in session:
        if o["kind"] == "w":
            my_last_write[o["key"]] = o["value"]
        elif o["key"] in my_last_write and o["value"] != my_last_write[o["key"]]:
            return False
    return True


def monotonic_reads(session):
    """Do successive reads of a key never go backward? Needs a notion of write order: here we use the
    value's position in the global write order, supplied as `order_of` via the key's write sequence.
    Simplified: a client must not read an older value after a newer one for the same key, where 'older'
    is a smaller write index recorded on each read as o['version']."""
    last = {}
    for o in session:
        if o["kind"] == "r" and "version" in o:
            if o["key"] in last and o["version"] < last[o["key"]]:
                return False
            last[o["key"]] = max(last.get(o["key"], -1), o["version"])
    return True


def _selftest():
    checks = 0
    # The classic non-sequential history (Lamport): two clients write, two read in opposite orders.
    # C1: W(x=1); C2: W(x=2); C3 reads x=1 then x=2; C4 reads x=2 then x=1. Not sequential.
    h = [
        {"client": "C1", "kind": "w", "key": "x", "value": 1, "start": 0, "end": 1},
        {"client": "C2", "kind": "w", "key": "x", "value": 2, "start": 0, "end": 1},
        {"client": "C3", "kind": "r", "key": "x", "value": 1, "start": 2, "end": 3},
        {"client": "C3", "kind": "r", "key": "x", "value": 2, "start": 4, "end": 5},
        {"client": "C4", "kind": "r", "key": "x", "value": 2, "start": 2, "end": 3},
        {"client": "C4", "kind": "r", "key": "x", "value": 1, "start": 4, "end": 5},
    ]
    assert not sequential(h)          # C3 and C4 disagree on the order of the two writes
    checks += 1

    # A history that is sequential but not linearizable: a read returns an old value although a newer
    # write finished (in real time) before the read started.
    h2 = [
        {"client": "C1", "kind": "w", "key": "x", "value": 1, "start": 0, "end": 1},
        {"client": "C2", "kind": "r", "key": "x", "value": 0, "start": 2, "end": 3},   # stale read after W finished
    ]
    assert sequential(h2) and not linearizable(h2)
    checks += 1

    # A linearizable history.
    h3 = [
        {"client": "C1", "kind": "w", "key": "x", "value": 1, "start": 0, "end": 1},
        {"client": "C2", "kind": "r", "key": "x", "value": 1, "start": 2, "end": 3},
    ]
    assert linearizable(h3) and sequential(h3) and causal(h3)
    checks += 1

    # Causal but not sequential: the two clients may order concurrent writes differently.
    assert causal(h) and not sequential(h)
    checks += 1

    # Read-your-writes within a session.
    sess = [{"client": "C", "kind": "w", "key": "x", "value": 5},
            {"client": "C", "kind": "r", "key": "x", "value": 5}]
    assert read_your_writes(sess)
    sess_bad = [{"client": "C", "kind": "w", "key": "x", "value": 5},
                {"client": "C", "kind": "r", "key": "x", "value": 0}]
    assert not read_your_writes(sess_bad)
    checks += 1

    # Monotonic reads.
    assert monotonic_reads([{"client": "C", "kind": "r", "key": "x", "value": 1, "version": 1},
                            {"client": "C", "kind": "r", "key": "x", "value": 2, "version": 2}])
    assert not monotonic_reads([{"client": "C", "kind": "r", "key": "x", "value": 2, "version": 2},
                                {"client": "C", "kind": "r", "key": "x", "value": 1, "version": 1}])
    checks += 1
    print("models self-test: OK (%d checks)" % checks)


if __name__ == "__main__":
    _selftest()
