# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-consolidation-write-is-silently-overwriting-a-higher-trust-semantic-fact-during-episodic-to-semantic-distillation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-consolidation-write-is-silently-overwriting-a-higher-trust-semantic-fact-during-episodic-to-semantic-distillation.warrant.json
# Markdown SHA-256:   211e321a680b5c5c705b2c82c79778b4c17fe42dff5042d5e42cc4efe2c1b936
# Code AST SHA-256:   a3875b0fa6fb72b4c9f1c5903de46d6828bb2cc56ff6247fde61b0ac431a15c9
# Verified Classes:   TrustClass, Provenance, SemanticFact, ConsolidationArbitrationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Optional


class TrustClass(IntEnum):
    TOOL_OBSERVATION = 1
    MODEL_INFERENCE = 2
    USER_ASIDE = 3
    USER_ASSERTION = 4
    USER_CONFIRMATION = 5


@dataclass
class Provenance:
    source_class: TrustClass
    support_count: int
    session_ids: list[int] = field(default_factory=list)

    def dominates(self, other: "Provenance") -> bool:
        return (
            self.support_count >= other.support_count
            and self.source_class >= other.source_class
        )


@dataclass
class SemanticFact:
    subject: str
    predicate: str
    obj: str
    provenance: Provenance
    contested: bool = False


class ConsolidationArbitrationError(RuntimeError):
    """Raised when a distillation candidate cannot be safely upserted and
    must be routed to contest rather than overwrite."""


def arbitrate_write(
    candidate: SemanticFact,
    incumbent: Optional[SemanticFact],
    allow_tolerance: bool = False,
) -> SemanticFact:
    if allow_tolerance:
        # Any epsilon on the comparison collapses the trust lattice into a
        # scalar and reintroduces the silent-overwrite failure. Refuse it.
        raise ConsolidationArbitrationError(
            "epsilon tolerance on arbitration comparison is forbidden: "
            "it hides lattice violations and permits low-trust overwrites"
        )

    if incumbent is None:
        return candidate

    if candidate.provenance.dominates(incumbent.provenance):
        return candidate

    # Candidate does not dominate. It must not be dropped and must not
    # overwrite. Route to contest; incumbent stays served, flagged.
    incumbent.contested = True
    raise ConsolidationArbitrationError(
        f"contest: candidate {candidate.subject}.{candidate.predicate}="
        f"{candidate.obj} (support={candidate.provenance.support_count}, "
        f"trust={candidate.provenance.source_class.name}) does not dominate "
        f"incumbent ={incumbent.obj} (support={incumbent.provenance.support_count}, "
        f"trust={incumbent.provenance.source_class.name}); "
        f"incumbent retained with contested=true, candidate held pending"
    )
