# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-consolidation-induced-recall-collapse-when-episodic-decay-outpaces-semantic-promotion-in-tiered-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-consolidation-induced-recall-collapse-when-episodic-decay-outpaces-semantic-promotion-in-tiered-agent-memory.warrant.json
# Markdown SHA-256:   d429e441f7b35d97465f6eb8c8ae7ca0774ed315c2575dcb3d7f9353d84e595b
# Code AST SHA-256:   bd9fc539f85c5ad34206a9b62973aa24ebb42d9e614508af3acac1eac5f6697b
# Verified Classes:   ConsolidationOrderingViolation, PromotionDecision, EpisodicRecord, ConsolidationPolicy
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass, field
from enum import Enum


class ConsolidationOrderingViolation(RuntimeError):
    """Raised when an episodic record is evicted while its promotion is still pending."""
    pass


class PromotionDecision(Enum):
    PENDING = "pending"
    PROMOTED = "promoted"
    REJECTED_BY_POLICY = "rejected_by_policy"


@dataclass
class EpisodicRecord:
    record_id: str
    w0: float
    lam: float                      # per-record decay rate
    access_count: int = 0
    decision: PromotionDecision = PromotionDecision.PENDING
    age_cycles: int = 0

    def weight(self) -> float:
        return self.w0 * math.exp(-self.lam * self.age_cycles)


@dataclass
class ConsolidationPolicy:
    theta_promote: float
    theta_evict: float
    promotion_interval: int
    access_gate_k: int
    safety_factor: float = 2.0

    def validate_decay_vs_promotion(self, lam_max: float) -> None:
        # Invariant 1: decay must not outrun promotion latency.
        max_allowed = 1.0 / (self.promotion_interval * self.safety_factor)
        if lam_max >= max_allowed:
            raise ConsolidationOrderingViolation(
                f"lambda_max={lam_max:.4f} exceeds bound {max_allowed:.4f}; "
                f"decay outruns promotion latency"
            )


def sweep(records, policy: ConsolidationPolicy) -> None:
    # Barrier: promotion sweep strictly precedes decay/eviction sweep.
    for r in records:
        if r.decision is not PromotionDecision.PENDING:
            continue
        if r.weight() >= policy.theta_promote and r.access_count >= policy.access_gate_k:
            r.decision = PromotionDecision.PROMOTED
        elif r.weight() < policy.theta_promote:
            # Below promotion threshold and never gated in: explicit policy rejection,
            # NOT silent eviction. This is the auditable terminal state.
            r.decision = PromotionDecision.REJECTED_BY_POLICY

    for r in records:
        if r.weight() < policy.theta_evict:
            if r.decision is PromotionDecision.PENDING:
                # Invariant 3: eviction of a pending record is a bug, not a policy outcome.
                raise ConsolidationOrderingViolation(
                    f"record {r.record_id} crossed eviction threshold "
                    f"(w={r.weight():.4f}) while promotion decision is PENDING"
                )
            # promoted or explicitly rejected -> safe to evict
            r.age_cycles += 1


def check_usage_coupling(lam_scales_with_inverse_access: bool,
                         promotion_gated_on_access: bool) -> None:
    # Invariant 2: these two couplings together are unsound regardless of tuning.
    if lam_scales_with_inverse_access and promotion_gated_on_access:
        raise ConsolidationOrderingViolation(
            "unsound coupling: decay scaled by inverse access_count AND promotion "
            "gated on access_count forms a positive feedback loop toward amnesia "
            "for rare-but-important facts"
        )
