# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-provenance-when-its-own-pruning-policy-rewrites-the-transcript-under-a-latency-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-provenance-when-its-own-pruning-policy-rewrites-the-transcript-under-a-latency-budget.warrant.json
# Markdown SHA-256:   acaf9e6c910d7312e4f3de214d252d10bb15f81a4cce02e5d636fdf96606e178
# Code AST SHA-256:   dbeda98e11610fca1c0f9a448013bf418803b00c48d7f7773cde07700f5262da
# Verified Classes:   PruneAction, ProvenanceViolation, Artifact, Span, ProvenanceTable
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class PruneAction(Enum):
    DROP = "drop"
    SUMMARIZE = "summarize"


class ProvenanceViolation(RuntimeError):
    """Raised when a tool call depends on a span that was rewritten, not dropped."""


@dataclass
class Artifact:
    ref: str
    content: str


@dataclass
class Span:
    span_id: str
    artifact_ref: Optional[str]  # None once summarized; set for live artifacts


@dataclass
class ProvenanceTable:
    # (message_id, arg_path) -> artifact_ref
    edges: dict = field(default_factory=dict)

    def resolve(self, message_id: str, arg_path: str) -> Optional[str]:
        return self.edges.get((message_id, arg_path))


def commit_prune_set(
    spans: dict[str, Span],
    prune_set: list[tuple[str, PruneAction]],
    latency_expired: bool,
) -> list[str]:
    """
    Commit a model-proposed prune set under a latency budget.
    Returns the list of span_ids actually summarized (rewritten).
    """
    if latency_expired:
        # Only drops may be committed on a partial set.
        for span_id, action in prune_set:
            if action is PruneAction.SUMMARIZE:
                continue  # defer; do not rewrite under expired budget
            spans[span_id].artifact_ref = None
        return []

    summarized = []
    for span_id, action in prune_set:
        if action is PruneAction.SUMMARIZE:
            spans[span_id].artifact_ref = None  # content becomes a view, not a source
            summarized.append(span_id)
        else:
            spans[span_id].artifact_ref = None
    return summarized


def dispatch_tool_call(
    tool_name: str,
    args: dict[str, str],
    arg_provenance: dict[str, tuple[str, str]],  # arg_name -> (message_id, arg_path)
    provenance: ProvenanceTable,
    spans: dict[str, Span],
) -> str:
    """
    Post-generation provenance check: every argument derived from a prior
    tool result must resolve to a *live* artifact reference.
    """
    for arg_name, (message_id, arg_path) in arg_provenance.items():
        ref = provenance.resolve(message_id, arg_path)
        if ref is None:
            # No provenance edge at all: caller must supply one.
            raise ProvenanceViolation(
                f"{tool_name}.{arg_name} has no provenance edge "
                f"({message_id},{arg_path})"
            )
        span = spans.get(ref)
        if span is None or span.artifact_ref is None:
            raise ProvenanceViolation(
                f"{tool_name}.{arg_name} derives from artifact {ref} "
                f"which was rewritten (summarized); re-fetch required"
            )
    return f"dispatched {tool_name}"


# --- observed failure reproduction ---
spans = {
    "s_read_file": Span("s_read_file", artifact_ref="art_config"),
    "s_validate1": Span("s_validate1", artifact_ref="art_validate1"),
}
provenance = ProvenanceTable(
    edges={
        ("msg_9", "region"): "art_config",   # derived from the read_file artifact
    }
)

# Step 6: policy summarizes the read_file span (rewrite).
commit_prune_set(
    spans,
    [("s_read_file", PruneAction.SUMMARIZE)],
    latency_expired=False,
)

# Step 9: model proposes validate(region="eu-west") using the summary as source.
try:
    dispatch_tool_call(
        "validate",
        {"region": "eu-west"},
        {"region": ("msg_9", "region")},
        provenance,
        spans,
    )
except ProvenanceViolation as e:
    # Correct behavior: block, re-fetch art_config, then retry.
    print(f"blocked: {e}")
    spans["s_read_file"].artifact_ref = "art_config"  # re-fetch restores live ref
    print(dispatch_tool_call(
        "validate",
        {"region": "eu-west"},
        {"region": ("msg_9", "region")},
        provenance,
        spans,
    ))
