# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundered-memory-writes-during-decay-driven-schema-migration.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundered-memory-writes-during-decay-driven-schema-migration.warrant.json
# Markdown SHA-256:   b743346193efdbee4076cd6970b2a3d304c15f877861d93e194db1b034efd4ce
# Code AST SHA-256:   b0ab52a701eac8d7de011700edbf6b85bb910bd73b2f8025606669c0d650641e
# Verified Classes:   ProvenanceLaunderingError, MemoryRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write promotes provenance above its inputs' tier."""


TIER_RANK = {"self_inferred": 0, "tool_observed": 1, "user_asserted": 2, "observed": 3}


@dataclass
class MemoryRecord:
    id: str
    claim: str
    provenance: str
    confidence: float
    half_life_hours: float
    derived_from: list[str] = field(default_factory=list)


def consolidate(
    sources: list[MemoryRecord],
    distilled: MemoryRecord,
    write_tool_default_tier: str,
    decaying_ids: set[str],
) -> MemoryRecord:
    if not sources:
        raise ProvenanceLaunderingError("consolidation with no sources is a bare assertion")

    # Invariant: a derivation cannot exceed the weakest input tier.
    inherited_tier = min(sources, key=lambda r: TIER_RANK[r.provenance]).provenance
    inherited_conf = max(r.confidence for r in sources)
    inherited_half_life = min(r.half_life_hours for r in sources)

    # Failure 1: write tool stamped tier by caller identity, not by inputs.
    if TIER_RANK[distilled.provenance] > TIER_RANK[inherited_tier]:
        raise ProvenanceLaunderingError(
            f"record {distilled.id!r} claims {distilled.provenance!r} "
            f"but its sources cap it at {inherited_tier!r}"
        )

    # Failure 2: no derivation edge -> orphan with elevated tier.
    if not distilled.derived_from:
        raise ProvenanceLaunderingError(
            f"record {distilled.id!r} has no derived_from edges; "
            "cannot verify provenance lineage"
        )

    # Failure 3: sources are being evicted by decay in the same window.
    evicted_sources = {r.id for r in sources} & decaying_ids
    if evicted_sources:
        raise ProvenanceLaunderingError(
            f"consolidation would erase evidence {sorted(evicted_sources)} "
            "concurrently with decay; tier cannot be audited post-hoc"
        )

    if distilled.confidence > inherited_conf + 1e-9:
        raise ProvenanceLaunderingError(
            f"record {distilled.id!r} confidence {distilled.confidence} "
            f"exceeds max source confidence {inherited_conf}"
        )

    return MemoryRecord(
        id=distilled.id,
        claim=distilled.claim,
        provenance=inherited_tier,
        confidence=min(distilled.confidence, inherited_conf),
        half_life_hours=min(distilled.half_life_hours, inherited_half_life),
        derived_from=[r.id for r in sources],
    )
