# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-vector-store-write-before-it-becomes-a-retrievable-memory-the-tombstone-before-embedding-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-vector-store-write-before-it-becomes-a-retrievable-memory-the-tombstone-before-embedding-boundary.warrant.json
# Markdown SHA-256:   3107d0353ac2199f87c23231e5328d0a6fb5577479cd8d594a7e92c410b708f7
# Code AST SHA-256:   d77b90384c4a3842226d1f884effb60dff628a6e321fb9c2de59870eacca16bd
# Verified Classes:   MemoryPoisoningBoundaryError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class MemoryPoisoningBoundaryError(RuntimeError):
    """Raised when a write would make an embedding retrievable without
    atomic provenance, or when a distillation would launder trust."""
    pass


TRUST_ORDER = {"unverified": 0, "corroborated": 1, "first_party": 2}


def atomic_write(store, embedding, provenance, trust_class, corroboration, staging_ns=None):
    if trust_class not in TRUST_ORDER:
        raise MemoryPoisoningBoundaryError(
            f"unknown trust_class {trust_class!r}; refusing write"
        )
    # Atomicity invariant: provenance and trust must ride the same record.
    record = {
        "embedding": embedding,
        "provenance": provenance,
        "trust_class": trust_class,
        "corroboration": corroboration,
    }
    if not store.supports_atomic_metadata():
        # Cannot guarantee zero retrieval window: stage, then promote.
        if staging_ns is None:
            raise MemoryPoisoningBoundaryError(
                "store lacks atomic metadata; staging namespace required to "
                "avoid a retrievable-unmarked window"
            )
        staged = store.put(staging_ns, record)
        store.promote_atomic(staged, target_ns="live")
        return staged
    return store.put("live", record)


def distill(store, parent_ids, derived_text, derived_embedding):
    parents = [store.get(pid) for pid in parent_ids]
    if not parents:
        raise MemoryPoisoningBoundaryError("distillation with no parents")
    # Anti-laundering invariant: derived trust <= min(parent trust).
    min_trust = min((p["trust_class"] for p in parents), key=lambda t: TRUST_ORDER[t])
    min_corr = min(p["corroboration"] for p in parents)
    if any(p["trust_class"] == "unverified" for p in parents):
        # A derived record inheriting an unverified parent must not be
        # written as first-party; force the inherited trust class.
        trust_class = min_trust
    else:
        trust_class = min_trust
    if TRUST_ORDER[trust_class] > TRUST_ORDER[min_trust]:
        raise MemoryPoisoningBoundaryError(
            f"distillation would promote trust from {min_trust} to {trust_class}; "
            "refusing to launder provenance"
        )
    return atomic_write(
        store,
        derived_embedding,
        provenance={"derived_from": parent_ids, "kind": "distillation"},
        trust_class=trust_class,
        corroboration=min_corr,
    )
