# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-pre-compaction-commit-barrier-and-the-semantic-orphan-failure-mode.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-pre-compaction-commit-barrier-and-the-semantic-orphan-failure-mode.warrant.json
# Markdown SHA-256:   6697fd36e93084dd7c32315a1919d3c7fe720117d9f27213d06bd0036f883d3a
# Code AST SHA-256:   336e0d11b2338988fa236d98f786bb9cf75017ab37f65d76b24eda78f29152d6
# Verified Classes:   CompactionObligationError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class CompactionObligationError(RuntimeError):
    """Raised when auto-compaction is attempted while live obligations
    (in-flight calls, unverified claims, unbound variables) remain and
    cannot be losslessly preserved in the summary artifact."""
    pass


def maybe_compact(state, window_tokens, threshold=0.85):
    utilization = state.used_tokens / window_tokens
    if utilization < threshold:
        return state  # no compaction needed

    obligations = state.open_obligations()  # in-flight calls, unverified claims, unbound vars
    if obligations:
        # Attempt to serialize obligations into a verbatim, non-summarized ledger.
        ledger = state.serialize_obligations(obligations)
        if not state.ledger_is_lossless(ledger, obligations):
            raise CompactionObligationError(
                f"Refusing to compact at {utilization:.0%}: "
                f"{len(obligations)} open obligation(s) cannot be losslessly preserved. "
                f"Resolve or defer compaction. Obligations: {[o.id for o in obligations]}"
            )
        return state.compact(preserve_ledger=ledger)

    return state.compact(preserve_ledger=None)
