# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-trace-span-timestamps-with-eval-and-safety-signal-timestamps-when-they-are-produced-by-different-clocks.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-trace-span-timestamps-with-eval-and-safety-signal-timestamps-when-they-are-produced-by-different-clocks.warrant.json
# Markdown SHA-256:   8233b4c02cd1e3a3f525984caab967c5e2464f99532b085201a194b11af45671
# Code AST SHA-256:   7b34e8b2d14d60e2fb1867a7cf9efe3e5cc2a83af19dd585972735ba0a73db88
# Verified Classes:   UnattributableSignal, ClockSkewViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UnattributableSignal(RuntimeError):
    """Raised when an eval or safety signal cannot be causally bound to an agent step."""
    pass


class ClockSkewViolation(RuntimeError):
    """Raised when a signal's ingest time precedes the step it claims to observe."""
    pass


def attribute_signal(signal, span, skew_bound_ms, queue_p99_ms):
    """
    Bind an eval/safety signal to an agent step using causal tokens.
    Timestamps are validators only; proximity is never used as a primary join.
    """
    if not signal.get("span_id") or not signal.get("trace_id"):
        raise UnattributableSignal(
            f"signal {signal.get('id')} missing trace/span propagation; "
            f"refusing proximity fallback (queue_p99={queue_p99_ms}ms)"
        )

    if signal["trace_id"] != span["trace_id"]:
        raise UnattributableSignal(
            f"trace mismatch: signal={signal['trace_id']} span={span['trace_id']}"
        )

    # Causal validator: a signal cannot be observed before its step ended.
    if signal["ingest_ts"] < span["end_ts"]:
        delta = span["end_ts"] - signal["ingest_ts"]
        raise ClockSkewViolation(
            f"signal {signal['id']} ingest precedes span {span['span_id']} end "
            f"by {delta}ms (skew_bound={skew_bound_ms}ms); quarantine, do not attribute"
        )

    # Proximity fallback is permitted only under the strict duration bound.
    if signal["span_id"] != span["span_id"]:
        if span["duration_ms"] <= 10 * (skew_bound_ms + queue_p99_ms):
            raise UnattributableSignal(
                f"span_id mismatch and step too short for safe proximity fallback "
                f"(duration={span['duration_ms']}ms)"
            )
        signal["attribution"] = "proximity_degraded"
    else:
        signal["attribution"] = "causal_token"

    return {**signal, "step_span_id": span["span_id"]}
