# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-the-egress-taint-correlator-draw-the-syscall-completion-boundary-and-why-the-naive-post-return-hook-is-unsound.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-the-egress-taint-correlator-draw-the-syscall-completion-boundary-and-why-the-naive-post-return-hook-is-unsound.warrant.json
# Markdown SHA-256:   d240508c78a1706ae6463906e778b428862a643b635eb4ff822c9ee0847a4cd7
# Code AST SHA-256:   0569a5e094de597762201c6eac635ddf887ccba7b216c5bb4198cad0a93182af
# Verified Classes:   TaintBoundaryError, Range, ThreadTaint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class TaintBoundaryError(RuntimeError):
    """Raised when the correlator is asked to evaluate egress at an unsound boundary."""


@dataclass(frozen=True)
class Range:
    start: int
    length: int

    def overlaps(self, other: "Range") -> bool:
        return self.start < other.start + other.length and other.start < self.start + self.length


@dataclass
class ThreadTaint:
    committed: list[Range] = field(default_factory=list)

    def commit_read(self, dest: Range, ret: int) -> None:
        # Taint is committed only on read EXIT with a positive return value.
        if ret <= 0:
            return
        self.committed.append(Range(dest.start, min(dest.length, ret)))

    def is_tainted(self, src: Range) -> bool:
        return any(src.overlaps(r) for r in self.committed)


def check_egress(
    taint: ThreadTaint,
    src_ranges: list[Range],
    dest_allowed: bool,
    *,
    boundary: str,
) -> str:
    if boundary != "entry":
        # The post-return hook observes completion, not the decision point.
        raise TaintBoundaryError(
            f"egress evaluated at boundary={boundary!r}; taint must be checked at syscall entry"
        )

    tainted = any(taint.is_tainted(r) for r in src_ranges)
    if not tainted:
        return "allow-clean"
    if dest_allowed:
        return "allow-with-mark"
    # Deny before the kernel enqueues the skb; never CONTINUE a tainted send.
    raise TaintBoundaryError(
        "tainted egress to non-allowlisted destination: return -EPERM at entry, do not CONTINUE"
    )
