# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-semantic-tier-write-during-episodic-consolidation-because-the-deduplication-key-collides-with-a-still-live.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-semantic-tier-write-during-episodic-consolidation-because-the-deduplication-key-collides-with-a-still-live.warrant.json
# Markdown SHA-256:   7ec3368911f402f84544be007eacfcedbd7832d4042f1fd209d7994790bc354f
# Code AST SHA-256:   530dc44b4127cdefa578fb8b044feb18e9213706f00f0e988b5163d31086f073
# Verified Classes:   ConsolidationDedupCollision, SemanticRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ConsolidationDedupCollision(RuntimeError):
    """Raised when a semantic write hits a dedup key whose antecedent set
    is disjoint from (or supersedes) the existing record's antecedent set.
    This is a supersession, not a duplicate; skipping would freeze a stale fact."""
    pass


@dataclass
class SemanticRecord:
    key: str
    claim: str
    derived_from: frozenset[str]
    version: int = 1
    superseded_by: Optional[int] = None
    invalidated_at: Optional[int] = None


def normalize(claim: str) -> str:
    return "".join(claim.split()).lower()


def dedup_key(claim: str) -> str:
    return hashlib.sha256(normalize(claim).encode()).hexdigest()


def consolidate_write(
    index: dict[str, SemanticRecord],
    claim: str,
    antecedent_ids: frozenset[str],
    supersedes: frozenset[str],
    clock: int,
) -> SemanticRecord:
    key = dedup_key(claim)
    existing = index.get(key)

    if existing is None:
        rec = SemanticRecord(key=key, claim=claim, derived_from=antecedent_ids)
        index[key] = rec
        return rec

    # Pending tombstone: key still occupied, write must not be silently dropped.
    if existing.invalidated_at is not None:
        raise ConsolidationDedupCollision(
            f"key {key[:12]} occupied by invalidated record awaiting GC; "
            f"refusing skip on new antecedents {sorted(antecedent_ids)}"
        )

    shared = existing.derived_from & antecedent_ids
    correction = bool(supersedes & existing.derived_from)

    if shared and not correction:
        # True replay: same cluster re-distilled. Idempotent skip is safe.
        return existing

    if not shared or correction:
        # Disjoint antecedents or explicit supersession: this is a new derivation
        # that collides on the normalized string. Must version, not skip.
        new = SemanticRecord(
            key=key,
            claim=claim,
            derived_from=antecedent_ids,
            version=existing.version + 1,
        )
        existing.superseded_by = new.version
        existing.invalidated_at = clock
        index[key] = new
        raise ConsolidationDedupCollision(
            f"supersession at key {key[:12]}: v{existing.version} invalidated, "
            f"v{new.version} written from antecedents {sorted(antecedent_ids)}"
        )

    raise ConsolidationDedupCollision(
        f"undecidable dedup state at key {key[:12]}: "
        f"shared={sorted(shared)} supersedes={sorted(supersedes)}"
    )
