# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-consistency-drift-and-context-poisoning-when-retrieval-provenance-is-only-partially-observable.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-consistency-drift-and-context-poisoning-when-retrieval-provenance-is-only-partially-observable.warrant.json
# Markdown SHA-256:   dd5ee97dcbd5ca826c18a7e2b96fd60cdeece21ef1a74dd841ce71e96d833543
# Code AST SHA-256:   c6dbb40bd563167a370f61a7eca565791d9315aba73fa08a2554efb272b8ce75
# Verified Classes:   ProvenanceViolation, RetrievalRecord, LedgerEntry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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

class ProvenanceViolation(RuntimeError):
    """Raised when a ledger update would violate trust-dominance or lineage-independence."""
    pass

@dataclass(frozen=True)
class RetrievalRecord:
    entity: str
    attribute: str
    value: str
    source_id: str
    trust_class: str          # assigned at ingestion, immutable
    content_fingerprint: str  # normalized hash of retrieved text
    ingested_turn: int

TRUST_RANK = {"PRIMARY": 3, "SECONDARY": 2, "AGGREGATOR": 1, "UNKNOWN": 0}

@dataclass
class LedgerEntry:
    value: str
    trust_class: str
    lineage: set = field(default_factory=set)
    status: str = "STABLE"    # STABLE | CONTESTED

def lineage_hash(rec: RetrievalRecord) -> str:
    return hashlib.sha256(
        f"{rec.content_fingerprint}|{rec.source_id.split('/')[0]}".encode()
    ).hexdigest()

def propose_update(ledger: dict, rec: RetrievalRecord) -> str:
    key = (rec.entity, rec.attribute)
    lh = lineage_hash(rec)

    incumbent: Optional[LedgerEntry] = ledger.get(key)
    if incumbent is None:
        ledger[key] = LedgerEntry(rec.value, rec.trust_class, {lh})
        return "ACCEPTED_INITIAL"

    # Duplicate-vote suppression: same lineage cannot corroborate itself.
    if lh in incumbent.lineage:
        return "DISCARDED_DUPLICATE_LINEAGE"

    dominates = TRUST_RANK[rec.trust_class] >= TRUST_RANK[incumbent.trust_class]
    disjoint = lh not in incumbent.lineage
    contested = incumbent.status == "CONTESTED"

    if dominates and disjoint:
        ledger[key] = LedgerEntry(rec.value, rec.trust_class, {lh}, "STABLE")
        return "SUPERSEDED"

    if contested and disjoint:
        # Tiebreaker candidate: lineage independence, not trust, governs here.
        incumbent.lineage.add(lh)
        incumbent.status = "CONTESTED"
        return "TIEBREAKER_RECORDED_PENDING_PRIMARY"

    if not dominates:
        incumbent.status = "CONTESTED"
        raise ProvenanceViolation(
            f"Refusing low-trust supersession of {key}: "
            f"incumbent={incumbent.trust_class} incoming={rec.trust_class} "
            f"lineage_disjoint={disjoint}. Attribute quarantined as CONTESTED."
        )

    raise ProvenanceViolation(
        f"Unhandled provenance state for {key}: dominates={dominates} "
        f"disjoint={disjoint} contested={contested}"
    )
