# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-credential-chain-has-silently-re-rooted-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-credential-chain-has-silently-re-rooted-mid-execution.warrant.json
# Markdown SHA-256:   8ccd2f8fe26661d63a4807f1f996e3baf299a974d22e8a90be74a821a8fed453
# Code AST SHA-256:   09fa47255c96593c8028abded54dca52d15cf0460efe79ccfdafb0ebdeb4f222
# Verified Classes:   DelegationRerootError, ChainPin
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class DelegationRerootError(RuntimeError):
    """Raised when a credential chain's root/path diverges from the task pin."""
    pass


@dataclass(frozen=True)
class ChainPin:
    task_id: str
    delegation_id: str
    expected_path_hash: str
    max_depth: int


def validate_refresh_parent(pin: ChainPin, candidate_parent: dict) -> None:
    # Refresh-parent selection must be by identity, not by mere validity.
    if candidate_parent.get("delegation_id") != pin.delegation_id:
        raise DelegationRerootError(
            f"refresh parent delegation_id {candidate_parent.get('delegation_id')!r} "
            f"!= pinned {pin.delegation_id!r} for task {pin.task_id}; "
            "refusing to reissue against a non-pinned parent (re-root candidate)"
        )
    if candidate_parent.get("delegation_path_hash") != pin.expected_path_hash:
        raise DelegationRerootError(
            f"refresh parent path hash {candidate_parent.get('delegation_path_hash')!r} "
            f"!= pinned {pin.expected_path_hash!r}; chain has re-rooted"
        )


def validate_call_chain(pin: ChainPin, presented_chain: list[dict]) -> None:
    # Call-time re-check: depth and path hash against the presented chain.
    if len(presented_chain) > pin.max_depth:
        raise DelegationRerootError(
            f"presented chain depth {len(presented_chain)} exceeds pinned max "
            f"{pin.max_depth} for task {pin.task_id}"
        )
    presented_hash = presented_chain[-1].get("delegation_path_hash")
    if presented_hash != pin.expected_path_hash:
        raise DelegationRerootError(
            f"presented path hash {presented_hash!r} != pinned "
            f"{pin.expected_path_hash!r}; authorization decision must not be "
            "root-keyed"
        )
