# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-auto-compact-the-pre-image-starvation-boundary-in-long-horizon-context-windows.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-auto-compact-the-pre-image-starvation-boundary-in-long-horizon-context-windows.warrant.json
# Markdown SHA-256:   551bb703d005b1684813385d7330185921177aac1a5fe56faf8adb2cdbaeeeaa
# Code AST SHA-256:   a945b1983f1ae19b9618d23ecee9d1325815bdd881f4cd342a6ac6403e3384f9
# Verified Classes:   PreImageStarvationError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class PreImageStarvationError(RuntimeError):
    """Raised when auto-compaction would evict a discriminator the next step needs."""
    pass


def should_compact(
    tokens_used: int,
    soft_limit: int,
    pending_step_symbols: set[str],
    durable_slots: dict[str, str],
    recent_events: list[dict],
) -> bool:
    """Return True only if compaction is safe. Refuse otherwise."""
    if tokens_used <= soft_limit:
        return False

    # Symbols the pending step will reference but that are not yet resolved.
    unresolved = {s for s in pending_step_symbols if s not in durable_slots}
    if not unresolved:
        return True  # safe: nothing load-bearing in raw history

    has_payload = any(
        e.get("kind") in ("error", "tool_output") for e in recent_events[-5:]
    )
    if has_payload:
        # The discriminator lives only in raw history about to be evicted.
        raise PreImageStarvationError(
            f"refusing to compact: unresolved symbols {unresolved} are "
            f"recoverable only from raw events that compaction would evict; "
            f"resolve them into durable slots first"
        )

    return True
