# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-provenance-valid-memory-write-whose-source-attestation-has-silently-expired-between-retrieval-and-comm.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-provenance-valid-memory-write-whose-source-attestation-has-silently-expired-between-retrieval-and-comm.warrant.json
# Markdown SHA-256:   0b9f992605ca79bf06a3f2115023c78dfea32470478ffef10efcce0310f7fa30
# Code AST SHA-256:   14360c4bb816c77d21e6e9306b932d73fd16a195d3795357e61bfe7d8d0fdfbe
# Verified Classes:   StaleAttestationError, SourceMutationError, Attestation, ProvenanceChain
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class StaleAttestationError(RuntimeError):
    """Raised when a provenance-gated write references an attestation whose
    lease has lapsed relative to the committing store's clock."""
    pass


class SourceMutationError(RuntimeError):
    """Raised when a lapsed attestation coincides with a changed source hash,
    indicating the lapse window may have been used for injection."""
    pass


@dataclass(frozen=True)
class Attestation:
    att_id: str
    source_id: str
    source_hash: str
    issued_at: float      # store-clock epoch seconds
    expires_at: float     # store-clock epoch seconds


@dataclass(frozen=True)
class ProvenanceChain:
    attestations: tuple   # ordered root-first
    root_source_hash: str


def validate_write(
    chain: ProvenanceChain,
    store_now: float,
    delta_max: float,
    current_source_hash: Optional[str],
) -> None:
    """Enforce the commit-time provenance invariant.

    Raises StaleAttestationError if any attestation is expired at store_now,
    or if the root's freshness window is exceeded. Raises SourceMutationError
    if the source hash changed since retrieval (lapse window may be poisoned).
    """
    if not chain.attestations:
        raise StaleAttestationError("empty provenance chain")

    root = chain.attestations[0]

    # Freshness window must be tighter than the lease, or the check is vacuous.
    ttl = root.expires_at - root.issued_at
    if delta_max >= ttl:
        raise StaleAttestationError(
            f"delta_max={delta_max}s >= TTL={ttl}s; freshness clause is vacuous"
        )

    # Invariant clause 1: every attestation unexpired at commit time.
    for att in chain.attestations:
        if att.expires_at <= store_now:
            raise StaleAttestationError(
                f"attestation {att.att_id} expired at {att.expires_at} "
                f"(store_now={store_now}); write must re-attest or reject"
            )

    # Invariant clause 2: root issued within the freshness window.
    if root.issued_at <= store_now - delta_max:
        raise StaleAttestationError(
            f"root attestation {root.att_id} issued at {root.issued_at} "
            f"exceeds delta_max={delta_max}s freshness window"
        )

    # Boundary: lapsed-or-not, a changed source hash forbids commit.
    if current_source_hash is None:
        raise StaleAttestationError(
            f"source {root.source_id} unreachable at commit; cannot re-attest"
        )
    if current_source_hash != chain.root_source_hash:
        raise SourceMutationError(
            f"source {root.source_id} hash changed: "
            f"{chain.root_source_hash} -> {current_source_hash}; "
            f"derived memory must be discarded and re-derived"
        )


def commit_distilled_memory(
    chain: ProvenanceChain,
    store_now: float,
    delta_max: float,
    current_source_hash: Optional[str],
) -> str:
    validate_write(chain, store_now, delta_max, current_source_hash)
    return "committed"
