# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-decide-between-lossy-and-lossless-compaction-before-the-context-window-saturates.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-decide-between-lossy-and-lossless-compaction-before-the-context-window-saturates.warrant.json
# Markdown SHA-256:   1521b35d70b4c3006d596db9b1f87219ec6495c6448989c349997ec05f89a2f2
# Code AST SHA-256:   896035d1a525506998597f771e0d23ed42d29da5ee3a926cd0a91d3140586031
# Verified Classes:   CompactionBoundaryError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class CompactionBoundaryError(RuntimeError):
    """Raised when a lossy compaction would fire while reversible headroom remains."""


def decide_compaction(
    actual_occupancy: int,
    lossless_reclaimable: int,
    soft_watermark: int,
    hard_limit: int,
    trigger_estimate: int,
) -> str:
    # The trigger estimate is advisory only; it may not authorize lossy compaction.
    if actual_occupancy < soft_watermark:
        return "no_compaction"

    lossless_viable = lossless_reclaimable > 0
    post_fold = actual_occupancy - lossless_reclaimable

    if lossless_viable and post_fold < hard_limit:
        return "lossless_compact"

    if actual_occupancy < hard_limit:
        # Headroom exists but folding alone is insufficient; lossy is still forbidden.
        if trigger_estimate >= hard_limit:
            raise CompactionBoundaryError(
                f"trigger estimate {trigger_estimate} crossed hard limit "
                f"{hard_limit} but measured occupancy {actual_occupancy} did not; "
                f"refusing irreversible lossy compaction"
            )
        return "defer"

    # Genuine breach: lossy compaction is now the only sound option.
    return "lossy_compact"
