# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-forks-before-committing-replay-state-and-why-does-the-obvious-last-writer-wins-merge-silently-corrupt-epi.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-forks-before-committing-replay-state-and-why-does-the-obvious-last-writer-wins-merge-silently-corrupt-epi.warrant.json
# Markdown SHA-256:   02741d7b2f933c6a6f1ed6f995dbb81db2f50ba5d6bca933210740595a165cc6
# Code AST SHA-256:   a2ed5019d9434944be316891e5ed7f842fccb7e70899f727fe91b4b04988910c
# Verified Classes:   ForkReconciliationError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ForkReconciliationError(RuntimeError):
    """Raised when a speculative fork's delta is committed without a
    reconciliation record, or when replay encounters a canonical entry
    whose originating fork was discarded but not recorded."""
    pass


def reconcile_forks(forks, causal_clock):
    """
    Pure reconciliation: merge fork delta logs into a canonical log using
    a logical (causal) clock, never a wall clock. Returns the canonical log
    and a reconciliation record naming every fork and its delta hash.
    """
    if not forks:
        raise ForkReconciliationError("no forks to reconcile")

    # Total causal order; wall-clock timestamps are explicitly ignored.
    ordered = sorted(forks, key=lambda f: causal_clock(f.fork_id))

    canonical = []
    record = {"winner": None, "discarded": [], "delta_hashes": {}}
    seen_keys = {}

    for fork in ordered:
        record["delta_hashes"][fork.fork_id] = fork.delta_hash()
        for entry in fork.delta_log:
            key = (entry.trajectory_id, entry.seq)
            if key in seen_keys:
                # Collision: two forks wrote the same logical slot.
                # This is only legal if the earlier writer is explicitly
                # superseded by causal order and recorded as discarded.
                prior = seen_keys[key]
                record["discarded"].append(prior)
            seen_keys[key] = fork.fork_id
            canonical.append(entry)

    if len(record["discarded"]) != len(set(record["discarded"])):
        record["discarded"] = list(set(record["discarded"]))

    record["winner"] = ordered[-1].fork_id
    return canonical, record


def commit_canonical(canonical, record, episodic_store, consistency_check):
    """
    Commit only after reconciliation. Enforces the invariant that every
    canonical entry's originating fork is either the winner or explicitly
    recorded as discarded.
    """
    # Cross-field consistency must pass BEFORE any write is visible to replay.
    violations = consistency_check(canonical)
    if violations:
        raise ForkReconciliationError(
            f"merged log fails cross-field consistency: {violations}"
        )

    for entry in canonical:
        origin = entry.fork_id
        if origin != record["winner"] and origin not in record["discarded"]:
            raise ForkReconciliationError(
                f"canonical entry seq={entry.seq} originates from fork "
                f"{origin!r} which is neither winner nor recorded discarded; "
                f"replay would reconstruct an unaccountable lineage"
            )

    # Atomic commit: record first, then entries, so replay always has provenance.
    episodic_store.write_reconciliation_record(record)
    episodic_store.append_canonical(canonical)
    return record


def replay(canonical, record, consistency_check):
    """
    Replay must consume the reconciliation record as input, not re-derive
    the winner. If a canonical entry's fork is absent from the record,
    replay aborts rather than reconstructing a false history.
    """
    known = {record["winner"], *record["discarded"]}
    for entry in canonical:
        if entry.fork_id not in known:
            raise ForkReconciliationError(
                f"replay aborted: entry seq={entry.seq} from unknown fork "
                f"{entry.fork_id!r}; reconciliation record is incomplete"
            )
    violations = consistency_check(canonical)
    if violations:
        raise ForkReconciliationError(
            f"replay reconstructed inconsistent state: {violations}"
        )
    return canonical
