# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-opentelemetry-semantic-convention-memory-span-as-authoritative-state-rather-than-a-diagnostic-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-opentelemetry-semantic-convention-memory-span-as-authoritative-state-rather-than-a-diagnostic-trace.warrant.json
# Markdown SHA-256:   59be49726eef1f14cd87b3017c978d043b6eee48a6ecdc22b4806a390556841a
# Code AST SHA-256:   10ddc66d2a892e93119bf9b798cb6519d17f567be4dfe94e1d6c78059734f8f2
# Verified Classes:   MemoryContractViolation, SpanContract, MemorySpan, LiveRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum


class MemoryContractViolation(RuntimeError):
    """Raised when a consumer attempts to apply a memory span whose contract
    does not permit authoritative use."""


class SpanContract(Enum):
    AUTHORITATIVE = "authoritative"
    DIAGNOSTIC = "diagnostic"


@dataclass(frozen=True)
class MemorySpan:
    operation: str          # "read" | "write" | "forget"
    record_id: str
    record_hash: str | None
    hash_version: str | None
    seq: int | None         # monotonic sequence, assigned at emit under mutation lock
    contract: SpanContract
    sampled: bool


@dataclass(frozen=True)
class LiveRecord:
    record_id: str
    value: str
    version: int            # store-assigned monotonic version


def apply_span_to_reconstruction(
    span: MemorySpan,
    rebuilt: dict[str, str],
    *,
    expected_hash_version: str,
) -> None:
    """Apply a span to a rebuilt memory state.

    Refuses to apply any span that does not carry the authoritative contract,
    because a diagnostic span may be sampled, reordered, or dropped, and
    applying it silently corrupts the reconstruction.
    """
    if span.contract is not SpanContract.AUTHORITATIVE:
        raise MemoryContractViolation(
            f"span for {span.record_id!r} is diagnostic; "
            f"refusing to apply to reconstructed state"
        )
    if span.sampled:
        raise MemoryContractViolation(
            f"authoritative span for {span.record_id!r} was sampled; "
            f"stream is incomplete and cannot be applied"
        )
    if span.seq is None:
        raise MemoryContractViolation(
            f"authoritative span for {span.record_id!r} lacks monotonic seq; "
            f"total order cannot be established"
        )
    if span.record_hash is not None and span.hash_version != expected_hash_version:
        raise MemoryContractViolation(
            f"hash version skew for {span.record_id!r}: "
            f"span={span.hash_version!r} expected={expected_hash_version!r}; "
            f"cannot compare, not a corruption signal"
        )
    if span.operation == "forget":
        rebuilt.pop(span.record_id, None)
    elif span.operation == "write":
        if span.record_hash is None:
            raise MemoryContractViolation(
                f"authoritative write for {span.record_id!r} lacks record hash"
            )
        rebuilt[span.record_id] = span.record_hash
    # reads do not mutate reconstruction


def reconcile(
    rebuilt: dict[str, str],
    live: dict[str, LiveRecord],
    spans: list[MemorySpan],
    *,
    expected_hash_version: str,
) -> list[str]:
    """Reconcile rebuilt vs live state. Returns drift reports; never mutates live."""
    for span in sorted(spans, key=lambda s: (s.seq is None, s.seq)):
        apply_span_to_reconstruction(
            span, rebuilt, expected_hash_version=expected_hash_version
        )
    drift: list[str] = []
    for rid, live_rec in live.items():
        rebuilt_hash = rebuilt.get(rid)
        if rebuilt_hash is None:
            drift.append(f"{rid}: present live, absent rebuilt (possible lost forget)")
        elif rebuilt_hash != live_rec.value:
            drift.append(f"{rid}: hash mismatch; advisory only, verify live version")
    for rid in rebuilt:
        if rid not in live:
            drift.append(f"{rid}: present rebuilt, absent live (possible lost write)")
    return drift
