# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-safety-critical-span-when-its-semantic-convention-attribute-set-is-internally-inconsistent.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-safety-critical-span-when-its-semantic-convention-attribute-set-is-internally-inconsistent.warrant.json
# Markdown SHA-256:   a3a77facd9c9af48e6429f2c40cf4067728abe224803b85f3e6bab6c1058717d
# Code AST SHA-256:   6052c49be7e0d0ec922f86c3d790ad494aebbc826994ceb6547c5061acc29e0f
# Verified Classes:   IncoherentSafetySpanError, SafetySpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class IncoherentSafetySpanError(RuntimeError):
    """Raised when a safety-critical span's attribute set violates a
    semantic-convention entailment and therefore must not be emitted."""
    pass


# Entailment rules keyed by operation class. Each rule is a predicate over
# the closed attribute dict; a span is emittable iff every rule returns True.
ENTAILMENTS: dict[str, list[tuple[str, Any]]] = {
    "execute_tool": [
        (
            "deny_all_with_egress_implies_noncompleted",
            lambda a: not (
                a.get("gen_ai.agent.sandbox.network_policy") == "deny_all"
                and a.get("gen_ai.agent.sandbox.network_egress_attempts", 0) > 0
                and a.get("gen_ai.agent.sandbox.execution_status") == "completed"
            ),
        ),
        (
            "completed_implies_no_escape",
            lambda a: not (
                a.get("gen_ai.agent.sandbox.execution_status") == "completed"
                and a.get("gen_ai.agent.sandbox.escape_detected") is True
            ),
        ),
        (
            "policy_violation_implies_escape_or_blocked",
            lambda a: not (
                a.get("gen_ai.agent.sandbox.network_egress_attempts", 0) > 0
                and a.get("gen_ai.agent.sandbox.execution_status") == "completed"
                and a.get("gen_ai.agent.sandbox.escape_detected") is False
                and a.get("gen_ai.agent.sandbox.network_policy") == "deny_all"
            ),
        ),
    ],
}

SAFETY_CRITICAL_OPS = frozenset({"execute_tool"})


@dataclass
class SafetySpan:
    operation: str
    attributes: dict[str, Any] = field(default_factory=dict)
    refused: bool = False
    refusal_reason: str | None = None


def emit_safety_span(span: SafetySpan) -> SafetySpan:
    """Atomically validate the entailment closure and emit, or refuse loudly."""
    if span.operation not in SAFETY_CRITICAL_OPS:
        return span  # advisory telemetry, no gate

    rules = ENTAILMENTS.get(span.operation, [])
    for rule_name, predicate in rules:
        if not predicate(span.attributes):
            span.refused = True
            span.refusal_reason = rule_name
            # Loud refusal: companion event carries the violated entailment
            # and the offending attribute set so the SLO evaluator can
            # distinguish "nothing happened" from "contradiction caught".
            raise IncoherentSafetySpanError(
                f"refusing to emit safety-critical span op={span.operation!r}: "
                f"violated entailment {rule_name!r} with attributes "
                f"{span.attributes!r}"
            )
    return span


# Reproduces the observed incident: policy-layer and kernel-layer writers
# merged into a contradictory attribute set that passed schema validation.
observed = SafetySpan(
    operation="execute_tool",
    attributes={
        "gen_ai.tool.name": "python_sandbox",
        "gen_ai.agent.sandbox.escape_detected": False,
        "gen_ai.agent.sandbox.network_egress_attempts": 3,
        "gen_ai.agent.sandbox.network_policy": "deny_all",
        "gen_ai.agent.sandbox.execution_status": "completed",
    },
)

try:
    emit_safety_span(observed)
except IncoherentSafetySpanError as exc:
    print(f"REFUSED + PAGED: {exc}")
