# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tainted-memory-write-rather-than-sanitize-it-in-place-label-laundering-through-tool-output-re-entry-an.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tainted-memory-write-rather-than-sanitize-it-in-place-label-laundering-through-tool-output-re-entry-an.warrant.json
# Markdown SHA-256:   ea3b0a95094d519ac52177ebbfde3a4410945033cabe128a2f68e9224fbdcd2d
# Code AST SHA-256:   3ef17d4cb8d33413059b495f004240eca5b85c52237a38d6fecd7d0e61a59474
# Verified Classes:   ProvenanceCollapseError, Label, MemoryWrite
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class ProvenanceCollapseError(RuntimeError):
    """Raised when a tainted write's recomputed label is weaker than its arrival label."""


@dataclass(frozen=True)
class Label:
    tags: FrozenSet[str]

    def __ge__(self, other: "Label") -> bool:
        return self.tags >= other.tags

    def join(self, other: "Label") -> "Label":
        return Label(self.tags | other.tags)


@dataclass
class MemoryWrite:
    content: str
    arrival_label: Label
    producer_id: str
    producer_is_label_monotone: bool
    content_is_instruction_eligible: bool
    quarantined: bool = False
    quarantine_label: Optional[Label] = None
    committed_label: Optional[Label] = None


def recompute_label(content: str) -> Label:
    # Content-only label derivation; cannot see the arrival edge.
    tags = set()
    if "http://" in content or "https://" in content:
        tags.add("external")
    return Label(frozenset(tags))


def gate_write(write: MemoryWrite) -> MemoryWrite:
    recomputed = recompute_label(write.content)
    provenance_intact = recomputed >= write.arrival_label

    if provenance_intact:
        write.committed_label = write.arrival_label
        return write

    # Provenance collapsed. Sanitize-in-place is only sound under both proofs.
    if write.producer_is_label_monotone and not write.content_is_instruction_eligible:
        write.committed_label = write.arrival_label
        return write

    write.quarantined = True
    write.quarantine_label = write.arrival_label
    raise ProvenanceCollapseError(
        f"write from producer {write.producer_id!r} arrived with "
        f"{sorted(write.arrival_label.tags)} but recomputes to "
        f"{sorted(recomputed.tags)}; quarantined, not sanitized"
    )
