# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-injection-taint-at-the-memory-write-boundary-when-a-tool-output-is-re-serialized-through-a-lossy-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-injection-taint-at-the-memory-write-boundary-when-a-tool-output-is-re-serialized-through-a-lossy-schema.warrant.json
# Markdown SHA-256:   1fcd844bc633d14a8ccf4f73b9b6bfb5596e9b416f157076e6c0b94437a70458
# Code AST SHA-256:   cc2f94401d56bded139b570cc6e7b8767f31ca4a45f350a457ceb644cd8315d5
# Verified Classes:   TaintLossError, TaintedValue, TaintedRead, MemoryRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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

class TaintLossError(RuntimeError):
    """Raised when a tainted value would be persisted without its label."""

@dataclass(frozen=True)
class TaintedValue:
    payload: Any
    label: FrozenSet[str]

    def read(self) -> "TaintedRead":
        # Reading latches the label onto the reading frame; the frame
        # refuses to construct unlabeled records.
        return TaintedRead(self.payload, self.label)

class TaintedRead:
    def __init__(self, payload: Any, label: FrozenSet[str]):
        self._payload = payload
        self._label = label

    def extract(self, **fields: Any) -> "MemoryRecord":
        return MemoryRecord(fields=fields, taint=self._label)

@dataclass
class MemoryRecord:
    fields: dict
    taint: FrozenSet[str] = field(default_factory=frozenset)

    def __post_init__(self) -> None:
        if not self.taint:
            raise TaintLossError(
                f"refusing to persist unlabeled record: {self.fields!r}"
            )

def write_memory(record: MemoryRecord) -> None:
    # Serializer boundary: an unset label is an error, never a default of clean.
    if not isinstance(record, MemoryRecord) or not record.taint:
        raise TaintLossError(
            "memory write attempted without taint label; write path is unsound"
        )
    # ... persist record.fields alongside record.taint ...
    return None

def extract_and_persist(tool_result: TaintedValue, **extracted: Any) -> None:
    # The only sanctioned path: read through the envelope so the label latches.
    record = tool_result.read().extract(**extracted)
    write_memory(record)

# Correct path: label latches, record persists with taint.
extract_and_persist(
    TaintedValue(payload={"body": "..."}, label=frozenset({"untrusted_web"})),
    subject="user", predicate="authorized_email_to", object="ops@attacker.example",
)

# Failure path: a caller that bypasses the envelope and coerces a bare dict
# into a record loses the label and is rejected at the write boundary.
def unsafe_persist(raw: dict) -> None:
    record = MemoryRecord(fields=raw)  # taint defaults to empty
    write_memory(record)  # raises TaintLossError

try:
    unsafe_persist({"subject": "user", "predicate": "authorized_email_to",
                    "object": "ops@attacker.example"})
except TaintLossError as exc:
    print(f"blocked: {exc}")
