# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-retention-provenance-divergence-in-read-write-forget-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-retention-provenance-divergence-in-read-write-forget-memory-tool-apis.warrant.json
# Markdown SHA-256:   2c112503a80354c70c38ebc7af077890c2e251379076176a0bbe5bbe6fcfe021
# Code AST SHA-256:   10d095a4dbc53bb3515d62044c05894c8dd6ca51d91a9a8d3874ed8330d7654b
# Verified Classes:   ProvenanceRetentionDivergence
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ProvenanceRetentionDivergence(RuntimeError):
    """Raised when a forgotten record's provenance edges survive without attestation."""
    pass


def verify_forget_consistency(
    forgotten_id: str,
    tombstone: dict | None,
    incident_edges: list[dict],
    required_attestation: bool = True,
) -> None:
    """
    Call immediately after a forget returns ok, before reading any dependent.

    tombstone: the record written by the forget path; must contain 'payload_hash'
               and 'forgotten_by' if attestation policy is in force.
    incident_edges: provenance edges still referencing forgotten_id, as returned
                    by the provenance resolver (which may bypass retention filters).
    """
    if not incident_edges:
        return  # no dependents; divergence cannot manifest

    if required_attestation:
        if tombstone is None:
            raise ProvenanceRetentionDivergence(
                f"forget({forgotten_id}) left {len(incident_edges)} live provenance "
                f"edges but wrote no tombstone; dependents cannot verify derivation"
            )
        if "payload_hash" not in tombstone or "forgotten_by" not in tombstone:
            raise ProvenanceRetentionDivergence(
                f"tombstone for {forgotten_id} lacks payload_hash/forgotten_by; "
                f"{len(incident_edges)} edges are unattested and must be treated as corrupt"
            )

    # Detect the specific hazard: a dependent whose retention horizon exceeds
    # the forgotten ancestor's, with no provenance_hold recorded on the ancestor.
    for edge in incident_edges:
        if edge.get("child_retention_horizon_days", 0) > edge.get(
            "parent_retention_horizon_days", 0
        ) and not edge.get("parent_provenance_hold", False):
            raise ProvenanceRetentionDivergence(
                f"edge {edge.get('child_id')}->{forgotten_id}: child horizon "
                f"{edge['child_retention_horizon_days']}d exceeds parent "
                f"{edge['parent_retention_horizon_days']}d with no provenance_hold; "
                f"write should have been rejected at creation"
            )
