# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-taint-labels-survive-a-tool-round-trip-but-the-provenance-edge-is-severed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-taint-labels-survive-a-tool-round-trip-but-the-provenance-edge-is-severed.warrant.json
# Markdown SHA-256:   8f63d244b229d40c262e83380ac4bcdf1728dfcb7e610218b4f4c45931ceda7a
# Code AST SHA-256:   05f3e429a1af8665ea074f6c40bd50699ced3b8a491ceff572978a66a833a1d5
# Verified Classes:   SeveredProvenanceEdge, ToolOutput, TurnContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class SeveredProvenanceEdge(RuntimeError):
    """Raised when a tainted turn produces an action argument with no provenance edge.

    This is the severed-edge condition: the taint label survived the tool
    round-trip but the derivation edge from source span to argument value did not.
    """


@dataclass(frozen=True)
class ToolOutput:
    fields: dict            # field name -> value
    provenance: dict        # field name -> frozenset of source span ids
    emits_provenance: bool  # did the tool declare + honor the contract?


@dataclass
class TurnContext:
    taint_labels: FrozenSet[str] = field(default_factory=frozenset)
    ingested_spans: FrozenSet[str] = field(default_factory=frozenset)


def ingest_untrusted(ctx: TurnContext, span_id: str, label: str) -> None:
    ctx.taint_labels = ctx.taint_labels | {label}
    ctx.ingested_spans = ctx.ingested_spans | {span_id}


def absorb_tool_output(ctx: TurnContext, out: ToolOutput) -> dict:
    """Fold a tool output back into the turn, normalizing provenance.

    If the tool did not emit provenance, every field inherits the union of all
    ingested untrusted spans (maximal taint). This is the edge-preserving
    fallback that prevents silent severance.
    """
    if out.emits_provenance:
        merged = {k: frozenset(v) for k, v in out.provenance.items()}
    else:
        inherited = frozenset(ctx.ingested_spans)
        merged = {k: inherited for k in out.fields}
    return merged


def check_action_boundary(
    ctx: TurnContext,
    argument_name: str,
    argument_provenance: FrozenSet[str],
) -> None:
    """Enforce: a tainted turn may never yield an action arg with empty provenance."""
    if ctx.taint_labels and not argument_provenance:
        raise SeveredProvenanceEdge(
            f"argument {argument_name!r} has no provenance edge while turn "
            f"carries taint labels {sorted(ctx.taint_labels)}; "
            f"tool round-trip likely dropped the derivation edge"
        )
    # Over-attribution guard: provenance present but no label is also a bug.
    if argument_provenance and not ctx.taint_labels:
        raise SeveredProvenanceEdge(
            f"argument {argument_name!r} cites spans {sorted(argument_provenance)} "
            f"but turn has no taint labels; label was dropped at ingest"
        )


def run_side_effecting_call(ctx: TurnContext, out: ToolOutput, arg_field: str) -> None:
    prov = absorb_tool_output(ctx, out)
    check_action_boundary(ctx, arg_field, prov.get(arg_field, frozenset()))
    # ... invoke the privileged tool only after the invariant holds ...
