# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-prune-a-reasoning-trace-it-cannot-re-derive-the-re-derivability-invariant-in-self-editing-context-windows.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-prune-a-reasoning-trace-it-cannot-re-derive-the-re-derivability-invariant-in-self-editing-context-windows.warrant.json
# Markdown SHA-256:   1213da39f5a611e152adb9b3035eaebb66536d5fea0e89aa0e7fba95de5364a8
# Code AST SHA-256:   66556389c168f3b3619ac01cc1832d1c7954390c5115d4e11c1191d6b7ca4aed
# Verified Classes:   UnprunableTraceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnprunableTraceError(RuntimeError):
    """Raised when a prune request would destroy a conclusion's only provenance."""
    pass


def prune_trace(trace, retained_inputs, live_dependencies, provenance_store):
    """
    Enforce the re-derivability invariant before allowing model-directed pruning.

    A trace may be pruned only if every conclusion it supports is either:
      (1) recorded with a provenance pointer to a still-retained input, or
      (2) re-derivable from retained inputs, or
      (3) not depended upon by any live or plausibly-live step.
    """
    for conclusion in trace.conclusions:
        has_provenance = provenance_store.has_record(
            conclusion, pointing_to=retained_inputs
        )
        re_derivable = conclusion.can_re_derive_from(retained_inputs)
        depended_upon = conclusion in live_dependencies

        if depended_upon and not (has_provenance or re_derivable):
            raise UnprunableTraceError(
                f"Refusing to prune trace {trace.id!r}: conclusion "
                f"{conclusion.id!r} is depended upon by a live step but has "
                f"no surviving provenance and is not re-derivable from "
                f"retained inputs. Promote a provenance-bearing record first."
            )

        if trace.depends_on_one_time_observation and not has_provenance:
            raise UnprunableTraceError(
                f"Refusing to prune trace {trace.id!r}: it is the sole carrier "
                f"of a one-time observation's significance for conclusion "
                f"{conclusion.id!r}. Summarize into a provenance record, then prune."
            )

    # All conclusions cleared the invariant; safe to drop the trace.
    return trace.drop()
