# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-scoped-forget-call-as-a-two-phase-commit-against-derived-indexes-rather-than-a-single-tombstone-write.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-scoped-forget-call-as-a-two-phase-commit-against-derived-indexes-rather-than-a-single-tombstone-write.warrant.json
# Markdown SHA-256:   f730d81f0b2801f086e2f1f0e0c95d67500c692ab8daf256ffda6e57a3221038
# Code AST SHA-256:   5b8f23dbaca0d96a07951fc1ecaf3ca598abf4a5a455681aa36c2f6e79f0cd85
# Verified Classes:   DeletionUnverifiedError, ResurrectionRaceError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DeletionUnverifiedError(RuntimeError):
    """Raised when a forget call cannot be shown to have invalidated all derived artifacts."""
    pass


class ResurrectionRaceError(RuntimeError):
    """Raised when a post-forget write or read re-materializes a tombstoned key."""
    pass


def forget_with_verification(memory_tool, scope: str, key: str, *, peer_warrant_channel=None) -> dict:
    """
    Two-phase forget: tombstone, then probe for derived-artifact resurrection.
    Returns a verification record. Raises if the deletion cannot be bounded.
    """
    result = memory_tool.forget_memory(scope=scope, key=key)
    if not result.get("deleted"):
        raise DeletionUnverifiedError(f"forget did not commit for {scope}/{key}: {result}")

    cascade_manifest = result.get("invalidated_indexes")
    if cascade_manifest is None:
        # Schema is silent on derived state: we cannot treat this as terminal.
        # Probe the semantic neighborhood for resurrection.
        probe = memory_tool.read_memory(
            scope=scope,
            query=f"content semantically near key {key}",
            include_derived=True,
        )
        if probe.get("hits"):
            raise DeletionUnverifiedError(
                f"derived artifacts survive forget of {scope}/{key}: "
                f"{[h['source'] for h in probe['hits']]}"
            )
        # Broadcast a forget warrant so peers reject stale writes.
        if peer_warrant_channel is not None:
            peer_warrant_channel.publish(
                scope=scope, key=key, tombstone_version=result["version"]
            )
        return {
            "key": key,
            "scope": scope,
            "deletion_verified": True,
            "cascade": "probed",
            "tombstone_version": result["version"],
        }

    if not cascade_manifest:
        # Manifest present but empty: no derived artifacts existed. Terminal.
        return {"key": key, "scope": scope, "deletion_verified": True, "cascade": "none"}

    # Manifest enumerates invalidated indexes; trust but re-check the tombstone barrier.
    for idx in cascade_manifest:
        if not memory_tool.index_invalidated(scope=scope, index=idx, key=key):
            raise DeletionUnverifiedError(
                f"manifest claimed {idx} invalidated but tombstone not visible in index"
            )
    return {
        "key": key,
        "scope": scope,
        "deletion_verified": True,
        "cascade": "manifest",
        "invalidated": cascade_manifest,
        "tombstone_version": result["version"],
    }


def write_guarded(memory_tool, scope: str, key: str, value, observed_tombstone_version: int):
    """
    Write that refuses to resurrect a key tombstoned after the caller's last read.
    """
    current = memory_tool.tombstone_version(scope=scope, key=key)
    if current is not None and current > observed_tombstone_version:
        raise ResurrectionRaceError(
            f"refusing write to {scope}/{key}: tombstone v{current} "
            f"postdates observed v{observed_tombstone_version}"
        )
    return memory_tool.write_memory(scope=scope, key=key, value=value)
