# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-replay-diverge-when-otel-genai-spans-record-post-sampling-tool-arguments.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-replay-diverge-when-otel-genai-spans-record-post-sampling-tool-arguments.warrant.json
# Markdown SHA-256:   3be2b4ae433e142c78612023dd70839b64dec6f0f53cde1e584dc3df7e720d33
# Code AST SHA-256:   75799732480bc2006fa11ed29f241eea12b607566f90e81377be25e64ca18dcc
# Verified Classes:   ReplayInadmissibleError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ReplayInadmissibleError(RuntimeError):
    """Raised when a retained OTel GenAI trace cannot serve as a deterministic replay input."""
    pass


TRUNCATION_SENTINEL = "[REDACTED]"


def check_replay_admissibility(
    spans: list[dict],
    attribute_length_limit: int,
    resolvable_payload_refs: set[str],
) -> str:
    """
    Returns 'ADMISSIBLE', 'DEGRADED', or 'INADMISSIBLE'.
    Fails closed: any ambiguity resolves to a stricter verdict.
    """
    present_ids = {s["span_id"] for s in spans}

    for span in spans:
        attrs = span.get("attributes", {})

        # Structural closure: every referenced parent must be present.
        parent = span.get("parent_span_id")
        if parent is not None and parent not in present_ids:
            raise ReplayInadmissibleError(
                f"span {span['span_id']} references absent parent {parent}; "
                "trace tree is not closed under retained set"
            )

        for key, value in attrs.items():
            if not (key.startswith("gen_ai.tool.call.arguments")
                    or key.startswith("gen_ai.completion")
                    or key.startswith("gen_ai.tool.call.result")):
                continue

            if isinstance(value, str) and len(value) == attribute_length_limit:
                # Exact-length is indistinguishable from truncated. Fail closed.
                raise ReplayInadmissibleError(
                    f"span {span['span_id']} attribute {key} length == "
                    f"limit {attribute_length_limit}; treated as truncated"
                )

            if value == TRUNCATION_SENTINEL:
                ref = attrs.get(f"{key}.ref")
                if ref is None or ref not in resolvable_payload_refs:
                    raise ReplayInadmissibleError(
                        f"span {span['span_id']} attribute {key} is redacted "
                        f"with no resolvable payload ref"
                    )

    # If we reached here, the trace is structurally and payload-complete.
    return "ADMISSIBLE"
