# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-shared-memory-claims-across-federated-zones-without-a-central-coordinator.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-shared-memory-claims-across-federated-zones-without-a-central-coordinator.warrant.json
# Markdown SHA-256:   52704d5aa28a57119d803cf1c9e8720c94b81148573f29ad3b6ff8f2f001f2ae
# Code AST SHA-256:   b6ea474a32deecf738f8438c87051093a1bc6a38545380f9863088cde90ba559
# Verified Classes:   IncomparableViewConflict, Certificate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class IncomparableViewConflict(RuntimeError):
    """Raised when two valid claim certificates overlap but their membership
    views are incomparable, so no safe tiebreaker exists."""
    pass


@dataclass(frozen=True)
class Certificate:
    region_start: int
    region_end: int
    view_id: str
    view_ancestors: frozenset  # ancestor view ids, for comparability check
    zone_id: str
    epoch: int
    signatures: tuple

    def overlaps(self, other: "Certificate") -> bool:
        return self.region_start < other.region_end and other.region_start < self.region_end

    def comparable_with(self, other: "Certificate") -> bool:
        return (
            self.view_id in other.view_ancestors
            or other.view_id in self.view_ancestors
            or self.view_id == other.view_id
        )


# Memory types where a wrong ordering causes silent corruption rather than a fault.
SILENT_CORRUPTION_TYPES = frozenset({"dma", "mmap_shared", "device_visible"})


def reconcile(c1: Certificate, c2: Certificate, memory_type: str) -> Optional[Certificate]:
    """Return the winning certificate, or None if the region must be frozen.

    Raises IncomparableViewConflict when the certificates overlap, are both
    structurally valid, and their views are incomparable AND the memory type
    is one where a wrong tiebreaker is undetectable.
    """
    if not c1.overlaps(c2):
        return None  # no conflict; caller keeps both

    if c1.comparable_with(c2):
        # Total order exists; higher epoch wins deterministically.
        return c1 if c1.epoch >= c2.epoch else c2

    # Incomparable views: no protocol-level tiebreaker.
    if memory_type in SILENT_CORRUPTION_TYPES:
        raise IncomparableViewConflict(
            f"region [{c1.region_start:#x}..{c1.region_end:#x}] has overlapping "
            f"certificates from incomparable views {c1.view_id!r} (zone {c1.zone_id}) "
            f"and {c2.view_id!r} (zone {c2.zone_id}); memory_type={memory_type!r} "
            f"permits silent corruption, refusing to order"
        )

    # Isolated memory: wrong ordering produces a detectable fault. Order by
    # epoch then zone id, and record the resolution for later audit.
    winner = max((c1, c2), key=lambda c: (c.epoch, c.zone_id))
    digest = hashlib.sha256(
        f"{c1.view_id}:{c2.view_id}:{winner.zone_id}".encode()
    ).hexdigest()[:16]
    print(f"[reconcile] resolved contested region via tiebreaker, audit={digest}")
    return winner
