# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-span-the-guardrail-evidence-boundary-in-trace-native-safety-enforcement.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-span-the-guardrail-evidence-boundary-in-trace-native-safety-enforcement.warrant.json
# Markdown SHA-256:   68b79c30aad306f7774337a4e6f9f60fb53145a0fbc0fb187709aed359258df3
# Code AST SHA-256:   cc4ea43772d29e049d4507f958a70a8fbc5e5e06e958a4ad9420dae5689457c7
# Verified Classes:   SpanDecision, UnacknowledgedGuardrailSpan, DecisionSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum


class SpanDecision(Enum):
    ALLOW = "allow"
    BLOCK = "block"
    REDACT = "redact"


class UnacknowledgedGuardrailSpan(RuntimeError):
    """Raised when an executor tries to advance on a guardrail verdict whose
    decision span was not recorded and acknowledged by the collector.

    This is the trace-native enforcement boundary: a block is not durable
    until its span is acknowledged, and an unrecorded verdict must never be
    read as 'allow'.
    """


@dataclass(frozen=True)
class DecisionSpan:
    verdict: SpanDecision
    is_recording: bool          # False for NonRecordingSpan (sampled out)
    exported_ack: bool          # True only if collector acknowledged
    dropped: bool               # True if BatchSpanProcessor dropped on end()


def commit_guardrail_decision(span: DecisionSpan, tool_name: str) -> SpanDecision:
    """Gate tool continuation on a durable, recorded, acknowledged decision span.

    Returns the verdict the executor is permitted to act on. Raises if the
    evidence channel cannot prove the decision was emitted.
    """
    if not span.is_recording:
        # Sampled-out: set_attribute/set_status were no-ops. A 'block' here
        # is indistinguishable from 'allow' downstream. Fail closed.
        raise UnacknowledgedGuardrailSpan(
            f"decision span for tool={tool_name!r} is non-recording "
            f"(sampled out); verdict={span.verdict.value} cannot be trusted"
        )

    if span.dropped:
        raise UnacknowledgedGuardrailSpan(
            f"decision span for tool={tool_name!r} was dropped by the span "
            f"processor; evidence channel is lossy, refusing to advance"
        )

    if not span.exported_ack:
        raise UnacknowledgedGuardrailSpan(
            f"decision span for tool={tool_name!r} not acknowledged by "
            f"collector; verdict={span.verdict.value} is not yet durable"
        )

    # Only now is the verdict authoritative for the state machine.
    return span.verdict


def executor_step(span: DecisionSpan, tool_name: str) -> str:
    verdict = commit_guardrail_decision(span, tool_name)
    if verdict is SpanDecision.BLOCK:
        return "halt_and_report"
    if verdict is SpanDecision.REDACT:
        return "invoke_with_redaction"
    return "invoke"


# --- demonstration of the boundary ---

if __name__ == "__main__":
    # Healthy path: recorded, acknowledged, allow.
    ok = DecisionSpan(SpanDecision.ALLOW, True, True, False)
    assert executor_step(ok, "file.write") == "invoke"

    # The bug: block verdict, span dropped on end(). Must raise, not proceed.
    lossy = DecisionSpan(SpanDecision.BLOCK, True, False, True)
    try:
        executor_step(lossy, "shell.exec")
    except UnacknowledgedGuardrailSpan as e:
        print(f"fail-closed: {e}")

    # The silent fail-open: sampled-out block. Must raise.
    sampled_out = DecisionSpan(SpanDecision.BLOCK, False, False, False)
    try:
        executor_step(sampled_out, "http.post")
    except UnacknowledgedGuardrailSpan as e:
        print(f"fail-closed: {e}")
