# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-content-addressed-chunk-manifest-as-authoritative-over-a-peer-s-partial-result-summary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-content-addressed-chunk-manifest-as-authoritative-over-a-peer-s-partial-result-summary.warrant.json
# Markdown SHA-256:   82a50a0c171282a836dba860b01c34f12b24b4a76ceebddaaa815b7a4aac4d75
# Code AST SHA-256:   be85db8323275abee0f06e7359b35e8d25e5bac8ef771f0fe5745c570edddf29
# Verified Classes:   HoleSetNonEmpty, ManifestSummaryConflict, Chunk, Manifest, PeerSummary, Received
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class HoleSetNonEmpty(RuntimeError):
    """Raised when a peer's partial-result summary claims completeness but the
    content-addressed manifest reveals missing chunk addresses."""
    pass


class ManifestSummaryConflict(RuntimeError):
    """Raised when the peer summary and the manifest disagree on chunk count
    or root, indicating the peer's commit accounting is unreliable."""
    pass


@dataclass
class Chunk:
    address: str          # "sha256:<hex>"
    data: bytes


@dataclass
class Manifest:
    root: str
    addresses: list[str]

    def address_set(self) -> set[str]:
        return set(self.addresses)


@dataclass
class PeerSummary:
    chunks_complete: int
    root: str
    status: str           # "complete" | "partial"
    committed_at: str | None = None


@dataclass
class Received:
    chunks: dict[str, Chunk] = field(default_factory=dict)

    def add(self, chunk: Chunk) -> None:
        self.chunks[chunk.address] = chunk

    def address_set(self) -> set[str]:
        return set(self.chunks.keys())


def sha256_address(data: bytes) -> str:
    return "sha256:" + hashlib.sha256(data).hexdigest()


def reconcile(
    manifest: Manifest,
    summary: PeerSummary,
    received: Received,
) -> bytes:
    """Reconcile a peer's partial-result summary against the chunk manifest.

    Invariant: commit predicate is (root_match AND hole_set_empty), evaluated
    against the manifest, never against the summary count alone.
    """
    # Step 1: count is necessary but not sufficient. A mismatch here means the
    # peer's commit accounting diverged from the manifest; refuse to proceed.
    if summary.chunks_complete != len(manifest.addresses):
        raise ManifestSummaryConflict(
            f"summary count {summary.chunks_complete} != manifest length "
            f"{len(manifest.addresses)}; peer commit accounting unreliable"
        )
    if summary.root != manifest.root:
        raise ManifestSummaryConflict(
            f"summary root {summary.root} != manifest root {manifest.root}"
        )

    # Step 2: hole set is the authoritative signal. Counts can match while a
    # mid-stream chunk is missing and a duplicate fills the count.
    hole_set = manifest.address_set() - received.address_set()
    if hole_set:
        raise HoleSetNonEmpty(
            f"{len(hole_set)} chunk address(es) missing from received set: "
            f"{sorted(hole_set)[:5]}{'...' if len(hole_set) > 5 else ''}; "
            f"request re-emission by address, do not commit"
        )

    # Step 3: assemble in manifest order (not receive order) and verify root.
    assembled = b"".join(
        received.chunks[addr].data for addr in manifest.addresses
    )
    if sha256_address(assembled) != manifest.root:
        raise HoleSetNonEmpty(
            "assembled artifact root mismatch despite empty hole set; "
            "a chunk was replaced, not merely missing — re-request full set"
        )
    return assembled
