# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-auto-compaction-when-hierarchical-checkpoints-share-a-semantic-dedup-index-across-divergent-branches.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-auto-compaction-when-hierarchical-checkpoints-share-a-semantic-dedup-index-across-divergent-branches.warrant.json
# Markdown SHA-256:   1e371ea2f4c375597e35c0cc5d87f6fdd80193b67f98a53de07f8ee3b5936b66
# Code AST SHA-256:   a9ba82ba51849e1f58adbe3757a48320aa294d7f51091114cc01543d0b5f2394
# Verified Classes:   CompactionRefused, Provenance, Canonical, CompactionContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Dict, Set


class CompactionRefused(RuntimeError):
    """Raised when auto-compaction would violate the shared-dedup invariant."""


@dataclass(frozen=True)
class Provenance:
    branch: str
    chunk_id: str
    snapshot_hash: str


@dataclass
class Canonical:
    identity: str
    frozen_hash: str
    provenance: Set[Provenance] = field(default_factory=set)


@dataclass
class CompactionContext:
    live_branches: Set[str]
    canonicals: Dict[str, Canonical]
    # merges whose divergence cosine fell in the ambiguous band since last checkpoint
    ambiguous_merges: Set[str] = field(default_factory=set)


def audit_eviction_candidate(ctx: CompactionContext, identity: str) -> None:
    canon = ctx.canonicals.get(identity)
    if canon is None:
        raise CompactionRefused(f"unknown canonical {identity!r}")

    branches_in_provenance = {p.branch for p in canon.provenance}

    # Invariant 1: shared dedup across >1 live branch is unsafe for eviction.
    if len(ctx.live_branches) > 1 and len(branches_in_provenance) >= 2:
        raise CompactionRefused(
            f"canonical {identity!r} has provenance across branches "
            f"{sorted(branches_in_provenance)} while live branches are "
            f"{sorted(ctx.live_branches)}; refusing to evict a shared lease"
        )

    # Invariant 2: canonical immutability — every pointer must match frozen hash.
    for p in canon.provenance:
        if p.snapshot_hash != canon.frozen_hash:
            raise CompactionRefused(
                f"canonical {identity!r} frozen_hash={canon.frozen_hash!r} but "
                f"provenance {p.branch}:{p.chunk_id} recorded "
                f"snapshot_hash={p.snapshot_hash!r}; merge mutated canonical"
            )

    # Invariant 3: ambiguous merges block compaction until re-resolved.
    if identity in ctx.ambiguous_merges:
        raise CompactionRefused(
            f"canonical {identity!r} was produced by an ambiguous merge "
            f"(divergence in [merge, divergence) band); refusing to compact"
        )


def try_compact(ctx: CompactionContext, candidates: Set[str]) -> Set[str]:
    """Return the evictable set, or refuse the whole batch on any violation."""
    for identity in sorted(candidates):
        audit_eviction_candidate(ctx, identity)
    return set(candidates)
