# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tainted-memory-write-rather-than-propagate-a-provenance-label-through-it.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tainted-memory-write-rather-than-propagate-a-provenance-label-through-it.warrant.json
# Markdown SHA-256:   329cca5b0195ae789286ca6ebd0290058e44cfe8a4a4de71bf09e38ab26bea5e
# Code AST SHA-256:   2ba2c04a7fb5e3e6275feed5cf18ca22af8ec6b3938950e496b5f2dde9f6086a
# Verified Classes:   FusedTaintWriteError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class FusedTaintWriteError(RuntimeError):
    """Raised when a derived memory write fuses trusted and untrusted spans
    and targets an authority-bearing tier without intact span provenance."""
    pass


def admit_memory_write(
    artifact,
    tier: str,
    authority_bearing_tiers=frozenset({"trusted_semantic", "shared_kb"}),
) -> None:
    """Enforce the separability invariant at the memory-write boundary.

    artifact must expose:
      - labels: set[str]  (e.g. {"internal", "web"})
      - separable: bool   (True iff span offset maps survived transformation)
      - source_spans: list[dict]  (required when separable)
    """
    labels = set(artifact.labels)
    untrusted = {l for l in labels if l.startswith(("web", "untrusted", "peer"))}
    trusted = labels - untrusted

    if not untrusted:
        return  # clean write, no taint to track

    if tier not in authority_bearing_tiers:
        return  # quarantine tier accepts fused writes

    # Mixed provenance AND authority-bearing tier: separability is mandatory.
    if trusted and untrusted and not artifact.separable:
        raise FusedTaintWriteError(
            f"Refusing fused write to authority tier '{tier}': "
            f"labels={sorted(labels)} with no span provenance. "
            f"Route to quarantine tier with fusion:true marker and "
            f"require re-derivation before promotion."
        )

    if artifact.separable and not artifact.source_spans:
        raise FusedTaintWriteError(
            f"separable=True but source_spans empty for tier '{tier}'; "
            f"cannot verify label-to-span mapping."
        )
