# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-revoked-memory-record-as-still-authoritative-during-an-in-flight-tool-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-revoked-memory-record-as-still-authoritative-during-an-in-flight-tool-loop.warrant.json
# Markdown SHA-256:   4db7ff27896163086fea6a5c279f695474a9cc99703d0358f5c5c5770d94360f
# Code AST SHA-256:   6f02fe82999369dd030d59dd426f51989eed0d54b50d80e111497991244642d9
# Verified Classes:   StaleProvenanceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleProvenanceError(RuntimeError):
    """Raised when a write's provenance ancestry contains a record whose
    revocation epoch is older than the instance's last confirmed poll,
    meaning the materialized copy may have been revoked in-flight."""
    pass


def guarded_write(instance, derived_content, provenance_ids, store):
    # The instance must hold a current epoch for every ancestor it cites.
    for pid in provenance_ids:
        rec = store.get(pid)
        if rec is None:
            raise StaleProvenanceError(
                f"provenance ancestor {pid} not found in store"
            )
        if rec.status == "revoked":
            # Do NOT re-derive from the in-context copy. Escalate.
            raise StaleProvenanceError(
                f"provenance ancestor {pid} is revoked; "
                f"re-derivation from stale materialization is forbidden"
            )
        if rec.revocation_epoch > instance.last_confirmed_epoch:
            # The store advanced past what this instance has observed.
            # Re-read before writing; the materialization is provisional.
            raise StaleProvenanceError(
                f"provenance ancestor {pid} epoch {rec.revocation_epoch} "
                f"exceeds instance epoch {instance.last_confirmed_epoch}; "
                f"re-read required before write"
            )
    return store.write(derived_content, provenance=provenance_ids)
