# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-compaction-induced-tombstone-resurrection-during-concurrent-multi-agent-writes-to-a-shared-episodic-store.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-compaction-induced-tombstone-resurrection-during-concurrent-multi-agent-writes-to-a-shared-episodic-store.warrant.json
# Markdown SHA-256:   61eca15399981e1b359a1b5e39412f77e612583a43bdee6b1f59692b3c19465f
# Code AST SHA-256:   65adf6f55205c4f7bc533a8d007700df3ba6cd73171c646324954e0f59da23d8
# Verified Classes:   TombstoneResurrectionError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class TombstoneResurrectionError(RuntimeError):
    """Raised when a live record's provenance shows it was retracted after its last write."""


def assert_not_resurrected(record: dict, tombstone_seqs: dict[str, int]) -> None:
    """
    Enforce the compaction-boundary invariant:
        live(record)  =>  record['last_modified_seq'] > tombstone_seqs[record['id']]

    A violation means a compaction pass merged a stale record forward without
    carrying its tombstone. The instance must halt and reconcile, not act.
    """
    rid = record["id"]
    deleted_seq = tombstone_seqs.get(rid)
    if deleted_seq is None:
        return  # no tombstone ever recorded; nothing to resurrect

    if record.get("live", True) and record["last_modified_seq"] <= deleted_seq:
        raise TombstoneResurrectionError(
            f"record {rid!r} is marked live but last_modified_seq="
            f"{record['last_modified_seq']} <= deleted_seq={deleted_seq}; "
            f"compaction boundary crossed without tombstone propagation. "
            f"Halt and reconcile before acting on this record."
        )


def guarded_retrieve(store, record_id: str, tombstone_seqs: dict[str, int]) -> dict:
    record = store.get(record_id)
    assert_not_resurrected(record, tombstone_seqs)
    return record
