# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scoped-forget-tombstones-from-resurrecting-through-the-memory-tool-s-read-path.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scoped-forget-tombstones-from-resurrecting-through-the-memory-tool-s-read-path.warrant.json
# Markdown SHA-256:   6954bcf88122d8d3ee5d477572ca0efbff3f2b3dfdd12a80be1866f8724f049c
# Code AST SHA-256:   d5c7f281671cc09ce002e723a84d434463f898c87dbf32ee5af848f5ee04bd79
# Verified Classes:   ForgetPropagationViolation, StaleDerivativeError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ForgetPropagationViolation(RuntimeError):
    """Raised when a read returns content whose derivation closure intersects a live tombstone."""


class StaleDerivativeError(ForgetPropagationViolation):
    """Raised when a distilled/semantic node derives from a tombstoned source and was committed after the tombstone."""


def guarded_read(memory_api, query, scope_prefix, *, require_clean=True):
    """
    Read path that enforces the scoped-forget invariant.

    The invariant: no returned item may have a derivation closure that
    intersects a live tombstone in its scope ancestry, unless the caller
    explicitly opts into unverified reads (require_clean=False).
    """
    response = memory_api.read(query=query, scope_prefix=scope_prefix)
    items = response.get("items", [])
    clean = []
    violations = []

    for item in items:
        # The API must expose derivation_clean and tombstone_ids for this
        # invariant to be checkable. Absence is itself a violation of the
        # contract, not a pass.
        if "derivation_clean" not in item:
            raise ForgetPropagationViolation(
                f"read path did not expose derivation_clean for item {item.get('id')}; "
                f"cannot prove scope {scope_prefix} is tombstone-clean"
            )

        if item["derivation_clean"]:
            clean.append(item)
            continue

        # Item is dirty: its closure intersects a tombstone. Record and,
        # if strict, refuse to hand it back as current fact.
        violations.append({
            "item_id": item.get("id"),
            "tombstone_ids": item.get("tombstone_ids", []),
            "propagation_status": item.get("propagation_status", "unknown"),
        })

        if item.get("propagation_status") == "pending":
            # Forget has not finished propagating; the derivative may be
            # mid-flight. This is the in-flight distillation case.
            raise StaleDerivativeError(
                f"item {item.get('id')} derives from tombstoned source(s) "
                f"{item.get('tombstone_ids')} but propagation is still pending; "
                f"refusing to serve as current fact"
            )

    if violations and require_clean:
        raise ForgetPropagationViolation(
            f"scoped-forget invariant violated for scope {scope_prefix}: "
            f"{len(violations)} item(s) have derivation closures intersecting live tombstones: "
            f"{[v['item_id'] for v in violations]}"
        )

    return {"clean": clean, "violations": violations}


def commit_distilled_node(memory_api, derived_node, source_ids):
    """
    Distillation commit path with a commit-time CAS against source liveness.
    Closes the window where a forget lands between the distiller's read
    and its commit.
    """
    for source_id in source_ids:
        liveness = memory_api.liveness(source_id)
        if liveness.get("tombstoned"):
            raise StaleDerivativeError(
                f"distillation aborted: source {source_id} was tombstoned at "
                f"logical clock {liveness.get('tombstone_clock')} after the distiller's "
                f"initial read; derived node {derived_node.get('id')} would be born-forgotten"
            )

    return memory_api.write(derived_node)
