# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-genai-agent-span-s-tool-call-child-as-non-retryable-when-the-parent-span-reports-error-type-timeout.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-genai-agent-span-s-tool-call-child-as-non-retryable-when-the-parent-span-reports-error-type-timeout.warrant.json
# Markdown SHA-256:   e21fa22a78169e1c19b69f46d53e88267f7f06889054067673716515ac0c541f
# Code AST SHA-256:   22fe707eaa88eaef9084b5ad37e68089ae4617b5742ddd227ab6d6fddf94d5a0
# Verified Classes:   ToolRetryAmbiguityError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ToolRetryAmbiguityError(RuntimeError):
    """Raised when a tool-call child span's retryability cannot be decided
    from its own attributes, and the parent's error.type must not be inherited."""


RETRYABLE_CHILD_ERROR_TYPES = frozenset({"timeout", "unavailable", "rate_limited"})


def decide_tool_retry(child_span: dict, parent_span: dict, tool_is_idempotent: bool) -> bool:
    child_status = child_span.get("status_code")  # "OK" | "ERROR" | "UNSET"
    child_error_type = child_span.get("error_type")
    parent_error_type = parent_span.get("error_type")

    # Child-level retryable error: trust the child, not the parent.
    if child_status == "ERROR" and child_error_type in RETRYABLE_CHILD_ERROR_TYPES:
        if tool_is_idempotent or child_span.get("idempotency_key"):
            return True
        raise ToolRetryAmbiguityError(
            f"tool {child_span.get('tool_name')} errored with {child_error_type} "
            f"but is non-idempotent and carries no idempotency key"
        )

    # Child succeeded or was cancelled mid-flight. Parent timeout is irrelevant
    # to the child's retry decision.
    if child_status in ("OK", "UNSET"):
        if child_status == "UNSET" and parent_error_type == "timeout" and not tool_is_idempotent:
            raise ToolRetryAmbiguityError(
                f"tool {child_span.get('tool_name')} is UNSET under a timed-out parent; "
                f"execution state unknown, manual reconciliation required"
            )
        return False

    # Child ERROR with a non-retryable error_type (e.g. invalid_argument).
    return False
