# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-missing-child-span-as-a-hard-abort-rather-than-a-benign-gap-in-a2a-distributed-tracing.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-missing-child-span-as-a-hard-abort-rather-than-a-benign-gap-in-a2a-distributed-tracing.warrant.json
# Markdown SHA-256:   3653a045827ea54b26f0edb49c50d51651ce841a670941452b5c9da9a0a1d0c8
# Code AST SHA-256:   d3c9116ef45d094eeb9d1f3854121b6ed44099ce5a4026a19122e59dd94377b6
# Verified Classes:   SpanLossClassificationError, SubtaskState, SubtaskRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class SpanLossClassificationError(RuntimeError):
    """Raised when a missing child span cannot be safely classified
    because no authoritative completion token exists to disambiguate
    'never started' from 'completed, telemetry lost'."""
    pass


class SubtaskState(Enum):
    BENIGN_GAP = "benign_gap"          # token present, span missing -> safe
    INDETERMINATE = "indeterminate"    # no token, within dispatch timeout
    UNRECONCILED = "unreconciled"      # no token, timeout elapsed -> abort


@dataclass
class SubtaskRecord:
    trace_id: str
    parent_span_id: str
    subtask_index: int
    token_present: bool
    dispatch_elapsed_s: float
    dispatch_timeout_s: float


def classify_missing_span(rec: SubtaskRecord, span_present: bool) -> SubtaskState:
    if span_present:
        # Span present: trace is intact, no gap to classify.
        return SubtaskState.BENIGN_GAP

    # Span is missing. The decision MUST key on the token, never the span.
    if rec.token_present:
        # Completed subtask whose span was dropped by the exporter.
        # Retrying here would duplicate a committed side effect.
        return SubtaskState.BENIGN_GAP

    if rec.dispatch_elapsed_s < rec.dispatch_timeout_s:
        # First attempt may still be in flight; do not retry yet.
        return SubtaskState.INDETERMINATE

    # No token after timeout: the three execution states are now
    # genuinely indistinguishable. A blind retry here is unsound.
    raise SpanLossClassificationError(
        f"subtask {rec.subtask_index} on trace {rec.trace_id} "
        f"parent {rec.parent_span_id}: span missing and no completion "
        f"token after {rec.dispatch_elapsed_s:.1f}s "
        f"(timeout {rec.dispatch_timeout_s:.1f}s). "
        f"Cannot distinguish never-started from completed-with-lost-span. "
        f"Abort subtask and escalate UNRECONCILED; do not retry."
    )


def decide_retry(rec: SubtaskRecord, span_present: bool) -> bool:
    state = classify_missing_span(rec, span_present)
    if state is SubtaskState.BENIGN_GAP:
        return False  # completed or trace-only gap; never retry
    if state is SubtaskState.INDETERMINATE:
        return False  # wait on token, do not retry
    return False      # UNRECONCILED raises before reaching here
