# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-tainted-memory-before-semantic-distillation-not-merely-filter-the-current-context.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-tainted-memory-before-semantic-distillation-not-merely-filter-the-current-context.warrant.json
# Markdown SHA-256:   6a9d9224d31ab1f6e9f0c03241b1709232d2ab17a68ab2f268480bfef9e01cd4
# Code AST SHA-256:   b3b265c9acb517be8a36e0260257dc3884971fe836cc2f4ca28843e0481f298a
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a distillation write would drop a taint label,
    converting untrusted source content into a default-clean memory record."""
    pass


CLEAN = "clean"
TAINTED = "tainted"


def distill_and_commit(source_text: str,
                       source_label: str,
                       summarizer,
                       memory_store) -> dict:
    """Distill source content into a memory record, preserving provenance.

    The invariant: a memory record's label may never be weaker (more clean)
    than the label of the source it was derived from. If the write path
    cannot carry the label through, the commit is refused.
    """
    if source_label not in (CLEAN, TAINTED):
        raise TaintLaunderingError(
            f"unknown source label {source_label!r}; refusing to distill"
        )

    # Distillation is content-only; it has no access to provenance.
    summary = summarizer(source_text)

    # The write path must inherit, never default, the label.
    record = {
        "fact": summary,
        "label": source_label,
        "requires_corroboration": source_label == TAINTED,
    }

    # Guardrail: reject any attempt to downgrade a tainted source to clean.
    if source_label == TAINTED and record.get("label") == CLEAN:
        raise TaintLaunderingError(
            "distillation dropped taint label; quarantining instead of committing"
        )

    if record["requires_corroboration"]:
        # Tainted derivatives are stored but flagged; they are not authoritative.
        memory_store.write_quarantined(record)
    else:
        memory_store.write(record)

    return record


def assert_fact(record: dict, corroborating_source: str | None) -> str:
    """An assertion drawn from memory must respect the corroboration flag."""
    if record.get("requires_corroboration") and corroborating_source is None:
        raise TaintLaunderingError(
            "refusing to assert a fact derived from a tainted source "
            "without independent corroboration"
        )
    return record["fact"]
