# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundering-when-taint-tracked-retrieval-augmentation-shares-a-vector-index-across-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundering-when-taint-tracked-retrieval-augmentation-shares-a-vector-index-across-agents.warrant.json
# Markdown SHA-256:   d3e13268b81aef399847162696ef3dd195f054a1e50a3645cb610877b424b521
# Code AST SHA-256:   657875eab4c96acbee28b8fe030b5eeb9130eca29e3ca29ca77ef607cb92a337
# Verified Classes:   TaintPropagationError, VectorRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TaintPropagationError(RuntimeError):
    """Raised when a write cannot be proven clean or tainted under derivation rules."""
    pass


@dataclass
class VectorRecord:
    record_id: str
    text: str
    embedding: tuple  # simplified: unit vector stand-in
    untrusted: bool
    derivation: set = field(default_factory=set)


def cosine(a: tuple, b: tuple) -> float:
    return sum(x * y for x, y in zip(a, b))


def write_with_taint_propagation(
    new_text: str,
    new_embedding: tuple,
    declared_derivation: set,
    read_set: dict,          # record_id -> VectorRecord, as fetched at write time
    similarity_threshold: float = 0.78,
) -> VectorRecord:
    # Re-fetch taint at write time; never trust a cached read-time flag.
    live_taint = {rid: read_set[rid].untrusted for rid in read_set}

    # Under-propagation check: any undeclared tainted read that is
    # semantically close to the write forces taint inheritance.
    undeclared_tainted = []
    for rid, rec in read_set.items():
        if rid in declared_derivation:
            continue
        if live_taint.get(rid) and cosine(new_embedding, rec.embedding) >= similarity_threshold:
            undeclared_tainted.append(rid)

    if undeclared_tainted:
        # Backstop fired: agent paraphrased a tainted read without declaring it.
        # Inherit taint and record the detection for audit.
        derivation = declared_derivation | set(undeclared_tainted)
        untrusted = True
    else:
        derivation = set(declared_derivation)
        untrusted = any(live_taint.get(rid, True) for rid in derivation)

    # A declared derivation that references an unknown record means the
    # read log is incomplete; the invariant cannot be enforced.
    unknown = [rid for rid in derivation if rid not in read_set]
    if unknown:
        raise TaintPropagationError(
            f"derivation references unlogged reads {unknown}; "
            f"taint cannot be computed at write boundary"
        )

    return VectorRecord(
        record_id=hashlib.sha256(new_text.encode()).hexdigest()[:16],
        text=new_text,
        embedding=new_embedding,
        untrusted=untrusted,
        derivation=derivation,
    )
