# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-re-label-tainted-memory-after-a-tool-output-clears-a-dynamic-information-flow-check.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-re-label-tainted-memory-after-a-tool-output-clears-a-dynamic-information-flow-check.warrant.json
# Markdown SHA-256:   474a89a2cb6f9367ff7f67221d99cedc691193b202f01566f129f3a65205fbde
# Code AST SHA-256:   a93a353fe83fae5d3d9dd865b8e15d23c930b865933238cd6ec804b50454a082
# Verified Classes:   Integrity, Label, Slot, TaintLaunderingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Dict, Optional


class Integrity(IntEnum):
    LOW = 0       # web_untrusted
    MEDIUM = 1    # tool-derived, not declassified
    HIGH = 2      # authorized declassification only


@dataclass(frozen=True)
class Label:
    source: str
    integrity: Integrity

    def join(self, other: "Label") -> "Label":
        # Least upper bound: integrity is the MIN (taint dominates).
        return Label(
            source=f"{self.source}|{other.source}",
            integrity=Integrity(min(self.integrity, other.integrity)),
        )


@dataclass
class Slot:
    slot_id: str
    value_hash: str
    label: Label
    epoch: int = 0
    declass_records: Dict[int, str] = field(default_factory=dict)  # epoch -> authority


class TaintLaunderingError(RuntimeError):
    """Raised when a label improvement lacks an epoch-scoped declassification record."""


AUTHORIZED_DECLASSIFIERS = {
    # (tool_or_authority, from_source, to_integrity)
    ("tool:authorized_redactor", "web_untrusted", Integrity.MEDIUM),
}


def try_relabel(slot: Slot, proposed: Label, justification: str) -> Slot:
    """
    Attempt to improve a slot's label. Permitted ONLY if:
      - the proposed integrity is not higher than current, OR
      - a declassification record exists for THIS slot's current epoch
        and the authority is in the authorized set.
    Value-equality with any other clean value is never sufficient.
    """
    if proposed.integrity <= slot.label.integrity:
        # No improvement requested; conservative join is safe.
        slot.label = slot.label.join(proposed)
        return slot

    authority = slot.declass_records.get(slot.epoch)
    if authority is None:
        raise TaintLaunderingError(
            f"slot {slot.slot_id} epoch {slot.epoch}: attempted upgrade "
            f"{slot.label.integrity.name}->{proposed.integrity.name} via "
            f"'{justification}' with no epoch-scoped declassification record"
        )

    if (authority, slot.label.source, proposed.integrity) not in AUTHORIZED_DECLASSIFIERS:
        raise TaintLaunderingError(
            f"slot {slot.slot_id}: authority '{authority}' not authorized to "
            f"declassify source '{slot.label.source}' to {proposed.integrity.name}"
        )

    slot.label = proposed
    return slot


def consolidate(origin: Slot, derived_value_hash: str, derived_label: Label) -> Slot:
    """
    The defective path from the incident: value equality used as provenance
    equality. This function MUST NOT upgrade origin's label even when
    derived_value_hash == origin.value_hash and derived_label is clean.
    """
    if derived_value_hash == origin.value_hash:
        # Same bytes, different provenance path. Join, never overwrite.
        # Any attempted upgrade here is laundering.
        proposed = derived_label
        if proposed.integrity > origin.label.integrity:
            raise TaintLaunderingError(
                f"laundering attempt on {origin.slot_id}: derived clean value "
                f"'{derived_label.source}' compares equal to tainted origin; "
                f"value equality is not declassification"
            )
        origin.label = origin.label.join(proposed)
    return origin
