# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-writes-memory-under-one-scope-key-and-reads-it-back-after-a-decay-tick-reclassifies-the-entry.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-writes-memory-under-one-scope-key-and-reads-it-back-after-a-decay-tick-reclassifies-the-entry.warrant.json
# Markdown SHA-256:   52de737d6243c2e5e920f5e51930f20507fdeb172970731d7d43c982b00ee55c
# Code AST SHA-256:   796830e20612a114d8becedad90f1638b4d5f02ac5091312915ce174b05531ef
# Verified Classes:   DecayedCheckpointMismatch, WriteReceipt
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class DecayedCheckpointMismatch(RuntimeError):
    """Raised when a read returns an entry whose tier or schema no longer
    matches the contract committed at write time."""
    pass


@dataclass
class WriteReceipt:
    scope: str
    key: str
    tier: str
    revision: int
    schema_hash: str
    pinned: bool


def commit_checkpoint(store, scope: str, key: str, value: dict, pinned: bool) -> WriteReceipt:
    schema_hash = hashlib.sha256(
        json.dumps(sorted(value.keys())).encode()
    ).hexdigest()
    resp = store.write(scope=scope, key=key, value=value, pinned=pinned)
    if not pinned and resp["tier"] in ("episodic", "semantic"):
        # Acceptable only if caller will validate on read; record the contract.
        pass
    return WriteReceipt(
        scope=scope, key=key, tier=resp["tier"], revision=resp["revision"],
        schema_hash=schema_hash, pinned=pinned,
    )


def resume_checkpoint(store, receipt: WriteReceipt) -> dict:
    resp = store.read(scope=receipt.scope, key=receipt.key)

    if not resp.get("ok"):
        raise DecayedCheckpointMismatch(
            f"checkpoint {receipt.scope}/{receipt.key} absent; treat as no-checkpoint"
        )

    # A decay tick that summarized the value changes tier and bumps revision
    # without any peer writer. That is a content mutation, not a conflict.
    if resp["tier"] != receipt.tier and not receipt.pinned:
        raise DecayedCheckpointMismatch(
            f"tier drifted {receipt.tier}->{resp['tier']} for "
            f"{receipt.scope}/{receipt.key}; value may be lossy-distilled"
        )

    if resp["revision"] != receipt.revision:
        raise DecayedCheckpointMismatch(
            f"revision moved {receipt.revision}->{resp['revision']}; "
            f"subsystem co-authored entry, do not treat as peer conflict"
        )

    value = resp["value"]
    actual_hash = hashlib.sha256(
        json.dumps(sorted(value.keys())).encode()
    ).hexdigest()
    if actual_hash != receipt.schema_hash:
        raise DecayedCheckpointMismatch(
            f"schema hash mismatch for {receipt.scope}/{receipt.key}: "
            f"expected keys of {receipt.schema_hash[:8]}, got {actual_hash[:8]}; "
            f"resume would index missing fields"
        )

    if "relocated_to" in resp:
        raise DecayedCheckpointMismatch(
            f"entry relocated to {resp['relocated_to']}; caller never wrote that key"
        )

    return value
