# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-causal-trace-link-across-an-a2a-hop-that-has-no-verifiable-shared-parent-span.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-causal-trace-link-across-an-a2a-hop-that-has-no-verifiable-shared-parent-span.warrant.json
# Markdown SHA-256:   83b7180598cac5285a5dc23b5ebee89ac775f33ebef91c55d7bc3b3f09a8a4e1
# Code AST SHA-256:   50c84a51955ec5c8b8f93391752470fd7d8d124cbc0ae945b093f8899a74f0f9
# Verified Classes:   CausalLinkViolation, SpanContext, LocalSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class CausalLinkViolation(RuntimeError):
    """Raised when a received span context cannot be asserted as a causal parent."""


@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str
    start_ns: int
    end_ns: Optional[int] = None
    # Channel the context arrived on: "a2a_envelope", "tool_request",
    # "tool_response", "cache_echo", etc.
    channel: str = "a2a_envelope"


@dataclass
class LocalSpan:
    trace_id: str
    span_id: str
    parent_id: Optional[str]
    causality: str  # "verified" | "unverified" | "none"
    links: list[SpanContext] = field(default_factory=list)


CLOCK_SKEW_NS = 250_000_000  # 250ms budget


def _is_ancestor(span_id: str, known_ancestors: set[str]) -> bool:
    return span_id in known_ancestors


def assert_causal_parent(
    received: SpanContext,
    child_start_ns: int,
    known_ancestors: set[str],
    seen_non_ancestor_contexts: set[str],
    now_ns: Optional[int] = None,
) -> LocalSpan:
    """
    Decide whether `received` may be emitted as a hard causal parent of the
    child span about to be created. Returns a LocalSpan whose `parent_id` is
    set only when the link is verified; otherwise the context is attached as a
    `link` with causality="unverified", or the call raises.
    """
    now_ns = now_ns if now_ns is not None else time.time_ns()

    # Condition 1: provenance — context must arrive on a work-delivery channel.
    if received.channel in ("tool_response", "cache_echo"):
        # Context echoed by a tool is never a legitimate causal parent.
        # If it is also structurally impossible, treat as injection.
        if received.end_ns is not None and received.end_ns < child_start_ns - CLOCK_SKEW_NS:
            raise CausalLinkViolation(
                f"rejected injected context span={received.span_id} "
                f"channel={received.channel}: parent ended before child began "
                f"beyond skew budget"
            )
        # Otherwise: downgrade to correlation-only.
        return LocalSpan(
            trace_id=received.trace_id,
            span_id=f"child-{now_ns}",
            parent_id=None,
            causality="unverified",
            links=[received],
        )

    # Condition 2: non-aliasing — a span ID already seen in a non-ancestor
    # role cannot be promoted to parent.
    if received.span_id in seen_non_ancestor_contexts:
        return LocalSpan(
            trace_id=received.trace_id,
            span_id=f"child-{now_ns}",
            parent_id=None,
            causality="unverified",
            links=[received],
        )

    # Condition 3: temporal consistency.
    if received.start_ns > child_start_ns + CLOCK_SKEW_NS:
        raise CausalLinkViolation(
            f"parent span={received.span_id} starts after child by more than "
            f"skew budget; causal order impossible"
        )
    if received.end_ns is not None and received.end_ns < child_start_ns - CLOCK_SKEW_NS:
        raise CausalLinkViolation(
            f"parent span={received.span_id} ended before child began beyond "
            f"skew budget"
        )

    # Condition 4: ancestor closure.
    if not _is_ancestor(received.span_id, known_ancestors):
        return LocalSpan(
            trace_id=received.trace_id,
            span_id=f"child-{now_ns}",
            parent_id=None,
            causality="unverified",
            links=[received],
        )

    return LocalSpan(
        trace_id=received.trace_id,
        span_id=f"child-{now_ns}",
        parent_id=received.span_id,
        causality="verified",
    )
