# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rolls-back-a-poisoned-memory-entry-while-a-concurrent-consolidation-pass-has-already-derived-a-semantic-summary-from-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rolls-back-a-poisoned-memory-entry-while-a-concurrent-consolidation-pass-has-already-derived-a-semantic-summary-from-it.warrant.json
# Markdown SHA-256:   306e56fc3adcd3cdfe3c2d956868d9d60d272ced53762ee5f405a8c46349ee87
# Code AST SHA-256:   df831d75d87cc9950b37ab6572c0300853210fbb0269c81992011052a4a8ff96
# Verified Classes:   PoisonedDerivativeOrphanedError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class PoisonedDerivativeOrphanedError(RuntimeError):
    """Raised when a source is revoked but a derivative that read a poisoned
    version of it remains retrievable. The store is in an inconsistent state:
    clean source, poisoned derivative, no detector watching the derivative."""
    pass


def rollback_entry(store, entry_id: str, revoke_version: int) -> None:
    # 1. Revoke the source version.
    store.revoke(entry_id, revoke_version)

    # 2. Compute the transitive closure of derivatives whose PINNED source
    #    versions include the revoked version. any-semantics, not all.
    tainted = store.derivatives_reading(entry_id, revoke_version)

    # 3. In the SAME transaction, mark every tainted derivative and pull it
    #    from the retrieval index. If any step fails, the whole rollback
    #    aborts — a half-rolled-back store is the failure mode we are fixing.
    with store.transaction():
        for deriv_id in tainted:
            store.mark_tainted(deriv_id, reason=f"source {entry_id}@{revoke_version} revoked")
            store.remove_from_index(deriv_id)

    # 4. Verify the invariant: no retrievable entry may transitively read the
    #    revoked version. If verification fails, we did not actually roll back;
    #    we amputated the source and left the metastasis.
    reachable = store.retrievable_entries_reading(entry_id, revoke_version)
    if reachable:
        raise PoisonedDerivativeOrphanedError(
            f"rollback of {entry_id}@{revoke_version} left "
            f"{len(reachable)} retrievable derivative(s): {reachable}. "
            f"Store is inconsistent; quarantine and re-derive before serving."
        )
