# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-taint-labels-as-monotonic-across-sandbox-re-entry.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-taint-labels-as-monotonic-across-sandbox-re-entry.warrant.json
# Markdown SHA-256:   a481e04cb2b3743c2de26053d1d68dd298910b0cf39221044f9ca27362b77c02
# Code AST SHA-256:   5b8eabc0410286ca981aa143fd46170503834abacc8587b8a13442d88e4ed787
# Verified Classes:   TaintMonotonicityError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class TaintMonotonicityError(RuntimeError):
    """Raised when a materialization path attempts to lower a value's taint label set."""
    pass


def materialize_value(stored_labels: frozenset, ambient_labels: frozenset,
                      reconstructed_labels: frozenset) -> frozenset:
    """
    Reconstruct the label set for a value crossing a sandbox re-entry boundary.

    Invariant: the returned set must be a superset of both stored and ambient labels.
    A content-addressed cache hit, deserialization, or IPC receive must call this.
    """
    required = stored_labels | ambient_labels
    if not reconstructed_labels >= required:
        missing = required - reconstructed_labels
        raise TaintMonotonicityError(
            f"label laundering at materialization boundary: "
            f"stored={sorted(stored_labels)} ambient={sorted(ambient_labels)} "
            f"reconstructed={sorted(reconstructed_labels)} missing={sorted(missing)}"
        )
    return reconstructed_labels


def read_from_content_addressed_store(key: str, store: dict,
                                      ambient_labels: frozenset) -> tuple:
    entry = store[key]
    # BUG PATTERN: naive path reconstructs from schema -> empty label set.
    # Correct path consults stored metadata and enforces monotonicity.
    labels = materialize_value(
        stored_labels=entry["labels"],
        ambient_labels=ambient_labels,
        reconstructed_labels=entry["labels"],  # must come from persisted metadata
    )
    return entry["value"], labels
