# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-ttl-provenance-deletion-races-in-agent-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-ttl-provenance-deletion-races-in-agent-memory-tool-apis.warrant.json
# Markdown SHA-256:   4499b1f6e4eb1291301454e6523057edef58c42b83543db1cf10b34a0458d1d5
# Code AST SHA-256:   d153d007292096a8a46034cc68f98d5c7ba926e022bd57d9cbbd8db0a3e9f5a2
# Verified Classes:   ResurrectionRiskError, MemoryRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ResurrectionRiskError(RuntimeError):
    """Raised when a derived memory write could outlive and launder a deletable ancestor."""
    pass


@dataclass
class MemoryRecord:
    id: str
    scope: str
    ttl_seconds: int
    created_at: float
    provenance: set[str]
    derived_from: Optional[str] = None
    tombstoned: bool = False

    def remaining_ttl(self, now: float) -> float:
        return (self.created_at + self.ttl_seconds) - now


DELETION_RELEVANT_TAGS = ("subject:", "consent:", "jurisdiction:")


def _deletion_tags(prov: set[str]) -> set[str]:
    return {p for p in prov if p.startswith(DELETION_RELEVANT_TAGS)}


def safe_derive(
    source: MemoryRecord,
    child_id: str,
    child_scope: str,
    child_ttl: int,
    child_provenance: set[str],
    now: float,
) -> MemoryRecord:
    """Enforce TTL monotonicity + provenance superset before a derived write."""
    if source.tombstoned:
        raise ResurrectionRiskError(
            f"source {source.id} is tombstoned; refusing to derive {child_id}"
        )

    src_remaining = source.remaining_ttl(now)
    if child_ttl > src_remaining:
        raise ResurrectionRiskError(
            f"child ttl {child_ttl}s exceeds source remaining {src_remaining}s; "
            f"replica would outlive deletion of {source.id}"
        )

    missing = _deletion_tags(source.provenance) - child_provenance
    if missing:
        raise ResurrectionRiskError(
            f"child {child_id} drops deletion-relevant provenance {sorted(missing)} "
            f"from {source.id}; delete predicate would not reach it"
        )

    return MemoryRecord(
        id=child_id,
        scope=child_scope,
        ttl_seconds=child_ttl,
        created_at=now,
        provenance=set(child_provenance) | {"derived_from:" + source.id},
        derived_from=source.id,
    )


def check_retrieval(record: MemoryRecord, tombstones: dict[str, MemoryRecord]) -> None:
    """Read-path backstop: quarantine records whose lineage reaches a tombstone."""
    cursor: Optional[str] = record.derived_from
    while cursor is not None:
        anc = tombstones.get(cursor)
        if anc is not None and anc.tombstoned:
            raise ResurrectionRiskError(
                f"record {record.id} descends from tombstoned {cursor}; "
                f"quarantine before distillation to prevent resurrection"
            )
        cursor = None  # single-hop here; extend with a lineage index for full DAG walk
