# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-capability-warrant-that-validates-cryptographically-but-exceeds-its-attested-execution-envelope.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-capability-warrant-that-validates-cryptographically-but-exceeds-its-attested-execution-envelope.warrant.json
# Markdown SHA-256:   288a7470085eab8a18589317808ef632412b9d8a5cf469ae54f72ed2582c0828
# Code AST SHA-256:   a3591113f8d3193b9ce4aff8009593da31aaf8dfc68aa8611d83df9bdbda3ae5
# Verified Classes:   WarrantExceedsEnvelope, EnvelopeIncomparable, Envelope, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class WarrantExceedsEnvelope(RuntimeError):
    """Warrant's declared bound exceeds the instance's attested envelope."""


class EnvelopeIncomparable(RuntimeError):
    """Warrant and attestation express a gating dimension in incompatible units."""


@dataclass(frozen=True)
class Envelope:
    max_egress_bytes: Optional[int]
    max_wall_clock_s: Optional[int]
    allowed_network_zones: frozenset[str]


@dataclass(frozen=True)
class Warrant:
    capability: str
    target: str
    max_bytes: Optional[int]
    deadline_s: Optional[int]
    network_zone: Optional[str]


def project_warrant_onto_envelope(
    warrant: Warrant,
    envelope: Envelope,
    task_declared_bytes: Optional[int],
) -> dict:
    """Return effective bounds, or raise if the warrant cannot be honored.

    Classification per gating dimension:
      dominated      -> warrant bound <= attested bound
      exceeds        -> warrant bound > attested bound AND task needs > attested
      clamped        -> warrant unbounded or over, but task fits attested bound
      incomparable   -> cannot compare; fail closed
    """
    effective: dict = {}

    # Egress bytes: the dimension that actually killed the worker.
    if warrant.max_bytes is not None and envelope.max_egress_bytes is not None:
        if warrant.max_bytes <= envelope.max_egress_bytes:
            effective["max_bytes"] = warrant.max_bytes
        else:
            # Warrant over envelope. Only consumable if task fits attested bound.
            if task_declared_bytes is None:
                raise WarrantExceedsEnvelope(
                    f"warrant max_bytes={warrant.max_bytes} > attested "
                    f"max_egress_bytes={envelope.max_egress_bytes}; "
                    f"no task_declared_bytes to justify clamping"
                )
            if task_declared_bytes > envelope.max_egress_bytes:
                raise WarrantExceedsEnvelope(
                    f"task needs {task_declared_bytes}B but attested envelope "
                    f"caps at {envelope.max_egress_bytes}B"
                )
            effective["max_bytes"] = envelope.max_egress_bytes
            effective["clamped_from"] = warrant.max_bytes
    elif warrant.max_bytes is not None and envelope.max_egress_bytes is None:
        # Warrant bounds a dimension the attestation does not bound: unknown.
        raise EnvelopeIncomparable(
            "warrant bounds max_bytes but attestation does not attest egress"
        )
    else:
        effective["max_bytes"] = envelope.max_egress_bytes

    # Wall clock: same projection, same fail-closed rule.
    if warrant.deadline_s is not None and envelope.max_wall_clock_s is not None:
        if warrant.deadline_s > envelope.max_wall_clock_s:
            raise WarrantExceedsEnvelope(
                f"warrant deadline_s={warrant.deadline_s} > attested "
                f"max_wall_clock_s={envelope.max_wall_clock_s}"
            )
        effective["deadline_s"] = warrant.deadline_s
    else:
        effective["deadline_s"] = envelope.max_wall_clock_s

    # Network zone: set membership, not numeric comparison.
    if warrant.network_zone is not None:
        if warrant.network_zone not in envelope.allowed_network_zones:
            raise WarrantExceedsEnvelope(
                f"warrant zone {warrant.network_zone!r} not in attested "
                f"zones {sorted(envelope.allowed_network_zones)}"
            )
    effective["network_zone"] = warrant.network_zone

    return effective
