# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-inherit-a-parent-trace-context-the-cross-org-trace-parent-laundering-failure-in-federated-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-inherit-a-parent-trace-context-the-cross-org-trace-parent-laundering-failure-in-federated-agent-handoffs.warrant.json
# Markdown SHA-256:   0adb20ee47b47d0bea5150f06434e71b77ffd3df18d998aa7d61e2bba9127054
# Code AST SHA-256:   c8a5165ffefa04daa7ceba4accc73d2f3e22ef768c302d89e0d9c85b610d5c81
# Verified Classes:   TraceLineageViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TraceLineageViolation(RuntimeError):
    """Raised when authority-bearing tracestate crosses a trust boundary un-reissued."""
    pass


AUTHORITY_BEARING = ("warrant", "budget_id", "audit_scope", "delegation")


def reissue_tracestate(
    incoming: dict,
    callee_tenant: str,
    peer_authenticated: bool,
) -> dict:
    """
    Called by the callee's tracing interceptor at the trust boundary.
    Correlation keys pass through; authority keys are dropped unless
    the callee can re-derive them from an authenticated peer.
    """
    if not peer_authenticated:
        # Fail closed: unauthenticated peer cannot confer authority.
        for key, _ in incoming.items():
            if any(marker in key for marker in AUTHORITY_BEARING):
                raise TraceLineageViolation(
                    f"unauthenticated peer attempted to pass authority-bearing "
                    f"tracestate key {key!r}; boundary must drop or reject"
                )

    reissued = {}
    for key, value in incoming.items():
        if any(marker in key for marker in AUTHORITY_BEARING):
            # Authority is re-derived from the authenticated peer, never inherited.
            continue
        reissued[key] = value

    reissued["tenant"] = callee_tenant
    reissued["trust.boundary"] = "crossed"
    return reissued


def emit_boundary_span(trace_id: str, callee_tenant: str, incoming: dict) -> dict:
    if not trace_id or len(trace_id) != 32:
        raise TraceLineageViolation(f"malformed trace_id {trace_id!r}")
    try:
        state = reissue_tracestate(incoming, callee_tenant, peer_authenticated=True)
    except TraceLineageViolation:
        # Emit an unverified boundary span so replay can still anchor.
        state = {"tenant": callee_tenant, "trust.boundary": "unverified"}
    return {
        "trace_id": trace_id,
        "span.kind": "PRODUCER",
        "trust.boundary": state["trust.boundary"],
        "tracestate": state,
    }
