# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-boundary-be-drawn-between-poisoning-detection-and-provenance-auditing-in-persistent-vector-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-boundary-be-drawn-between-poisoning-detection-and-provenance-auditing-in-persistent-vector-stores.warrant.json
# Markdown SHA-256:   2dcdcb2bc0b01da23b6c6fc03d49079439a7ae59f59986992ddfd1662479ce4b
# Code AST SHA-256:   de9d729e7f614fc7e5076e8bd1914735edbf8f4e097363dfc3a71401746f499c
# Verified Classes:   ProvenanceMutationViolation, VectorStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceMutationViolation(RuntimeError):
    """Raised when a detection-initiated mutation would overwrite a provenance link's referent."""
    pass


class VectorStore:
    def __init__(self):
        self.vectors = {}          # vector_id -> payload
        self.provenance = {}       # vector_id -> {parent_vector_id, ingest_ts, ...}
        self.transition_log = []   # append-only: dicts of provenance transitions

    def tombstone(self, vector_id, cause, detector_run_id=None):
        if vector_id not in self.vectors:
            raise ProvenanceMutationViolation(
                f"tombstone target {vector_id} absent; refusing to write dangling transition"
            )
        prior = self.provenance.get(vector_id, {}).get("parent_vector_id")
        # Enforce: append transition BEFORE mutating live state.
        transition = {
            "vector_id": vector_id,
            "prior_state": "live",
            "new_state": "tombstoned",
            "cause": cause,
            "detector_run_id": detector_run_id,
            "prior_parent_vector_id": prior,
        }
        self.transition_log.append(transition)
        # Only now mutate the live store.
        self.vectors.pop(vector_id, None)

    def audit_parent_reference(self, vector_id):
        """Audit must resolve parent links against the transition log, never live state."""
        for entry in reversed(self.transition_log):
            if entry["vector_id"] == vector_id and entry["prior_parent_vector_id"] is not None:
                return entry["prior_parent_vector_id"]
        live = self.provenance.get(vector_id, {}).get("parent_vector_id")
        if live is not None and live not in self.vectors:
            # Dangling reference with no logged transition: invariant broken.
            raise ProvenanceMutationViolation(
                f"vector {vector_id} references absent parent {live} with no logged transition; "
                f"detection mutated provenance without recording it"
            )
        return live
