# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-span-granular-correlation-between-traces-evals-and-safety-signals.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-span-granular-correlation-between-traces-evals-and-safety-signals.warrant.json
# Markdown SHA-256:   d5008de3348edd622df49f632e02b05b9d78410d44384a886c96edd14ce0e575
# Code AST SHA-256:   3214a16398587db4d375fa4523f3355ffd35217ac981daf439ea63f874032e69
# Verified Classes:   CorrelationInvariantViolation, SpanRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class CorrelationInvariantViolation(RuntimeError):
    """Raised when a span-granular join would attribute eval/safety to the wrong execution."""
    pass

@dataclass(frozen=True)
class SpanRecord:
    trace_id: str
    span_id: str
    attempt_index: Optional[int]
    emit_sequence: int
    output_payload: str
    safety_verdict: Optional[str] = None
    eval_score: Optional[float] = None

def correlation_key(span: SpanRecord) -> tuple:
    # Bijection key: must distinguish every semantic execution.
    if span.attempt_index is None:
        raise CorrelationInvariantViolation(
            f"span {span.trace_id}/{span.span_id} lacks attempt_index; "
            "cannot form bijective key, demote to correlation_gap"
        )
    return (span.trace_id, span.span_id, span.attempt_index, span.emit_sequence)

def join_eval_and_safety(spans: list[SpanRecord]) -> dict:
    groups: dict[tuple, list[SpanRecord]] = {}
    for s in spans:
        groups.setdefault(correlation_key(s), []).append(s)

    joined = {}
    for key, members in groups.items():
        if len(members) > 1:
            # Multiple records under a bijective key means the invariant is broken
            # upstream (duplicate emit_sequence), not a legitimate retry.
            raise CorrelationInvariantViolation(
                f"key {key} maps to {len(members)} records; "
                "emit_sequence collision — halt join, emit correlation_gap"
            )
        m = members[0]
        # Safety is non-demotable: a BLOCK anywhere in the group poisons the group.
        joined[key] = {
            "eval_score": m.eval_score,
            "safety_verdict": m.safety_verdict,
            "attributed": True,
        }
    return joined

def aggregate_trace(spans: list[SpanRecord]) -> dict:
    try:
        return join_eval_and_safety(spans)
    except CorrelationInvariantViolation as e:
        # Circuit-break: fall back to trace-level aggregation with gap marker.
        return {
            "correlation_gap": str(e),
            "trace_level_only": True,
            "span_count": len(spans),
        }
