# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-federated-memory-write-when-the-namespace-quorum-returns-a-stale-epoch-acknowledgement.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-federated-memory-write-when-the-namespace-quorum-returns-a-stale-epoch-acknowledgement.warrant.json
# Markdown SHA-256:   8921612e90d4438b1156415c9ce3efc5de9b80c52905a243fb2b2ce880093d64
# Code AST SHA-256:   7dfc5fcf833663f4127d92fe28184fbcc89dddfd99b2da68f6099c9f45011d29
# Verified Classes:   StaleEpochCommitError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StaleEpochCommitError(RuntimeError):
    """Raised when a write is about to be committed on a superseded namespace epoch."""
    pass


def commit_write(acks, fresh_epoch, merge_policy, idempotent):
    """
    acks: list of dicts {peer, accepted, epoch, seq}
    fresh_epoch: int, re-read immediately before commit decision
    merge_policy: 'carry_forward' | 'discard_superseded'
    idempotent: bool
    """
    accepted = [a for a in acks if a["accepted"]]
    stale = [a for a in acks if not a["accepted"] and a.get("reason") == "STALE_EPOCH"]

    # Any STALE_EPOCH from any peer invalidates the whole attempt.
    if stale:
        max_seen = max([fresh_epoch] + [a["epoch"] for a in stale])
        if not idempotent and merge_policy == "discard_superseded":
            raise StaleEpochCommitError(
                f"non-idempotent write hit stale epoch; peers={[a['peer'] for a in stale]}, "
                f"fresh_epoch={fresh_epoch}, max_seen={max_seen}; abort and reconcile"
            )
        # idempotent or carry-forward: force re-issue at fresh epoch
        return {"status": "REISSUE", "epoch": max_seen}

    # All ACKs must agree on the fresh epoch; equality, not just acceptance.
    for a in accepted:
        if a["epoch"] != fresh_epoch:
            raise StaleEpochCommitError(
                f"ACK epoch {a['epoch']} != fresh epoch {fresh_epoch} on peer {a['peer']}"
            )

    return {"status": "COMMITTED", "epoch": fresh_epoch, "seq": accepted[0]["seq"]}
