# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-confidence-decay-resurrection-when-a-contradicted-episodic-trace-outlives-its-semantic-tombstone.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-confidence-decay-resurrection-when-a-contradicted-episodic-trace-outlives-its-semantic-tombstone.warrant.json
# Markdown SHA-256:   6dea28ae9ee9fa4fa2097bdcd22e238e90f19ef0471453e2762e2721a3dbdd67
# Code AST SHA-256:   d28f365393471c4087b21f52ba4951af3e8087ecc4329245e231aed5afd90719
# Verified Classes:   ResurrectionBlocked, Trace, SemanticFact, Tombstone
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ResurrectionBlocked(RuntimeError):
    """Raised when a decayed episodic trace would re-distill a tombstoned fact."""


@dataclass
class Trace:
    trace_id: str
    entity_id: str
    asserted_value: str
    asserted_at: int          # logical clock
    confidence: float
    promoted_to: Optional[str]  # semantic fact id, if promoted


@dataclass
class SemanticFact:
    fact_id: str
    entity_id: str
    value: str
    tombstoned_by: Optional[str]  # tombstone id, if contradicted


@dataclass
class Tombstone:
    tombstone_id: str
    entity_id: str
    contradicted_value: str
    written_at: int


def assert_distillable(
    trace: Trace,
    facts: dict[str, SemanticFact],
    tombstones: dict[str, Tombstone],
    entity_traces: list[Trace],
) -> None:
    # 1. Lineage check: if the trace was promoted to a tombstoned fact, block.
    if trace.promoted_to is not None:
        target = facts.get(trace.promoted_to)
        if target is not None and target.tombstoned_by is not None:
            raise ResurrectionBlocked(
                f"trace {trace.trace_id} promoted to {target.fact_id} "
                f"which is tombstoned by {target.tombstoned_by}; "
                f"decayed confidence {trace.confidence:.3f} does not "
                f"override contradiction"
            )

    # 2. Entity-global value check: block if any tombstone for this entity
    #    contradicts the asserted value, unless a *newer* trace re-asserts it.
    for ts in tombstones.values():
        if ts.entity_id != trace.entity_id:
            continue
        if ts.contradicted_value != trace.asserted_value:
            continue
        reasserted = any(
            t.trace_id != trace.trace_id
            and t.asserted_value == trace.asserted_value
            and t.asserted_at > ts.written_at
            for t in entity_traces
        )
        if not reasserted:
            raise ResurrectionBlocked(
                f"trace {trace.trace_id} re-asserts value "
                f"{trace.asserted_value!r} for entity {trace.entity_id}, "
                f"tombstoned by {ts.tombstone_id} at t={ts.written_at}; "
                f"no newer re-assertion found"
            )


def distill(trace: Trace, facts, tombstones, entity_traces) -> SemanticFact:
    assert_distillable(trace, facts, tombstones, entity_traces)
    new_id = f"S_{trace.trace_id}"
    return SemanticFact(
        fact_id=new_id,
        entity_id=trace.entity_id,
        value=trace.asserted_value,
        tombstoned_by=None,
    )
