# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-propagate-a-federated-trace-context-across-an-organizational-trust-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-propagate-a-federated-trace-context-across-an-organizational-trust-boundary.warrant.json
# Markdown SHA-256:   b8b3d9e94452992dd9158de61354aa197d5188358658ebcdc4b3e1f695c00e23
# Code AST SHA-256:   fb4c026d55803ab1384a4a60aab1561aaf3a6a1494bb5456896082e86bd8a5c6
# Verified Classes:   FederatedTraceBoundaryError, TraceContext
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class FederatedTraceBoundaryError(RuntimeError):
    """Raised when a foreign trace context must not be re-emitted across a trust boundary."""


@dataclass
class TraceContext:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    baggage: dict = field(default_factory=dict)
    issuer: str = ""
    issued_at: float = 0.0
    signature_valid: bool = False
    covered_baggage_fields: frozenset = frozenset()
    issuer_authorized_fields: frozenset = frozenset()
    namespaced: bool = False
    parent_resolvable: bool = True


DECLARED_SKEW_BOUND_S = 30.0


def assert_reemittable(ctx: TraceContext, trust_root_validator, now: Optional[float] = None) -> None:
    now = time.time() if now is None else now

    if not ctx.signature_valid or not trust_root_validator(ctx):
        raise FederatedTraceBoundaryError(
            f"unsigned or unverifiable context from issuer={ctx.issuer!r}; "
            "terminate at boundary, do not re-emit"
        )

    uncovered = set(ctx.baggage) - set(ctx.covered_baggage_fields)
    if uncovered:
        raise FederatedTraceBoundaryError(
            f"baggage fields {sorted(uncovered)} not covered by signature; "
            "opaque pass-through is unsound"
        )

    unauthorized = set(ctx.baggage) - set(ctx.issuer_authorized_fields)
    if unauthorized:
        raise FederatedTraceBoundaryError(
            f"issuer={ctx.issuer!r} not authorized to assert fields {sorted(unauthorized)}"
        )

    if not ctx.namespaced:
        raise FederatedTraceBoundaryError(
            f"trace_id {ctx.trace_id!r} is not issuer-namespaced; collision could merge causal chains"
        )

    if not ctx.parent_resolvable:
        raise FederatedTraceBoundaryError(
            f"span {ctx.span_id!r} has unresolved parent {ctx.parent_span_id!r}; "
            "re-parenting to a local root would forge causality"
        )

    if abs(now - ctx.issued_at) > DECLARED_SKEW_BOUND_S:
        raise FederatedTraceBoundaryError(
            f"issued_at skew {abs(now - ctx.issued_at):.1f}s exceeds bound {DECLARED_SKEW_BOUND_S}s"
        )


def handle_inbound(ctx: TraceContext, trust_root_validator) -> dict:
    """Accept the call; decide only whether to re-emit the trace context."""
    try:
        assert_reemittable(ctx, trust_root_validator)
    except FederatedTraceBoundaryError as e:
        # Degrade: terminate the foreign trace, start a local root,
        # preserve the correlation_id as an attribute, never as parentage.
        return {
            "action": "boundary_terminated",
            "new_local_root": True,
            "correlation_id": ctx.trace_id,
            "audit": str(e),
        }
    return {"action": "reemit", "parent_span_id": ctx.span_id}
