# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-cached-summaries-when-an-upstream-memory-edit-contradicts-a-compaction-snapshot.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-cached-summaries-when-an-upstream-memory-edit-contradicts-a-compaction-snapshot.warrant.json
# Markdown SHA-256:   86efc4a97071fb7e8e1bfd495ac0eb797163498ae6f9607289218150ff88bc46
# Code AST SHA-256:   8447654dde5a0fd6a12c5f504989c039fb2a0097842301325c55e90edfd192b3
# Verified Classes:   StaleCompactionError, Summary
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class StaleCompactionError(RuntimeError):
    """Raised when a cached summary's source content no longer matches its recorded hash."""


@dataclass
class Summary:
    summary_id: str
    source_ids: list[str]
    source_content_hash: str
    derivation_depth: int
    text: str
    parents: list[str] = field(default_factory=list)


def content_hash(records: dict[str, str], source_ids: list[str]) -> str:
    h = hashlib.sha256()
    for rid in sorted(source_ids):
        h.update(rid.encode())
        h.update(b"\x00")
        h.update(records.get(rid, "<MISSING>").encode())
        h.update(b"\x01")
    return h.hexdigest()


def load_summary(summary: Summary, records: dict[str, str]) -> str:
    """Serve a cached summary only if its transitive source content is unchanged."""
    expected = content_hash(records, summary.source_ids)
    if expected != summary.source_content_hash:
        raise StaleCompactionError(
            f"summary {summary.summary_id} (depth {summary.derivation_depth}) "
            f"source content drifted: cached={summary.source_content_hash[:12]} "
            f"actual={expected[:12]} -- invalidate and re-derive, do not serve"
        )
    return summary.text


def propagate_mutation(
    mutated_ids: list[str],
    summaries: dict[str, Summary],
    records: dict[str, str],
    event_type: str,
) -> list[str]:
    """Return the ordered list of summaries that must be invalidated.

    APPEND: no ancestor invalidation. SUPERSEDE/RETRACT: walk parents,
    invalidate every summary whose recomputed content hash changed.
    """
    if event_type == "APPEND":
        return []

    dirty: list[str] = []
    frontier = [s for s in summaries.values() if set(s.source_ids) & set(mutated_ids)]
    seen: set[str] = set()

    while frontier:
        s = frontier.pop()
        if s.summary_id in seen:
            continue
        seen.add(s.summary_id)
        if content_hash(records, s.source_ids) != s.source_content_hash:
            dirty.append(s.summary_id)
            for pid in s.parents:
                if pid in summaries:
                    frontier.append(summaries[pid])
        elif event_type in ("SUPERSEDE", "RETRACT"):
            # Contradiction with unaddressable paraphrase: cannot bound the delta.
            # Conservative branch -- invalidate unconditionally up the chain.
            dirty.append(s.summary_id)
            for pid in s.parents:
                if pid in summaries:
                    frontier.append(summaries[pid])

    if event_type in ("SUPERSEDE", "RETRACT") and not dirty:
        raise StaleCompactionError(
            f"{event_type} on {mutated_ids} matched no summary but may have "
            f"paraphrased into an ancestor -- manual re-derivation required"
        )
    return dirty
