# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-memory-write-before-provenance-reconciliation-and-what-breaks-when-it-doesn-t.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-memory-write-before-provenance-reconciliation-and-what-breaks-when-it-doesn-t.warrant.json
# Markdown SHA-256:   573e7aa8a5f4b368815b980c956ac68f284180c7b034729259c5474d20bbd5eb
# Code AST SHA-256:   3f2d26581c84bb50a02f68a0a0d12741fb9fa76ad52f00d82205716ef038d514
# Verified Classes:   ProvenanceViolation, TombstoneState, RecordStatus, MemoryRecord, Store
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ProvenanceViolation(RuntimeError):
    """Raised when a memory write cannot be safely committed under the
    write-provenance / forget-audit interleaving invariant."""


class TombstoneState(Enum):
    LIVE = "live"
    IN_FLIGHT = "in_flight"      # tombstone issued, not yet finalized
    FINALIZED_DEAD = "finalized_dead"


class RecordStatus(Enum):
    LIVE = "live"
    PENDING_RECONCILE = "pending_reconcile"   # quarantined
    TOMBSTONED = "tombstoned"


@dataclass
class MemoryRecord:
    record_id: str
    parent_episode: Optional[str]
    taint_class: str
    forget_epoch: int
    status: RecordStatus = RecordStatus.LIVE
    quarantined_at_epoch: Optional[int] = None


@dataclass
class Store:
    records: dict = field(default_factory=dict)
    tombstones: dict = field(default_factory=dict)      # episode -> TombstoneState
    reconcile_queue: list = field(default_factory=list)  # quarantined record_ids
    current_epoch: int = 0


QUARANTINE_TTL_EPOCHS = 3


def commit_write(store: Store, rec: MemoryRecord) -> RecordStatus:
    """Commit a provenance-tagged memory write under the interleaving invariant.

    Invariant enforced: no record is retrievable while any ancestor in its
    provenance chain has an unfinalized tombstone. In-flight parents force
    quarantine; finalized-dead parents force rejection.
    """
    parent = rec.parent_episode
    if parent is None:
        store.records[rec.record_id] = rec
        return RecordStatus.LIVE

    state = store.tombstones.get(parent, TombstoneState.LIVE)

    if state is TombstoneState.FINALIZED_DEAD:
        # Parent is gone for good; the write is a live child of a dead parent.
        # Committing would let retrieval reconstruct the erased ancestor.
        raise ProvenanceViolation(
            f"write {rec.record_id} references finalized-dead parent {parent}; "
            f"rejecting to prevent forget-reversal via ancestor reconstruction"
        )

    if state is TombstoneState.IN_FLIGHT:
        # Resolvable but not final: the audit may have already walked past this
        # child's position. Quarantine and publish to the reconcile queue
        # atomically with the commit so the audit cannot finalize the parent
        # without seeing this child.
        rec.status = RecordStatus.PENDING_RECONCILE
        rec.quarantined_at_epoch = store.current_epoch
        store.records[rec.record_id] = rec
        store.reconcile_queue.append(rec.record_id)
        return RecordStatus.PENDING_RECONCILE

    # Parent live: normal commit.
    store.records[rec.record_id] = rec
    return RecordStatus.LIVE


def finalize_tombstone(store: Store, episode: str) -> None:
    """Finalize a tombstone only after draining all quarantined children.

    The audit cannot finalize a parent while a quarantined child references it,
    because finalization would convert the child's IN_FLIGHT parent into a
    FINALIZED_DEAD one without the child ever being reconciled — exactly the
    live-child-of-dead-parent state the invariant forbids.
    """
    pending_children = [
        rid for rid in store.reconcile_queue
        if store.records[rid].parent_episode == episode
        and store.records[rid].status is RecordStatus.PENDING_RECONCILE
    ]
    if pending_children:
        raise ProvenanceViolation(
            f"cannot finalize tombstone for {episode}: "
            f"{len(pending_children)} quarantined children still pending reconcile"
        )
    store.tombstones[episode] = TombstoneState.FINALIZED_DEAD


def reconcile_quarantine(store: Store) -> None:
    """Drain the quarantine queue at an epoch boundary, with TTL escalation.

    Resolution rules:
      - parent FINALIZED_DEAD  -> child permanently tombstoned (forget propagates)
      - parent LIVE            -> child promoted to live (tombstone was rolled back)
      - parent IN_FLIGHT       -> stays quarantined; escalate if past TTL
    """
    still_pending = []
    for rid in store.reconcile_queue:
        rec = store.records[rid]
        parent_state = store.tombstones.get(rec.parent_episode, TombstoneState.LIVE)

        if parent_state is TombstoneState.FINALIZED_DEAD:
            rec.status = RecordStatus.TOMBSTONED
        elif parent_state is TombstoneState.LIVE:
            rec.status = RecordStatus.LIVE
            rec.quarantined_at_epoch = None
        else:  # still IN_FLIGHT
            age = store.current_epoch - (rec.quarantined_at_epoch or store.current_epoch)
            if age >= QUARANTINE_TTL_EPOCHS:
                # Escalate to supervisor reconcile; never auto-promote (would
                # reintroduce forget-reversal), never auto-drop (would lose
                # legitimate derived memory).
                raise ProvenanceViolation(
                    f"quarantined record {rid} exceeded TTL ({age} epochs) "
                    f"with parent {rec.parent_episode} still in-flight; "
                    f"escalating to supervisor reconcile"
                )
            still_pending.append(rid)
    store.reconcile_queue = still_pending
