# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-semantic-store-merge-divergence-when-concurrent-agent-writers-re-assert-stale-episodic-facts.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-semantic-store-merge-divergence-when-concurrent-agent-writers-re-assert-stale-episodic-facts.warrant.json
# Markdown SHA-256:   04b999774b272607d84d9b76830606ff29d9baae19ae66542dbd6200cc928556
# Code AST SHA-256:   61310a0cd46dac61d4ea64eb1add86c5301fe75176a635883b84d873a60c0541
# Verified Classes:   ReAssertionRejected, Provenance, FactVersion
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ReAssertionRejected(RuntimeError):
    """Raised when a write re-asserts content ancestry dominated by the incumbent."""


@dataclass(frozen=True)
class Provenance:
    episode_id: int
    observed_at: float  # monotonic seconds; NOT wall-clock write time


@dataclass
class FactVersion:
    value: str
    provenance: Provenance
    superseded_ancestry: frozenset = field(default_factory=frozenset)


def is_dominated(incoming: Provenance, incumbent: FactVersion) -> bool:
    # Incoming content ancestry is older than the incumbent's, OR it is
    # literally an ancestry the incumbent already superseded.
    if incoming.episode_id in incumbent.superseded_ancestry:
        return True
    return incoming.observed_at < incumbent.provenance.observed_at


def merge_write(
    store: dict,
    key: str,
    value: str,
    content_provenance: Provenance,
    envelope_time: float,
    declared_confidence: float,
) -> FactVersion:
    incumbent: Optional[FactVersion] = store.get(key)
    if incumbent is not None and is_dominated(content_provenance, incumbent):
        raise ReAssertionRejected(
            f"write to {key!r} re-asserts stale ancestry "
            f"episode#{content_provenance.episode_id} "
            f"(observed {incumbent.provenance.observed_at - content_provenance.observed_at:.1f}s "
            f"older than incumbent episode#{incumbent.provenance.episode_id}); "
            f"envelope_time={envelope_time:.1f} confidence={declared_confidence:.2f} "
            f"are advisory and do not override provenance monotonicity"
        )
    new_superseded = (
        incumbent.superseded_ancestry | {incumbent.provenance.episode_id}
        if incumbent is not None
        else frozenset()
    )
    version = FactVersion(
        value=value,
        provenance=content_provenance,
        superseded_ancestry=new_superseded,
    )
    store[key] = version
    return version
