# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-memory-write-that-passes-every-per-write-anomaly-score-but-is-contradicted-by-a-later-session-s-retr.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-memory-write-that-passes-every-per-write-anomaly-score-but-is-contradicted-by-a-later-session-s-retr.warrant.json
# Markdown SHA-256:   da2bb00eca261ca120e10594b9fc92d821e323662d9d99cbbcb7c5bf2fe78a6a
# Code AST SHA-256:   8a3c17085c7cdfad15eabef23523f6a99f084c67b5c7b26836288046debfa5bb
# Verified Classes:   ContestedMemoryError, MemoryChunk
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

LOAD_BEARING_FIELDS = {"rate_limit", "endpoint", "auth_scheme", "quota"}


class ContestedMemoryError(RuntimeError):
    """Raised when a retrieved write is contradicted by another retrieved write
    and no authority ordering resolves the conflict. Consolidation must halt."""
    pass


@dataclass
class MemoryChunk:
    chunk_id: str
    session: str
    source: str                      # "internal_doc" | "external_tool" | "agent_inference"
    anomaly_score: float
    cleared_by_write_scorer: bool
    fields: dict = field(default_factory=dict)
    contested: bool = False


AUTHORITY = {"internal_doc": 3, "agent_inference": 2, "external_tool": 1}


def resolve_and_consolidate(retrieved: list[MemoryChunk]) -> list[MemoryChunk]:
    """Run read-time contradiction detection before consolidation.
    Returns chunks eligible for semantic distillation. Raises on non-resolvable
    contradiction so the caller cannot silently pick by recency."""
    contradictions = []
    for i, a in enumerate(retrieved):
        for b in retrieved[i + 1:]:
            shared = set(a.fields) & set(b.fields) & LOAD_BEARING_FIELDS
            for f in shared:
                if a.fields[f] != b.fields[f]:
                    contradictions.append((a, b, f))

    for a, b, f in contradictions:
        auth_a, auth_b = AUTHORITY[a.source], AUTHORITY[b.source]
        if auth_a == auth_b:
            # Both cleared by write scorer, same authority, disagree on load-bearing field.
            # This is the non-resolvable boundary. Do NOT default to recency.
            a.contested = b.contested = True
            raise ContestedMemoryError(
                f"Non-resolvable contradiction on field '{f}': "
                f"{a.chunk_id}(session={a.session},source={a.source},"
                f"anomaly={a.anomaly_score},cleared={a.cleared_by_write_scorer}) "
                f"vs {b.chunk_id}(session={b.session},source={b.source},"
                f"anomaly={b.anomaly_score},cleared={b.cleared_by_write_scorer}). "
                f"Both cleared at write time; clearance is novelty, not truth. "
                f"Halting consolidation and marking contested."
            )
        # Resolvable: lower-authority chunk is suppressed, not consolidated.
        loser = a if auth_a < auth_b else b
        loser.contested = True

    return [c for c in retrieved if not c.contested]
