# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-survived-provenance-sanitization-the-tombstone-lineage-resurrection-failure-in-provenance-tracked-ve.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-survived-provenance-sanitization-the-tombstone-lineage-resurrection-failure-in-provenance-tracked-ve.warrant.json
# Markdown SHA-256:   ebe72f37cbbaf1e8fa2e83cd948414c70272d6073b2feb4a545e5397bda1d1e1
# Code AST SHA-256:   581817b593ee9da8615827144e51b9ae6eb82107949166d493a0f35869f67cbc
# Verified Classes:   LineageRevocationError, MemArtifact
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Set


class LineageRevocationError(RuntimeError):
    """Raised when revocation cannot be proven sound over the derivation graph."""


@dataclass
class MemArtifact:
    id: str
    trust_tier: int
    derived_from: List[str] = field(default_factory=list)
    source_hash: str = ""
    revoked: bool = False


def revoke_to_fixpoint(
    store: Dict[str, MemArtifact],
    seed_ids: List[str],
    quarantined_hashes: Set[str],
) -> Set[str]:
    """Revoke seed entries and every descendant reachable via derived_from,
    plus every artifact whose source_hash is quarantined. Iterates to fixpoint.

    Raises LineageRevocationError if a descendant has no recorded edge back to
    a seed but shares its source hash — a signal the derivation graph is
    incomplete and lineage-based revocation is unsound.
    """
    revoked: Set[str] = set()
    for sid in seed_ids:
        if sid not in store:
            raise LineageRevocationError(f"seed {sid} not in store")
        store[sid].revoked = True
        revoked.add(sid)

    changed = True
    while changed:
        changed = False
        for art in store.values():
            if art.revoked:
                continue
            if any(parent in revoked for parent in art.derived_from):
                art.revoked = True
                revoked.add(art.id)
                changed = True
            elif art.source_hash and art.source_hash in quarantined_hashes:
                art.revoked = True
                revoked.add(art.id)
                changed = True

    # Soundness check: any live artifact sharing a quarantined hash but lacking
    # a derivation edge to a seed indicates a broken lineage graph.
    for art in store.values():
        if art.revoked:
            continue
        if art.source_hash and art.source_hash in quarantined_hashes:
            raise LineageRevocationError(
                f"artifact {art.id} shares quarantined hash {art.source_hash} "
                f"but has no derivation edge to a revoked seed; "
                f"derivation graph is incomplete, lineage revocation unsound"
            )
    return revoked
