# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-shared-agent-store-entry-when-provenance-tracked-write-auditing-detects-a-tainted-ancestor-rather-than.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-shared-agent-store-entry-when-provenance-tracked-write-auditing-detects-a-tainted-ancestor-rather-than.warrant.json
# Markdown SHA-256:   048173f9e5d8842101360f59ed65ae50d314d2a48e33ad4541c25428977343d5
# Code AST SHA-256:   e8dc9639a4d10506f8f5e932847a72c422e625d7f68b457fbcd6374a61da9188
# Verified Classes:   AncestorTaintViolation, Entry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class AncestorTaintViolation(RuntimeError):
    """Raised when a clean-writer entry is served despite a tainted read-set ancestor."""
    pass


@dataclass
class Entry:
    key: str
    writer: str
    read_set: Set[str] = field(default_factory=set)
    write_ts: float = 0.0
    quarantined: bool = False


def invalidate_transitive(
    store: Dict[str, Entry],
    taint_roots: Set[str],
    now: float,
) -> Set[str]:
    """Compute all keys that must be invalidated due to ancestor taint.

    A key is ancestor-tainted if its writer is clean but its read_set
    intersects the taint set, and it was written before the taint was
    established (retroactive taint). This is the boundary case.
    """
    tainted: Set[str] = set(taint_roots)
    changed = True
    while changed:
        changed = False
        for key, entry in store.items():
            if key in tainted or entry.quarantined:
                continue
            if entry.read_set & tainted and entry.write_ts < now:
                # Clean writer, tainted ancestry: must invalidate.
                tainted.add(key)
                changed = True
    return tainted


def guard_read(store: Dict[str, Entry], key: str, taint_roots: Set[str], now: float) -> Entry:
    entry = store[key]
    if entry.writer in taint_roots:
        raise AncestorTaintViolation(
            f"tainted write: {key} written by {entry.writer}"
        )
    tainted = invalidate_transitive(store, taint_roots, now)
    if key in tainted and entry.writer not in taint_roots:
        raise AncestorTaintViolation(
            f"ancestor taint: {key} has clean writer {entry.writer} "
            f"but read-set intersects taint set {entry.read_set & tainted}"
        )
    return entry
