# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-prompt-injection-taint-survive-a-sanitizing-tool-but-die-at-a-memory-write-boundary-and-what-breaks-when-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-prompt-injection-taint-survive-a-sanitizing-tool-but-die-at-a-memory-write-boundary-and-what-breaks-when-it-does-not.warrant.json
# Markdown SHA-256:   41a507fa3cb78a61470501bf3decd50cbbb7885f97ccfd298a29725da2e1406b
# Code AST SHA-256:   d722be43c4e16a00660839fdf285cec1d31620fe2dda867b44bf6d1726332837
# Verified Classes:   TaintLaunderingError, Label
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a label is cleared or replaced rather than joined."""
    pass


class Label:
    CLEAN = frozenset()
    def __init__(self, tags, declassified_by=None):
        self.tags = frozenset(tags)
        self.declassified_by = declassified_by or frozenset()

    def join(self, other):
        return Label(self.tags | other.tags,
                     self.declassified_by | other.declassified_by)

    def is_tainted(self):
        return bool(self.tags)


def sanitize(value, label, tool_id):
    # Content transform only. Annotate; never clear.
    if not label.is_tainted():
        return value, label
    return value, Label(label.tags, label.declassified_by | {tool_id})


def memory_write(store, key, value, label):
    prior = store.get(key, (None, Label.CLEAN))
    prior_label = prior[1] if isinstance(prior, tuple) else Label.CLEAN
    joined = prior_label.join(label)
    if label.is_tainted() and not joined.is_tainted():
        raise TaintLaunderingError(
            f"write to {key!r} would clear taint from {label.tags!r}"
        )
    store[key] = (value, joined)
    return joined


def subagent_call_by_reference(store, key, caller_label, rederive):
    # Reference-pass must re-derive labels from provenance at read site.
    _, recorded = store[key]
    derived = rederive(key)
    effective = recorded.join(derived).join(caller_label)
    if recorded.is_tainted() and not effective.is_tainted():
        raise TaintLaunderingError(
            f"reference pass to {key!r} dropped taint via stale label"
        )
    return store[key][0], effective


def sink_admit(value, label, trusted_declassifiers):
    if not label.is_tainted():
        return True
    if label.declassified_by and label.declassified_by <= trusted_declassifiers:
        return True
    raise TaintLaunderingError(
        f"sink refused tainted value: tags={label.tags!r} "
        f"declassified_by={label.declassified_by!r}"
    )
