# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-prompt-injection-alerts-with-otel-trace-anomaly-scores-when-the-two-signals-are-computed-on-disjoint-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-prompt-injection-alerts-with-otel-trace-anomaly-scores-when-the-two-signals-are-computed-on-disjoint-spans.warrant.json
# Markdown SHA-256:   2dcc0f0f07b86764e8bedd72b257e9bfd82f478caa8618ac88c8c8d6564b9eb4
# Code AST SHA-256:   36c24ac01244cb6f350e9ad5065cd3545d60f9729a9dc13ce1d81ebeef95b54a
# Verified Classes:   CorrelationIndeterminate, PISpan, AnomalyRow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime


class CorrelationIndeterminate(RuntimeError):
    """Raised when a PI alert cannot be validly joined to an anomaly score."""


@dataclass
class PISpan:
    trace_id: str
    agent_root_span_id: str
    score: float
    span_end_time: datetime


@dataclass
class AnomalyRow:
    trace_id: str
    agent_root_span_id: str
    score: float
    feature_window_closed_at: datetime
    pi_score_in_features: bool


def correlate(pi: PISpan, anomaly: AnomalyRow, threshold: float = 0.7) -> dict:
    # Root-identity invariant: trace_id alone is insufficient.
    if (pi.trace_id, pi.agent_root_span_id) != (
        anomaly.trace_id,
        anomaly.agent_root_span_id,
    ):
        raise CorrelationIndeterminate(
            f"root mismatch: pi=({pi.trace_id},{pi.agent_root_span_id}) "
            f"anomaly=({anomaly.trace_id},{anomaly.agent_root_span_id})"
        )

    # Ordering invariant: classifier must close before feature window closes.
    if pi.span_end_time >= anomaly.feature_window_closed_at:
        raise CorrelationIndeterminate(
            f"temporal mismatch: pi closed {pi.span_end_time} "
            f">= window {anomaly.feature_window_closed_at}; "
            f"score {pi.score:.2f} arrived too late to gate detection"
        )

    # Feature-completeness invariant: PI score must have been an input.
    if not anomaly.pi_score_in_features:
        raise CorrelationIndeterminate(
            "PI score was co-located post-hoc, not fed into detector features"
        )

    # Valid join: PI score may now gate the anomaly threshold downward.
    effective_threshold = 0.4 if pi.score > 0.8 else threshold
    return {
        "trace_id": pi.trace_id,
        "pi_score": pi.score,
        "anomaly_score": anomaly.score,
        "escalate": anomaly.score >= effective_threshold,
        "correlation_status": "valid",
    }
