# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-missing-reasoning-span-as-a-correlation-break-rather-than-a-sampling-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-missing-reasoning-span-as-a-correlation-break-rather-than-a-sampling-gap.warrant.json
# Markdown SHA-256:   5d0bc2b28a7d81165d13ef872b0a26811687d9210bfc98d4bbd524095c149828
# Code AST SHA-256:   aeab08be8c7a9472818f6345f2bae4825288347d4cba79aef84c99fecb505d24
# Verified Classes:   CorrelationVerdict, CorrelationBreakError, ChildSpan, ParentSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class CorrelationVerdict(Enum):
    HEALTHY = "healthy"
    SAMPLING_GAP = "sampling_gap"
    CORRELATION_BREAK = "correlation_break"
    MISATTRIBUTION = "misattribution"
    UNDERDETERMINED = "underdetermined"


class CorrelationBreakError(RuntimeError):
    """Raised when a reasoning span's declared fan-out is violated by a recorded child."""


@dataclass
class ChildSpan:
    name: str
    sampling_decision: str | None  # "recorded" | "dropped" | None if unknown


@dataclass
class ParentSpan:
    name: str
    expected_children: set[str]
    observed_children: list[ChildSpan] = field(default_factory=list)
    pipeline_lossless: bool = True


def classify(parent: ParentSpan) -> CorrelationVerdict:
    observed_names = {c.name for c in parent.observed_children}
    missing = parent.expected_children - observed_names
    extra = observed_names - parent.expected_children

    if extra:
        return CorrelationVerdict.MISATTRIBUTION
    if not missing:
        return CorrelationVerdict.HEALTHY

    decisions = {c.sampling_decision for c in parent.observed_children}
    if decisions == {"dropped"}:
        return CorrelationVerdict.SAMPLING_GAP
    if None in decisions and not parent.pipeline_lossless:
        return CorrelationVerdict.UNDERDETERMINED
    return CorrelationVerdict.CORRELATION_BREAK


def assert_correlated(parent: ParentSpan) -> None:
    verdict = classify(parent)
    if verdict is CorrelationVerdict.CORRELATION_BREAK:
        missing = parent.expected_children - {c.name for c in parent.observed_children}
        raise CorrelationBreakError(
            f"parent={parent.name!r} missing recorded children {sorted(missing)}; "
            f"not attributable to sampling"
        )
    if verdict is CorrelationVerdict.MISATTRIBUTION:
        extra = {c.name for c in parent.observed_children} - parent.expected_children
        raise CorrelationBreakError(
            f"parent={parent.name!r} has unexpected children {sorted(extra)}; "
            f"async-context propagation likely stale"
        )


# Example: the async-context bug — step 2 got a tool.call it never declared.
step2 = ParentSpan(
    name="agent.step[2]",
    expected_children={"tool.call:search"},
    observed_children=[
        ChildSpan("tool.call:search", "recorded"),
        ChildSpan("tool.call:fetch", "recorded"),
    ],
)
assert_correlated(step2)  # raises CorrelationBreakError (misattribution)
