# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-memory-poisoning-attestation-as-a-per-write-invariant-rather-than-a-periodic-sweep.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-memory-poisoning-attestation-as-a-per-write-invariant-rather-than-a-periodic-sweep.warrant.json
# Markdown SHA-256:   bd69a45a78b999af737966eeafd9e0f041d08563100a3ae898191ca11b67611b
# Code AST SHA-256:   b303fd04c9ac9bcdbabd8510e4161a6a14909d7cfeea5d5efca5356a8b29c21b
# Verified Classes:   ProvenanceAttestationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceAttestationError(RuntimeError):
    """Raised when a store mutation lacks a valid per-write provenance gate."""
    pass


TRUSTED_SOURCE_CLASSES = frozenset({"internal_agent", "operator_signed"})


def commit_memory_write(store, chunk, provenance):
    """
    Commit a memory chunk only if its provenance gate passed in the same
    transaction. Attestation covers (data, provenance); a sweep over data
    alone would launder unverified writes.
    """
    if provenance is None:
        raise ProvenanceAttestationError(
            f"write of chunk {chunk.id!r} has no provenance record; "
            "refusing to commit data without committed provenance"
        )

    source_class = provenance.get("source_class")
    gate_decision = provenance.get("gate_decision")

    if source_class not in TRUSTED_SOURCE_CLASSES and gate_decision != "allow":
        raise ProvenanceAttestationError(
            f"chunk {chunk.id!r} from source_class={source_class!r} "
            f"has gate_decision={gate_decision!r}; untrusted write "
            "cannot enter the attested root"
        )

    # Atomic: data and provenance land together, or neither lands.
    with store.transaction() as tx:
        tx.put_data(chunk)
        tx.put_provenance(chunk.id, provenance)
        tx.extend_attestation_root(chunk, provenance)
    return True
