# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-semantic-equivalence-during-cross-org-policy-translation-and-silently-exceed-its-delegated-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-semantic-equivalence-during-cross-org-policy-translation-and-silently-exceed-its-delegated-warrant.warrant.json
# Markdown SHA-256:   82f61ad61468a417508739dbdebc54efd55af440930ee95a96e061c2fb66540f
# Code AST SHA-256:   49fbef60af5baa0aeb28fee541bfe993a3d5fce13dcfdf24893eb1002c265905
# Verified Classes:   UntranslatableConstraintError, Constraint, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UntranslatableConstraintError(RuntimeError):
    """Raised when a source-warrant constraint has no subsuming target constraint
    and cannot be carried as an out-of-band obligation."""


@dataclass(frozen=True)
class Constraint:
    name: str
    value: object


@dataclass
class Warrant:
    constraints: dict[str, Constraint] = field(default_factory=dict)
    obligations: list[Constraint] = field(default_factory=list)

    def add(self, c: Constraint) -> None:
        self.constraints[c.name] = c


# Subsumption oracle: returns True iff target constraint entails source constraint
# (target is at least as restrictive). Returns None when undecidable.
def subsumes(target: Optional[Constraint], source: Constraint) -> Optional[bool]:
    if target is None:
        return None
    if target.name != source.name:
        return None
    # Quantitative bounds: target must be <= source to entail it.
    if source.name in ("max_records", "retention_hours"):
        try:
            return float(target.value) <= float(source.value)
        except (TypeError, ValueError):
            return None
    # Enumerated sensitivity: a total order PUBLIC < INTERNAL < RESTRICTED.
    order = {"PUBLIC": 0, "INTERNAL": 1, "RESTRICTED": 2}
    if source.name == "data_class":
        t, s = order.get(str(target.value)), order.get(str(source.value))
        if t is None or s is None:
            return None
        return t >= s
    # Unknown constraint family: undecidable by construction.
    return None


def translate(source: Warrant, target_dialect: set[str]) -> Warrant:
    """Translate a source warrant into a target dialect.

    Invariant: the returned warrant must entail the source warrant, or the
    untranslatable constraint must be carried as an obligation, or we refuse.
    """
    out = Warrant()
    for name, src in source.constraints.items():
        if name not in target_dialect:
            # Unrepresentable in target dialect: must become an obligation.
            out.obligations.append(src)
            continue
        tgt = Constraint(name=name, value=src.value)
        verdict = subsumes(tgt, src)
        if verdict is None:
            # Cannot prove entailment: fail closed, do not forward as permission.
            raise UntranslatableConstraintError(
                f"constraint {name!r} has no decidable subsumption in target "
                f"dialect {sorted(target_dialect)}; refusing to widen warrant"
            )
        if verdict is False:
            raise UntranslatableConstraintError(
                f"target constraint {name}={tgt.value!r} does not entail "
                f"source {name}={src.value!r}; translation would widen authority"
            )
        out.add(tgt)
    return out


def enforce(warrant: Warrant, enforceable_obligations: set[str]) -> None:
    """Target runtime gate: refuse if any carried obligation cannot be enforced."""
    for ob in warrant.obligations:
        if ob.name not in enforceable_obligations:
            raise UntranslatableConstraintError(
                f"target runtime cannot enforce obligation {ob.name}={ob.value!r}; "
                f"refusing execution rather than silently dropping it"
            )


# Observed failure reproduction:
source = Warrant()
source.add(Constraint("data_class", "INTERNAL"))
source.add(Constraint("max_records", 500))
source.add(Constraint("retention_hours", 24))

target_dialect = {"data_class"}  # flat dialect: no row or retention concept

translated = translate(source, target_dialect)
# max_records and retention_hours are now obligations, not permissions.
assert {o.name for o in translated.obligations} == {"max_records", "retention_hours"}

# A target runtime that cannot honor retention must refuse, not default to 30 days.
enforce(translated, enforceable_obligations={"max_records"})  # raises
