# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-span-it-cannot-lineage-join-the-split-warrant-taint-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-span-it-cannot-lineage-join-the-split-warrant-taint-gap.warrant.json
# Markdown SHA-256:   0a282678287f39190af4ede3b2386484f5189084969fecf11aecf6860ac24f53
# Code AST SHA-256:   31b2a2946843087c0ca7e60d92dbbd9787df59bf507271f83b55c5a180a34cf1
# Verified Classes:   LineageOrderingViolation, Span, Warrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime


class LineageOrderingViolation(RuntimeError):
    """Raised when a span claims authorization from a warrant that did not yet exist."""


@dataclass
class Span:
    span_id: str
    start_time: datetime
    taint_id: str | None
    claimed_warrant_id: str | None
    authorizes_link: bool


@dataclass
class Warrant:
    warrant_id: str
    minted_at: datetime | None  # None => pre-allocated, not yet backfilled


def emit_span(span: Span, warrants: dict[str, Warrant], strict: bool = True) -> dict:
    """Decide whether a span may assert authorized lineage, or must degrade to a hint."""
    attrs = {
        "span_id": span.span_id,
        "taint_id": span.taint_id,
        "claimed_warrant_id": span.claimed_warrant_id,
    }

    if span.claimed_warrant_id is None:
        attrs["lineage_unverified"] = False
        return attrs

    warrant = warrants.get(span.claimed_warrant_id)
    if warrant is None:
        raise LineageOrderingViolation(
            f"span {span.span_id} references unknown warrant {span.claimed_warrant_id}"
        )

    # Causal precedence invariant: the warrant must predate the span it authorizes.
    if warrant.minted_at is None:
        attrs["lineage_unverified"] = True
        attrs["pending_warrant"] = warrant.warrant_id
        attrs["degraded_reason"] = "warrant_not_yet_minted"
        return attrs

    if warrant.minted_at >= span.start_time:
        if strict and span.authorizes_link:
            # The span asserts an 'authorizes' edge it cannot temporally prove.
            raise LineageOrderingViolation(
                f"span {span.span_id} start={span.start_time.isoformat()} "
                f"claims authorization from warrant {warrant.warrant_id} "
                f"minted_at={warrant.minted_at.isoformat()} (effect precedes cause)"
            )
        attrs["lineage_unverified"] = True
        attrs["degraded_reason"] = "warrant_minted_after_span_open"
        return attrs

    attrs["lineage_unverified"] = False
    attrs["lineage_verified"] = True
    return attrs
