# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-renegotiated-sla-as-a-new-escrow-epoch-rather-than-an-amendment-to-the-existing-contract.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-renegotiated-sla-as-a-new-escrow-epoch-rather-than-an-amendment-to-the-existing-contract.warrant.json
# Markdown SHA-256:   173d343b9d005f87185619e0eab40df3ff00de22d2fd137708600f7a50ed7a90
# Code AST SHA-256:   31f452982260f0f25908f56b43f6635590923676363c1a087f1ffddfc5194420
# Verified Classes:   EscrowEpochViolation, ContractRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class EscrowEpochViolation(RuntimeError):
    """Raised when a term change would mutate a live escrow epoch under a preserved contract_id."""
    pass


class ContractRecord:
    def __init__(self, contract_id: str, escrow_epoch_id: int,
                 t_accept: float, t_deadline: float):
        self.contract_id = contract_id
        self.escrow_epoch_id = escrow_epoch_id
        self.t_accept = t_accept
        self.t_deadline = t_deadline


def apply_term_change(record: ContractRecord, incoming: dict,
                      escrow_read: dict | None) -> ContractRecord:
    """
    incoming: {'contract_id', 'escrow_epoch_id'(optional), 'sla_relative_s',
              'price', 'scope'}
    escrow_read: result of GET_ESCROW, or None if the read failed.
    """
    if incoming.get("contract_id") != record.contract_id:
        raise EscrowEpochViolation(
            f"contract_id mismatch: {incoming.get('contract_id')} vs {record.contract_id}"
        )

    if escrow_read is None:
        # Cannot verify preservation; must not apply. Hold original terms.
        raise EscrowEpochViolation(
            "escrow read unavailable; refusing to apply unverified term change"
        )

    live_epoch = escrow_read["epoch_id"]
    lock_ts = escrow_read["lock_timestamp"]

    epoch_preserved = (live_epoch == record.escrow_epoch_id
                       and lock_ts <= record.t_accept)
    anchor_preserved = incoming.get("escrow_epoch_id") in (None, record.escrow_epoch_id)

    if epoch_preserved and anchor_preserved:
        # Amendment: keep t_accept and t_deadline; apply commercial deltas only.
        return record

    # Renegotiation: epoch moved or anchor re-derived. Must mint new identity.
    if live_epoch != record.escrow_epoch_id or lock_ts > record.t_accept:
        raise EscrowEpochViolation(
            f"epoch moved {record.escrow_epoch_id}->{live_epoch} under preserved "
            f"contract_id {record.contract_id}; renegotiate as new contract"
        )

    raise EscrowEpochViolation(
        "term change re-anchors SLA without new epoch; ambiguous classification"
    )
