# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-otel-genai-trace-as-a-lossy-projection-rather-than-a-replayable-log.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-otel-genai-trace-as-a-lossy-projection-rather-than-a-replayable-log.warrant.json
# Markdown SHA-256:   099350e7b2005cd8a202c94d079b888868534da6e9e53d7a8f38812882a6fb72
# Code AST SHA-256:   8ebfb571adb572572ba3cd793dea025d3591d9fe6001431480eb8160dcf85426
# Verified Classes:   ReplayInadmissible, SpanEdge
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import json
from dataclasses import dataclass


class ReplayInadmissible(RuntimeError):
    """Raised when a trace cannot support causal replay for the edge under investigation."""


@dataclass
class SpanEdge:
    span_id: str
    parent_span_id: str | None
    recorded_input_tokens: int          # gen_ai.usage.input_tokens on the consumer span
    recorded_output_payload: str        # gen_ai.output.messages / tool result on the producer
    sampling_temperature: float
    ordering_source: str                # "parent_span_id" | "start_time_unix_nano"
    truncation_marker_present: bool


def _reconstruct_prompt_tokens(payload: str) -> int:
    # Placeholder for the harness's tokenizer; must match the consumer model's tokenizer.
    return len(payload.split())


def assert_replay_admissible(edge: SpanEdge) -> None:
    # Invariant 1: payload completeness. A token-count gap means the recorded
    # producer payload is not what the consumer actually received.
    if edge.truncation_marker_present:
        raise ReplayInadmissible(
            f"edge {edge.span_id}: producer payload carries a truncation marker; "
            "recorded output is not byte-identical to consumer input"
        )
    reconstructed = _reconstruct_prompt_tokens(edge.recorded_output_payload)
    if reconstructed != edge.recorded_input_tokens:
        raise ReplayInadmissible(
            f"edge {edge.span_id}: token-count gap "
            f"(reconstructed={reconstructed}, recorded={edge.recorded_input_tokens}); "
            "payload completeness invariant violated"
        )

    # Invariant 2: causal ordering must come from parent links, never wall-clock.
    if edge.ordering_source != "parent_span_id":
        raise ReplayInadmissible(
            f"edge {edge.span_id}: ordering inferred from {edge.ordering_source!r}; "
            "concurrent agents invert wall-clock causality"
        )

    # Invariant 3: non-greedy sampling downgrades the claim to distributional.
    if edge.sampling_temperature > 0.0:
        # Not a hard failure, but replay must not emit a bit-exact bug verdict.
        raise ReplayInadmissible(
            f"edge {edge.span_id}: temperature={edge.sampling_temperature} > 0; "
            "replay is distributional, not deterministic — refuse causal attribution"
        )


def replay_edge(edge: SpanEdge) -> dict:
    assert_replay_admissible(edge)
    return {"span_id": edge.span_id, "verdict": "admissible"}
