# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-span-the-orphaned-parent-boundary-in-cross-org-federated-agent-audit-trails.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-span-the-orphaned-parent-boundary-in-cross-org-federated-agent-audit-trails.warrant.json
# Markdown SHA-256:   2b8e4d380be2ceb993e2f1f93fcd7534c771422b17eeae429d1fd6738d443f37
# Code AST SHA-256:   764569f934e53fbe0da7001abdc3546d4abd92318bc30cb6b81cd28e2ca36932
# Verified Classes:   FederatedAdmissionError, Span, CrossOrgWarrant, FederatedAdmissionGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class FederatedAdmissionError(RuntimeError):
    """Raised when a span cannot be admitted to a federated audit trail under the attestation invariant."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    signer: str            # org identity that signed this span
    signature_valid: bool
    attributes_hash: str
    received_at: float = field(default_factory=time.time)
    warrant: Optional["CrossOrgWarrant"] = None


@dataclass
class CrossOrgWarrant:
    issuer: str            # org that owns the parent span
    grantee: str           # org authorized to emit children
    trace_id: str
    parent_span_id: str
    expires_at: float


class FederatedAdmissionGate:
    RE_RESOLUTION_WINDOW_S = 30.0

    def __init__(self):
        self.local_spans: dict[str, Span] = {}
        self.quarantine: list[Span] = []
        self.unverified_causality: list[Span] = []

    def _resolve_parent(self, span: Span) -> Optional[Span]:
        return self.local_spans.get(span.parent_span_id) if span.parent_span_id else None

    def _warrant_ok(self, span: Span, parent: Span) -> bool:
        w = span.warrant
        if w is None:
            return False
        return (
            w.issuer == parent.signer
            and w.grantee == span.signer
            and w.trace_id == span.trace_id
            and w.parent_span_id == parent.span_id
            and w.expires_at > time.time()
        )

    def admit(self, span: Span) -> str:
        if not span.signature_valid:
            # Malformed signature is the ONLY legitimate drop path.
            raise FederatedAdmissionError(
                f"span {span.span_id} has invalid signature; refusing admission"
            )

        if span.parent_span_id is None:
            self.local_spans[span.span_id] = span
            return "ADMITTED_ROOT"

        parent = self._resolve_parent(span)

        if parent is not None:
            if parent.signer == span.signer:
                self.local_spans[span.span_id] = span
                return "ADMITTED_SAME_ORG"
            if self._warrant_ok(span, parent):
                self.local_spans[span.span_id] = span
                return "ADMITTED_BOUNDARY_STUB"
            # Parent present, cross-org, no valid warrant: possible forgery.
            self.unverified_causality.append(span)
            return "UNVERIFIED_CAUSALITY"

        # Parent absent: NEVER drop. Quarantine with bounded re-resolution.
        self.quarantine.append(span)
        return "QUARANTINED_PENDING_PARENT"

    def reap_quarantine(self, now: Optional[float] = None) -> list[Span]:
        now = now if now is not None else time.time()
        still_pending, expired = [], []
        for s in self.quarantine:
            if now - s.received_at > self.RE_RESOLUTION_WINDOW_S:
                expired.append(s)
            else:
                still_pending.append(s)
        self.quarantine = still_pending
        for s in expired:
            parent = self._resolve_parent(s)
            if parent is not None and parent.signer == s.signer:
                self.local_spans[s.span_id] = s
            elif parent is not None and self._warrant_ok(s, parent):
                self.local_spans[s.span_id] = s
            else:
                self.unverified_causality.append(s)
        return expired

    def assert_trail_integrity(self) -> None:
        # Invariant: every admitted span has a parent that is either present
        # with matching signer, or present with a valid cross-org warrant.
        for sid, s in self.local_spans.items():
            if s.parent_span_id is None:
                continue
            parent = self.local_spans.get(s.parent_span_id)
            if parent is None:
                raise FederatedAdmissionError(
                    f"invariant violated: admitted span {sid} has absent parent {s.parent_span_id}"
                )
            if parent.signer != s.signer and not self._warrant_ok(s, parent):
                raise FederatedAdmissionError(
                    f"invariant violated: span {sid} admitted across org boundary without warrant"
                )
