# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-provenance-label-after-tool-call-graph-re-entry-rather-than-propagate-it.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-provenance-label-after-tool-call-graph-re-entry-rather-than-propagate-it.warrant.json
# Markdown SHA-256:   56887fe14c2b6fe8467df8b78bd9dae331c1b8eb8acb33817e3c34dcb03a8dbc
# Code AST SHA-256:   5197758adfddda0c2b7f24a9e0ba81378e4c409d5cd965c9520230d3b415edd8
# Verified Classes:   ProvenanceLaunderingError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a tool result re-enters on an instruction edge carrying
    content byte-identical to an untrusted span, without a recorded relabel."""
    pass


@dataclass(frozen=True)
class Span:
    span_id: str
    trust: str          # "trusted" | "untrusted"
    origin: str         # "user" | "retrieval" | "tool:write_state" | ...
    content: str


def label_tool_result(
    result_span: Span,
    tool_trust: str,
    edge_type: str,                       # "data" | "instruction"
    untrusted_working_set: list[Span],
    echo_min_len: int = 24,
) -> Span:
    """Decide whether to propagate or invalidate-and-relabel a tool result.

    Propagate on data edges; invalidate-and-relabel on instruction edges.
    On instruction edges, an echo of untrusted content forces the result
    to the minimum trust of the echoed span and the tool.
    """
    if edge_type not in ("data", "instruction"):
        raise ProvenanceLaunderingError(f"unknown edge_type {edge_type!r}")

    if edge_type == "data":
        # Monotonic join: label travels with bytes.
        return result_span

    # Instruction edge: the old label is discarded. New trust is the edge's
    # channel trust, floored by any echoed untrusted content.
    new_trust = "trusted" if tool_trust == "trusted" else "untrusted"
    for prior in untrusted_working_set:
        if prior.trust != "untrusted":
            continue
        probe = prior.content[: max(echo_min_len, 1)]
        if len(probe) >= echo_min_len and probe in result_span.content:
            # Echo detected: launder closed. Downgrade and require relabel.
            new_trust = "untrusted"
            return Span(
                span_id=result_span.span_id,
                trust=new_trust,
                origin=f"relabel:{prior.span_id}",
                content=result_span.content,
            )
    return Span(
        span_id=result_span.span_id,
        trust=new_trust,
        origin=result_span.origin,
        content=result_span.content,
    )


def assert_no_laundering(spans: list[Span], untrusted: list[Span]) -> None:
    """Post-condition check: no trusted span may contain an untrusted echo
    without a relabel origin. Raise if the invariant is violated."""
    for s in spans:
        if s.trust != "trusted" or s.origin.startswith("relabel:"):
            continue
        for u in untrusted:
            if len(u.content) >= 24 and u.content[:24] in s.content:
                raise ProvenanceLaunderingError(
                    f"trusted span {s.span_id} contains echo of untrusted "
                    f"{u.span_id} with no relabel_event; provenance laundered "
                    f"across an instruction edge"
                )
