# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-provenance-label-as-tainted-across-a-memory-write-boundary-rather-than-resetting-it-at-the-tool-output-edge.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-provenance-label-as-tainted-across-a-memory-write-boundary-rather-than-resetting-it-at-the-tool-output-edge.warrant.json
# Markdown SHA-256:   7d836caccd2d53b43db0cb49ebf1b45dec562bb005e6fbd2d2464de9c1c8d5cc
# Code AST SHA-256:   a31a33f89e0250117bedd20c2f2e255f85b244196b0cbb5d4c64f1ebbaa732ad
# Verified Classes:   ProvenanceTaintError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ProvenanceTaintError(RuntimeError):
    """Raised when a memory write would reset taint inherited from its inputs."""
    pass


TRUST_ORDER = {"trusted": 0, "untrusted:web": 1, "untrusted:tool": 1, "untrusted:external": 2}


def join_taint(inputs):
    """Provenance join: most-tainted input wins. Caller identity is never consulted."""
    worst = "trusted"
    for label in inputs:
        if TRUST_ORDER.get(label, 2) > TRUST_ORDER.get(worst, 0):
            worst = label
    return worst


def write_memory(record, contributing_inputs, declared_label):
    """Persist a memory record, enforcing taint inheritance across the write boundary."""
    inherited = join_taint(contributing_inputs)
    if TRUST_ORDER.get(declared_label, 0) < TRUST_ORDER.get(inherited, 0):
        raise ProvenanceTaintError(
            f"memory write declares {declared_label!r} but content lineage "
            f"is tainted {inherited!r}; reset at write boundary is forbidden"
        )
    record["provenance"] = inherited
    return record
