# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-lift-a-memory-quarantine-when-the-poisoned-span-and-the-verified-span-share-a-token-level-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-lift-a-memory-quarantine-when-the-poisoned-span-and-the-verified-span-share-a-token-level-provenance.warrant.json
# Markdown SHA-256:   990cd8b6ee6c4a4522b2d76cc7bb6f6f61ce66a168012c10c42082ff8040655c
# Code AST SHA-256:   afedf7a344c2b0deeb59d28ed14a25973d703ba32c0184f43dbdf90348ae686a
# Verified Classes:   ProvenanceLaunderingError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a quarantine lift would admit a span whose reconstruction
    shares a provenance root (or read-set ancestor) with the tainted span."""
    pass


def lift_quarantine(entry_id, replacement_span, tainted_span, read_set_index):
    """
    tainted_span: dict with 'roots' (set) and 'read_closure' (set of span ids).
    replacement_span: dict with 'roots' (set) and 'read_closure' (set).
    read_set_index: maps span_id -> set of span ids it read during derivation.
    """
    tainted_roots = set(tainted_span["roots"])
    repl_roots = set(replacement_span["roots"])

    # Expand replacement read-closure transitively through the read-set index.
    closure = set(replacement_span["read_closure"])
    frontier = list(closure)
    while frontier:
        sid = frontier.pop()
        for parent in read_set_index.get(sid, ()):  # spans it read
            if parent not in closure:
                closure.add(parent)
                frontier.append(parent)

    root_overlap = tainted_roots & repl_roots
    read_overlap = closure & set(tainted_span["read_closure"])

    if root_overlap or read_overlap:
        # Text may look clean; provenance says the poison was laundered through.
        raise ProvenanceLaunderingError(
            f"Refusing to lift quarantine on {entry_id}: "
            f"root_overlap={sorted(root_overlap)} "
            f"read_overlap={sorted(read_overlap)}. "
            f"Re-derive from a disjoint provenance root before lifting."
        )

    # Disjoint provenance root: safe to lift.
    return {"entry_id": entry_id, "status": "CLEAN", "roots": repl_roots}
