# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-when-a-decay-policy-has-silently-outlived-its-contradiction-resolution-authority.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-when-a-decay-policy-has-silently-outlived-its-contradiction-resolution-authority.warrant.json
# Markdown SHA-256:   eef6c43c70af4e921897be26f0fce5b39d588d213c966524f7f616c5763b1c71
# Code AST SHA-256:   a3c251e0d9f8f1b783a4aaf0b99eb04ab686d099ef89826a3e905397a1dda51b
# Verified Classes:   SupersessionResurrectionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SupersessionResurrectionError(RuntimeError):
    """Raised when a write-refresh would make an adjudicated-false record visible again."""
    pass


ERASED = "__erased__"


def refresh_last_access(record: dict, now: float, tau: float) -> dict:
    if record.get("superseded_by") is not None:
        # A superseded record must never have its score recomputed by a write.
        raise SupersessionResurrectionError(
            f"refusing to refresh superseded record {record['id']!r} "
            f"(superseded_by={record['superseded_by']!r}); "
            f"resurrection would violate the separation invariant"
        )
    record["last_access"] = now
    record["score"] = record["base_weight"] * _decay(now - record["last_access"])
    return record


def read_visible(records: list[dict], tau: float, eps: float = 0.02) -> list[dict]:
    out = []
    for r in records:
        if r.get("superseded_by") is not None:
            # Hard filter: supersession is orthogonal to score.
            if r["superseded_by"] == ERASED:
                # Dangling pointer to an erased record: escalate, do not trust.
                raise SupersessionResurrectionError(
                    f"record {r['id']!r} superseded by erased record; "
                    f"memory subsystem is non-authoritative for this key"
                )
            continue
        if abs(r["score"] - tau) <= eps:
            # Recoverable-but-stale band: flag for caller, do not silently trust.
            r = {**r, "_stale_band": True}
        if r["score"] >= tau:
            out.append(r)
    return out


def forget(user_id: str, primary: dict, ledger: dict) -> None:
    # Cascade erasure through the supersession ledger with explicit sentinels.
    doomed = {rid for rid, rec in primary.items() if rec.get("user_id") == user_id}
    for rid in doomed:
        primary.pop(rid, None)
    for entry in ledger.values():
        if entry.get("record_id") in doomed:
            entry["superseded_by"] = ERASED
    for rid, rec in primary.items():
        if rec.get("superseded_by") in doomed:
            primary[rid]["superseded_by"] = ERASED


def _decay(dt: float, lam: float = 0.05) -> float:
    import math
    return math.exp(-lam * dt)
