# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-trace-correlation-rather-than-repair-a-broken-span-parent-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-trace-correlation-rather-than-repair-a-broken-span-parent-chain.warrant.json
# Markdown SHA-256:   cddae08618976ec29ee4835a719ad1cbcc8c453654670eee39e6e46c32279b4e
# Code AST SHA-256:   67cbdb62445afe4e4083756ac869f42d6ca4848523bdf56f5a7540e28167d4bb
# Verified Classes:   ContradictoryTraceLink
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ContradictoryTraceLink(RuntimeError):
    """Raised when a span's claimed parent chain violates causal monotonicity."""
    pass


def correlate_span(span, parent_index, skew_epsilon_s=0.050):
    """
    Attach span to its claimed parent only if the edge is causally consistent.
    Never re-parents. Returns (status, parent) or raises for hard contradictions.
    """
    claimed_id = span.get("parent_span_id")
    if claimed_id is None:
        return ("uncorrelated_rootless", None)

    parent = parent_index.get(claimed_id)
    if parent is None:
        # Missing linkage: defer, do not repair.
        return ("deferred_missing_parent", None)

    if parent.get("end_time") is None:
        # Parent never closed; cannot bound children.
        return ("deferred_open_parent", None)

    if parent.get("trace_id") != span.get("trace_id"):
        raise ContradictoryTraceLink(
            f"span {span['span_id']} claims parent {claimed_id} "
            f"but trace_id namespaces disagree "
            f"({span.get('trace_id')} != {parent.get('trace_id')})"
        )

    if span["start_time"] < parent["start_time"]:
        raise ContradictoryTraceLink(
            f"span {span['span_id']} starts before its claimed parent {claimed_id}"
        )

    if span["start_time"] > parent["end_time"] + skew_epsilon_s:
        raise ContradictoryTraceLink(
            f"span {span['span_id']} starts after parent {claimed_id} closed "
            f"(start={span['start_time']} end={parent['end_time']})"
        )

    # Duplicate logical operation under one parent without retry marker = contradiction.
    op_key = (span.get("operation"), span.get("target"))
    for sibling in parent.get("children", []):
        if (sibling.get("operation"), sibling.get("target")) == op_key:
            if sibling.get("retry_of") != span["span_id"] and span.get("retry_of") != sibling["span_id"]:
                raise ContradictoryTraceLink(
                    f"span {span['span_id']} duplicates operation {op_key} under "
                    f"parent {claimed_id} without retry_of marker"
                )

    return ("ok", parent)
