# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-provenance-audited-memory-writes-as-unverifiable-when-the-forget-operation-races-the-read-that-validates-it.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-provenance-audited-memory-writes-as-unverifiable-when-the-forget-operation-races-the-read-that-validates-it.warrant.json
# Markdown SHA-256:   5cca281aedeb6bc5788b9b824538f5ab8e9c6e5e342823ed2a1d2d0d7553af26
# Code AST SHA-256:   da12007cfee2710305c75b0e1fa33d418f15d0133aad8708da316b47c173584a
# Verified Classes:   ProvenanceUnverifiableError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ProvenanceUnverifiableError(RuntimeError):
    """Raised when a provenance audit cannot establish a sound verdict.

    Indicates the graph changed under the audit or an ancestor edge is
    unresolvable — the audit result carries no evidentiary weight.
    """


def audit_entry(entry, graph, audit_epoch):
    # Fail closed: a dangling parent is unresolvable, never a clean root.
    for parent_id in entry.parent_ids:
        node = graph.get(parent_id)
        if node is None:
            raise ProvenanceUnverifiableError(
                f"entry {entry.id}: parent {parent_id} unresolvable "
                f"(tombstoned or forgotten); cannot classify as trusted"
            )
        if node.tombstone_epoch is not None and node.tombstone_epoch > audit_epoch:
            raise ProvenanceUnverifiableError(
                f"entry {entry.id}: ancestor {parent_id} tombstoned at "
                f"{node.tombstone_epoch} after audit epoch {audit_epoch}"
            )
        if node.source_class == "untrusted_tool_output":
            return "rejected"

    if entry.commit_epoch > audit_epoch:
        raise ProvenanceUnverifiableError(
            f"entry {entry.id}: committed at {entry.commit_epoch}, "
            f"audit snapshot predates it"
        )
    return "trusted"


def safe_promote(entry, graph, audit_epoch, quarantine):
    try:
        verdict = audit_entry(entry, graph, audit_epoch)
    except ProvenanceUnverifiableError:
        quarantine.append(entry.id)
        return False
    if verdict != "trusted":
        return False
    promote(entry)
    return True
