# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-memory-record-that-passes-checksum-verification-but-fails-provenance-continuity.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-memory-record-that-passes-checksum-verification-but-fails-provenance-continuity.warrant.json
# Markdown SHA-256:   3e6a4ddc078e5ea3a3610bc5abb51982a53f72dee201dd4927651500b652de85
# Code AST SHA-256:   e0270c42f8b8c09a5a6df6cc3f4e0cc8a29435e64410cd426344525245b8b1c6
# Verified Classes:   ProvenanceContinuityError, MemoryRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class ProvenanceContinuityError(RuntimeError):
    """Raised when a checksum-valid record fails lineage continuity."""
    pass

@dataclass
class MemoryRecord:
    record_id: str
    parent_id: Optional[str]
    source_epoch: int
    content_hash: str
    stored_hash: str
    producer_signature_valid_at_epoch: bool
    parent_last_mutation_epoch: Optional[int]
    lineage_depth: int

MAX_LINEAGE_DEPTH = 64

def verify_continuity(record: MemoryRecord, parent_exists: bool, tombstone_epoch: Optional[int]) -> None:
    if record.content_hash != record.stored_hash:
        raise ProvenanceContinuityError(f"checksum mismatch on {record.record_id}")

    # Condition 1: parent must resolve to a live record or an older tombstone
    if record.parent_id is not None:
        if not parent_exists:
            if tombstone_epoch is None or tombstone_epoch >= record.source_epoch:
                raise ProvenanceContinuityError(
                    f"dangling lineage on {record.record_id}: parent {record.parent_id} "
                    f"absent with no valid prior tombstone"
                )

    # Condition 2: signature must be valid at the record's own epoch
    if not record.producer_signature_valid_at_epoch:
        raise ProvenanceContinuityError(
            f"producer signature invalid at epoch {record.source_epoch} for {record.record_id}"
        )

    # Condition 3: bounded acyclic lineage
    if record.lineage_depth > MAX_LINEAGE_DEPTH:
        raise ProvenanceContinuityError(
            f"lineage depth {record.lineage_depth} exceeds bound on {record.record_id}"
        )

    # Condition 4: monotonic derivation
    if record.parent_last_mutation_epoch is not None and record.parent_last_mutation_epoch > record.source_epoch:
        raise ProvenanceContinuityError(
            f"non-monotonic derivation on {record.record_id}: parent mutated at "
            f"{record.parent_last_mutation_epoch} after child epoch {record.source_epoch}"
        )
