# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-semantic-store-write-whose-provenance-tag-resolves-to-a-forgotten-episodic-record.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-semantic-store-write-whose-provenance-tag-resolves-to-a-forgotten-episodic-record.warrant.json
# Markdown SHA-256:   e94c6e0418cc5db32dbef68b7ba2b1176df6ee7c0e836f0b547cbe65410ff0af
# Code AST SHA-256:   eece695cdbf84886f47da4242520f87be2aa1e40302502ee7da6b3917e6ef704
# Verified Classes:   TombstonedProvenanceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TombstonedProvenanceError(RuntimeError):
    """Raised when a semantic write cites an episodic record that has been forgotten."""
    def __init__(self, claim: str, tombstoned: list[str], dangling: list[str]):
        self.claim = claim
        self.tombstoned = tombstoned
        self.dangling = dangling
        super().__init__(
            f"refusing semantic write {claim!r}: "
            f"tombstoned={tombstoned} dangling={dangling}"
        )


def write_semantic(store, claim: str, provenance: list[str]) -> str:
    if not provenance:
        raise TombstonedProvenanceError(claim, [], [])  # unprovenanced: unauditable

    tombstoned, dangling = [], []
    for ep_id in provenance:
        status = store.episodic_status(ep_id)  # "live" | "tombstone" | "absent"
        if status == "tombstone":
            tombstoned.append(ep_id)
        elif status == "absent":
            dangling.append(ep_id)

    if tombstoned or dangling:
        # Do NOT cascade-delete or silently strip. Surface for re-derivation.
        raise TombstonedProvenanceError(claim, tombstoned, dangling)

    # Serialize against concurrent forget on the cited episodes.
    with store.lock_episodes(provenance):
        for ep_id in provenance:
            if store.episodic_status(ep_id) != "live":
                raise TombstonedProvenanceError(claim, [ep_id], [])
        return store.insert_semantic(claim, provenance)


def distill_with_recovery(store, claim: str, provenance: list[str]) -> str | None:
    try:
        return write_semantic(store, claim, provenance)
    except TombstonedProvenanceError as e:
        surviving = [p for p in provenance if p not in e.tombstoned and p not in e.dangling]
        if not surviving:
            store.metric("distillation_loss", claim=claim)
            return None  # belief unjustifiable; drop, do not launder
        return write_semantic(store, claim, surviving)  # new claim, surviving evidence only
