# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-cross-federation-reputation-laundering-when-otel-trace-attribution-diverges-from-execution-custody.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-cross-federation-reputation-laundering-when-otel-trace-attribution-diverges-from-execution-custody.warrant.json
# Markdown SHA-256:   4e2b7d9ab7361510119fb70dbdaf52a16b820311a8221c9680e3d1391019f7a7
# Code AST SHA-256:   c052307564c025dab4f71ec28952fe37319b4018313ed7a68a2c8323223803e3
# Verified Classes:   CustodyDivergenceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CustodyDivergenceError(RuntimeError):
    """Raised when a span's parentage claims custody the warrant chain cannot support."""
    pass


def verify_custody_credit(span, warrant_registry, skew_bound_ms):
    """
    Reject a span from custody-based reputation credit if its parentage
    disagrees with the warrant chain reachable from its parent.
    """
    parent = span.parent
    if parent is None:
        return True  # root spans are self-custodied; attribution == custody

    # Condition 1: child warrant issuer must appear in parent's warrant chain.
    parent_chain = warrant_registry.chain_for(parent.warrant_id)
    if span.warrant_issuer not in {w.issuer for w in parent_chain}:
        raise CustodyDivergenceError(
            f"span {span.span_id} claims parent {parent.span_id} but issuer "
            f"{span.warrant_issuer} is absent from parent warrant chain "
            f"{[w.issuer for w in parent_chain]}"
        )

    # Condition 2: child warrant scope must be a strict subset of parent scope.
    parent_scope = warrant_registry.scope_for(parent.warrant_id)
    if not span.warrant_scope.issubset(parent_scope):
        raise CustodyDivergenceError(
            f"span {span.span_id} widens scope {span.warrant_scope} beyond "
            f"parent scope {parent_scope}"
        )

    # Condition 3: child start must fall inside the declared custody window.
    lo = parent.start_ms - skew_bound_ms
    hi = parent.end_ms + skew_bound_ms
    if not (lo <= span.start_ms <= hi):
        raise CustodyDivergenceError(
            f"span {span.span_id} start {span.start_ms} outside custody window "
            f"[{lo}, {hi}] for parent {parent.span_id}"
        )

    return True
