# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-has-silently-decoupled-from-its-causal-span-lineage-across-distributed-agent-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-has-silently-decoupled-from-its-causal-span-lineage-across-distributed-agent-traces.warrant.json
# Markdown SHA-256:   9c408eaa47e890a0df4348f2f0f4d68a73941776432b5651239a08f3ac88202a
# Code AST SHA-256:   585a9e128788a7f9336cf9acf42844d376d715c27cf359c184a56470181601a3
# Verified Classes:   TaintProvenanceGap, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TaintProvenanceGap(RuntimeError):
    """Raised when a span consumed state whose taint lineage was not carried
    across a memory/tool boundary, so inherited taint under-reports provenance."""
    pass


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    kind: str                      # "llm" | "tool" | "memory.get" | "memory.put" | "action"
    taint: set[str] = field(default_factory=set)
    payload_hash: str | None = None
    privileged: bool = False


def _ancestor_taint(span: Span, store: dict[str, Span]) -> set[str]:
    acc: set[str] = set()
    cur = store.get(span.parent_id) if span.parent_id else None
    while cur is not None:
        acc |= cur.taint
        cur = store.get(cur.parent_id) if cur.parent_id else None
    return acc


def correlate(span: Span, store: dict[str, Span],
              memory_writes: dict[str, str]) -> bool:
    """Enforce TaintProvenance subset-of CausalAncestor closure, treating
    memory reads as implicit edges to matching writes. Returns True if the
    span is safe to treat as clean; raises on a provenance gap."""
    inherited = _ancestor_taint(span, store)

    # Memory read: recover taint from the write that produced this payload.
    if span.kind == "memory.get" and span.payload_hash:
        writer_id = memory_writes.get(span.payload_hash)
        if writer_id is not None:
            writer = store[writer_id]
            if writer.taint - inherited:
                # Content crossed a boundary without a modeled lineage edge.
                raise TaintProvenanceGap(
                    f"span {span.span_id} read payload {span.payload_hash[:8]} "
                    f"tainted by {writer.taint - inherited} via {writer_id} "
                    f"with no causal ancestor carrying it"
                )
        elif span.payload_hash:
            # Non-empty read, zero tainted ancestors: provenance gap.
            raise TaintProvenanceGap(
                f"span {span.span_id} returned non-empty memory with no "
                f"tainted ancestor and no recorded writer"
            )

    if span.privileged:
        # Privileged boundary: inherited taint must cover re-derived taint.
        rederived = span.taint
        if rederived - inherited - {span.span_id}:
            raise TaintProvenanceGap(
                f"privileged span {span.span_id} executed with taint "
                f"{rederived - inherited} absent from its causal lineage"
            )

    return not (span.taint | inherited)
