# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-countersign-a-federated-audit-receipt-when-its-own-local-provenance-log-is-non-monotonic.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-countersign-a-federated-audit-receipt-when-its-own-local-provenance-log-is-non-monotonic.warrant.json
# Markdown SHA-256:   8e133503d4f29e08186984b344a3196206fd5794553b11583718c1a6bf3e4b16
# Code AST SHA-256:   6f8ca2130c858cbfe58385a55ba1022425fd00c0f3752fcf4acbc9a33fb366a4
# Verified Classes:   ProvenanceForkError, ReceiptOrderingError, Root, AttestedRoots
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceForkError(RuntimeError):
    """Raised when about to countersign a root that does not monotonically
    extend every previously attested root, with no signed retraction."""


class ReceiptOrderingError(RuntimeError):
    """Raised on timestamp/counter skew that is NOT a provenance fork."""


@dataclass
class Root:
    value: str
    parent: Optional[str] = None  # hash of predecessor root, None for genesis


@dataclass
class AttestedRoots:
    """Set of roots this instance has countersigned to external parties."""
    roots: dict = field(default_factory=dict)  # value -> Root
    retractions: dict = field(default_factory=dict)  # superseded -> retraction_ref

    def ancestry(self, value: str) -> list:
        chain, cur = [], self.roots.get(value)
        while cur is not None:
            chain.append(cur.value)
            cur = self.roots.get(cur.parent) if cur.parent else None
        return chain

    def is_extension_of(self, new: Root, prior: str) -> bool:
        # new extends prior iff prior appears in new's ancestry chain
        return prior in self.ancestry(new.value)


def countersign_receipt(attested: AttestedRoots, new_root: Root,
                        receipt_counter: int, last_counter: int) -> str:
    if receipt_counter <= last_counter:
        # Ordering skew is a transport problem, not a fork. Do not refuse on fork grounds.
        raise ReceiptOrderingError(
            f"receipt counter {receipt_counter} <= last {last_counter}; re-derive, do not fork-refuse"
        )

    for prior_value in attested.roots:
        if attested.is_extension_of(new_root, prior_value):
            continue
        # Divergence detected. Allowed only if a signed retraction names the prior root.
        if prior_value in attested.retractions:
            continue
        raise ProvenanceForkError(
            f"refusing to countersign root {new_root.value}: does not extend "
            f"previously attested root {prior_value} and no signed retraction exists"
        )

    attested.roots[new_root.value] = new_root
    return f"receipt:{new_root.value}:signed"
