# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-memory-forget-observability-attribute-schema-has-silently-desynchronized-from-the-memory-store-s-actual-deletion-se.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-memory-forget-observability-attribute-schema-has-silently-desynchronized-from-the-memory-store-s-actual-deletion-se.warrant.json
# Markdown SHA-256:   57316814177076ccbd6bf5421f5f3003ef9b257287f950ae371b38b73fd43956
# Code AST SHA-256:   80e028834522608fd629243e53de71e4ab7cb92e6d5854edafb0b1b26bf33916
# Verified Classes:   ForgetSchemaDesyncError, ForgetAttributes, StoreView
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Callable, Optional


class ForgetSchemaDesyncError(RuntimeError):
    """Raised when a forget attribute set is structurally incapable of
    falsifying its own claim of deletion (degenerate corroboration)."""
    pass


@dataclass
class ForgetAttributes:
    key_hash: str
    mode: str                      # "hard" | "soft" | "expire"
    acked: bool
    tombstone: bool
    records_removed: int
    post_read_probe: str           # "absent" | "present"
    probe_client_id: str
    writer_client_id: str
    records_removed_from_store: bool  # True if sourced from store mutation count


@dataclass
class StoreView:
    """Independent, filter-free view of the store. The only trustworthy oracle."""
    read: Callable[[str], Optional[bytes]]


def validate_forget_claim(attrs: ForgetAttributes, store: StoreView) -> None:
    # 1. Probe must be an independent principal, not the writer's own view.
    if attrs.probe_client_id == attrs.writer_client_id:
        raise ForgetSchemaDesyncError(
            f"post_read_probe for {attrs.key_hash} used writer client "
            f"{attrs.writer_client_id!r}; probe cannot observe tombstones "
            f"and is structurally unable to falsify the delete claim."
        )

    # 2. records_removed must be effect-derived, not return-derived.
    if not attrs.records_removed_from_store:
        raise ForgetSchemaDesyncError(
            f"records_removed for {attrs.key_hash} derived from control flow, "
            f"not a store-reported mutation count; value {attrs.records_removed} "
            f"measures absence of exception, not presence of deletion."
        )

    # 3. mode="hard" must be corroborated by a filter-free read.
    if attrs.mode == "hard":
        payload = store.read(attrs.key_hash)
        if payload is not None:
            raise ForgetSchemaDesyncError(
                f"key {attrs.key_hash} claimed mode='hard' but independent "
                f"store read returned {len(payload)} bytes; attribute schema "
                f"has desynchronized from store deletion semantics."
            )
        if attrs.tombstone:
            raise ForgetSchemaDesyncError(
                f"key {attrs.key_hash} claimed mode='hard' but tombstone=true; "
                f"store performed soft-delete while emitter reported hard."
            )


def check_corroboration_variance(history: list[ForgetAttributes], window: int = 100) -> None:
    """A confirming attribute that never varies is an assertion, not a measurement."""
    if len(history) < window:
        return
    recent = history[-window:]
    tombstone_values = {a.tombstone for a in recent}
    if len(tombstone_values) == 1 and len(recent) >= window:
        # Constant across a full window: flag as unverified, not healthy.
        raise ForgetSchemaDesyncError(
            f"attribute 'tombstone' held constant value {tombstone_values.pop()!r} "
            f"across {window} forget operations; degenerate corroboration — "
            f"emitter is reading a default, not store state."
        )
