# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-poisoned-memory-record-when-the-provenance-chain-is-intact-but-the-write-path-attestation-is-stale.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-poisoned-memory-record-when-the-provenance-chain-is-intact-but-the-write-path-attestation-is-stale.warrant.json
# Markdown SHA-256:   13203bca98bf817a9eeb36786d26df417e2eed830210e68523a81b6a8b511ce8
# Code AST SHA-256:   5ed10a33f506860f078d19143332600b480d261552bc211830b6547727dabae7
# Verified Classes:   StaleAttestationError, FrozenIngestionPathError, AuthorizationStaleError, MemoryRecord, TrustContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class StaleAttestationError(RuntimeError):
    """Raised when a memory record's attestation is stale relative to its class cadence."""
    pass


class FrozenIngestionPathError(RuntimeError):
    """Raised when a record's ingestion path is dead; staleness is unbounded."""
    pass


class AuthorizationStaleError(RuntimeError):
    """Raised when the writer's authorization for the record's class was revoked post-attestation."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    semantic_class: str
    attestation_ts: float          # epoch seconds
    ingestion_path_id: str
    writer_id: str
    auth_valid_from: float
    auth_valid_until: float        # revocation time; +inf if never revoked


@dataclass
class TrustContext:
    now: float
    class_cadence: dict            # semantic_class -> seconds
    live_paths: set                # set of ingestion_path_id currently live
    safety_factor: float = 0.75


def evaluate_trust(rec: MemoryRecord, ctx: TrustContext) -> str:
    """Return 'trust' | 'quarantine' | 'reject' per the three-conjunct invariant."""
    # Conjunct 2: ingestion path liveness (checked against live registry, not the record)
    if rec.ingestion_path_id not in ctx.live_paths:
        raise FrozenIngestionPathError(
            f"record {rec.record_id}: ingestion path {rec.ingestion_path_id} is dead; "
            f"staleness is unbounded and the record will pass naive checks forever"
        )

    # Conjunct 3: authorization window must cover the attestation and not be revoked since
    if rec.auth_valid_until < ctx.now:
        raise AuthorizationStaleError(
            f"record {rec.record_id}: writer {rec.writer_id} authorization for "
            f"class {rec.semantic_class} revoked at {rec.auth_valid_until}, "
            f"attestation at {rec.attestation_ts}"
        )

    # Conjunct 1: semantic staleness vs class cadence
    cadence = ctx.class_cadence.get(rec.semantic_class)
    if cadence is None:
        # Unknown cadence -> cannot bound staleness -> quarantine, never trust
        return "quarantine"

    age = ctx.now - rec.attestation_ts
    horizon = cadence * ctx.safety_factor
    if age > horizon:
        raise StaleAttestationError(
            f"record {rec.record_id}: age {age:.0f}s exceeds horizon {horizon:.0f}s "
            f"(class {rec.semantic_class} cadence {cadence}s, factor {ctx.safety_factor})"
        )
    return "trust"


def retrieve_or_refresh(rec: MemoryRecord, ctx: TrustContext) -> str:
    try:
        verdict = evaluate_trust(rec, ctx)
    except FrozenIngestionPathError:
        # Frozen records must be evicted, not quarantined, or they re-enter the trusted set.
        return "evict"
    except (StaleAttestationError, AuthorizationStaleError):
        return "quarantine_and_refresh"
    return verdict
