# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tainted-value-egress-denial-as-a-hard-halt-rather-than-a-retryable-error.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tainted-value-egress-denial-as-a-hard-halt-rather-than-a-retryable-error.warrant.json
# Markdown SHA-256:   81e123f75a38e9c912cfad0524456cc26e053cfb7c125ffcaa34c4f0f955910a
# Code AST SHA-256:   3fc2e4e9842f7adb4ad7a36fdc7de95f2bd58cb0296e746d0f7a276746098006
# Verified Classes:   EgressAttribution, TaintHalt, EgressError, HaltRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class EgressAttribution(str, Enum):
    DESTINATION = "destination"
    PAYLOAD = "payload"
    UNKNOWN = "unknown"


class TaintHalt(RuntimeError):
    """Raised when a payload-attributed egress denial must terminate the task."""
    pass


@dataclass
class EgressError:
    sink: str
    offending_label: Optional[str]
    attribution: EgressAttribution
    provenance_chain: list = field(default_factory=list)


@dataclass
class HaltRecord:
    sink: str
    label: str
    provenance: list
    action: str = "HALT_ESCALATE"


def handle_egress_error(err: EgressError, attempt_budget: int, attempts_used: int) -> HaltRecord:
    """
    Classify an egress denial and either permit bounded re-routing (capability
    denial) or raise TaintHalt (payload denial / unknown attribution).

    Invariant: payload-attributed denials are terminal for the current
    data-flow edge. The agent has no authority to transform, paraphrase,
    split, or re-derive the tainted value to reach the sink.
    """
    if err.attribution is EgressAttribution.DESTINATION:
        if attempts_used >= attempt_budget:
            raise TaintHalt(
                f"capability denial at {err.sink} exhausted attempt budget "
                f"({attempts_used}/{attempt_budget}); escalate to orchestrator"
            )
        # Caller may re-route to an allowlisted sink; no taint concern.
        return HaltRecord(sink=err.sink, label="<none>",
                          provenance=[], action="REROUTE_PERMITTED")

    # PAYLOAD or UNKNOWN -> fail closed.
    label = err.offending_label or "<unattributed>"
    if err.attribution is EgressAttribution.UNKNOWN:
        # An unattributed denial is treated as payload: never route around it.
        raise TaintHalt(
            f"unattributed egress denial at {err.sink}; failing closed as taint halt"
        )

    # Explicit payload attribution: hard halt, no retry, no transform.
    raise TaintHalt(
        f"taint denial at {err.sink}: label '{label}' forbidden at sink; "
        f"provenance={err.provenance_chain}; transformation laundering prohibited"
    )
