# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-ttl-expired-memory-reads-that-pass-provenance-checks-but-violate-temporal-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-ttl-expired-memory-reads-that-pass-provenance-checks-but-violate-temporal-warrant.warrant.json
# Markdown SHA-256:   47162a8fc66166289235e99e174e831bd38d76335d53714a7deaf29349db1ecd
# Code AST SHA-256:   1a4c0ad9cd8c58786a77e5cb0bfbc24dbaa51bdea1766fb3fe555e363cd929b4
# Verified Classes:   TemporalWarrantError, MemoryRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class TemporalWarrantError(RuntimeError):
    """Raised when a memory record is used for derivation despite an expired TTL."""
    pass


@dataclass
class MemoryRecord:
    key: str
    value: object
    expires_at: float          # absolute epoch seconds, from writer's clock
    provenance_verdict: str    # "valid" | "invalid"
    physically_present: bool = True


def read_with_temporal_warrant(
    record: Optional[MemoryRecord],
    now: Optional[float] = None,
) -> MemoryRecord:
    """
    Read path that enforces the invariant: provenance-clean is not current.
    The reader computes the temporal verdict against its own clock.
    """
    if now is None:
        now = time.time()

    if record is None or not record.physically_present:
        raise TemporalWarrantError(f"record absent: {getattr(record, 'key', '?')}")

    if record.provenance_verdict != "valid":
        raise TemporalWarrantError(
            f"provenance invalid for {record.key}; do not use for derivation"
        )

    # The critical check the backend's lazy eviction skipped.
    if record.expires_at <= now:
        raise TemporalWarrantError(
            f"record {record.key} expired at {record.expires_at:.0f}, "
            f"read at {now:.0f}; present but temporally dead — "
            f"re-fetch upstream, do not derive"
        )

    return record


def derive_and_write(
    parent: MemoryRecord,
    derived_key: str,
    derived_value: object,
    requested_ttl: float,
    now: Optional[float] = None,
) -> MemoryRecord:
    """
    Derivation write that propagates the weakest parent's remaining TTL.
    A derived fact cannot outlive its weakest parent.
    """
    if now is None:
        now = time.time()

    parent = read_with_temporal_warrant(parent, now=now)  # fail closed on expired

    parent_remaining = parent.expires_at - now
    effective_ttl = min(requested_ttl, parent_remaining)

    if effective_ttl <= 0:
        raise TemporalWarrantError(
            f"derived TTL for {derived_key} would be {effective_ttl:.1f}s; "
            f"parent {parent.key} has no temporal warrant left"
        )

    return MemoryRecord(
        key=derived_key,
        value=derived_value,
        expires_at=now + effective_ttl,
        provenance_verdict="valid",
    )
