# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-scoped-ttl-expiry-with-derived-summary-retention-when-a-forget-request-arrives-mid-distillation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-scoped-ttl-expiry-with-derived-summary-retention-when-a-forget-request-arrives-mid-distillation.warrant.json
# Markdown SHA-256:   b7ec1c40fe6fa34dc39c52e1436a63cc3a5411ff6d3da6d329cc4cb7ede0007c
# Code AST SHA-256:   22b3cf47e6f607b98a9e635225027feb337fcb2780b96ed93c2d5d8c3cc99f7e
# Verified Classes:   DerivationClosureError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class DerivationClosureError(RuntimeError):
    """Raised when a derived-memory commit would resurrect erased source content."""
    pass


def commit_derived_summary(
    subject_id: str,
    summary_text: str,
    source_epoch_at_read: int,
    current_epoch_lookup,
    semantic_store,
) -> str:
    """
    Commit a distilled semantic summary only if the subject's erasure epoch
    has not advanced since the source records were read.

    source_epoch_at_read is captured by the distillation worker at the moment
    it calls read(scope=episodic, subject=subject_id). If a forget() landed
    between that read and this commit, the epoch advanced and the summary
    must be discarded -- not written with a dangling derived_from pointer.
    """
    live_epoch = current_epoch_lookup(subject_id)

    if live_epoch != source_epoch_at_read:
        # The source records were erased (or re-erased) mid-distillation.
        # Writing now would launder erased content into a fresh-TTL record.
        raise DerivationClosureError(
            f"subject={subject_id} epoch advanced "
            f"{source_epoch_at_read}->{live_epoch} during distillation; "
            f"discarding {len(summary_text)}-char summary to preserve "
            f"right-to-be-forgotten closure"
        )

    record_id = semantic_store.write(
        subject_id=subject_id,
        text=summary_text,
        scope="semantic",
        ttl_seconds=30 * 24 * 3600,
        source_epoch=source_epoch_at_read,
    )
    return record_id


def forget(subject_id: str, epoch_store, episodic_store, job_registry) -> int:
    """
    Erasure: tombstone sources, advance the subject's epoch, and cancel
    in-flight distillation jobs. The epoch bump is what fences the commit
    path in commit_derived_summary; the tombstone alone is insufficient.
    """
    new_epoch = epoch_store.increment(subject_id)
    erased = episodic_store.tombstone_all(subject_id)
    cancelled = job_registry.cancel_inflight(subject_id)
    # Any worker that read before this bump will fail its commit check.
    return erased + cancelled
