# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-elicitation-replies-as-non-authoritative-once-the-server-re-enters-sampling-and-how-to-detect-the-diverge.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-elicitation-replies-as-non-authoritative-once-the-server-re-enters-sampling-and-how-to-detect-the-diverge.warrant.json
# Markdown SHA-256:   a99c7751bf31ed248489727ed7e221331593e0a9fa9c6175be0048fcd1531209
# Code AST SHA-256:   40f1f172f4eb7bc68d72312bb7331e3956b13bedd21adffa5201925ded4aa709
# Verified Classes:   ElicitationAuthorityViolation, InvocationLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class ElicitationAuthorityViolation(RuntimeError):
    """Raised when a sampled value attempts to supersede an elicited constraint."""
    pass


@dataclass
class InvocationLedger:
    elicited: dict[str, Any] = field(default_factory=dict)
    sampled: dict[str, Any] = field(default_factory=dict)

    def pin_elicited(self, key: str, value: Any) -> None:
        self.elicited[key] = value

    def reconcile_sampling(
        self,
        sampled_output: dict[str, Any],
        constraints_ref: dict[str, str] | None,
    ) -> dict[str, Any]:
        """Diff sampled output against elicited registry.

        Returns the safe subset of sampled fields the server may act on.
        Raises on any divergence that is not justified by a constraints_ref
        binding the field to its elicited source.
        """
        constraints_ref = constraints_ref or {}
        safe: dict[str, Any] = {}
        for key, sampled_val in sampled_output.items():
            if key not in self.elicited:
                safe[key] = sampled_val
                continue
            elicited_val = self.elicited[key]
            if sampled_val == elicited_val:
                safe[key] = sampled_val
                continue
            # Divergence: only permissible if explicitly declared as derived.
            if constraints_ref.get(key) == "derives_from_elicited":
                # Still not authoritative — quarantine, do not forward.
                continue
            raise ElicitationAuthorityViolation(
                f"sampled field {key!r}={sampled_val!r} diverges from "
                f"elicited {elicited_val!r} with no constraints_ref binding; "
                f"refusing to forward to server action"
            )
        self.sampled.update(safe)
        return safe


def handle_server_sampling(
    ledger: InvocationLedger,
    sampled_output: dict[str, Any],
    constraints_ref: dict[str, str] | None,
    server_action_depends_on: list[str],
) -> dict[str, Any]:
    safe = ledger.reconcile_sampling(sampled_output, constraints_ref)
    missing = [k for k in server_action_depends_on if k in ledger.elicited and k not in safe]
    if missing:
        raise ElicitationAuthorityViolation(
            f"server action depends on elicited fields {missing} that were "
            f"superseded or quarantined by sampling; re-elicitation required"
        )
    return safe
