# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-auto-compaction-has-crossed-the-recall-loss-boundary-in-long-horizon-agent-transcripts.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-auto-compaction-has-crossed-the-recall-loss-boundary-in-long-horizon-agent-transcripts.warrant.json
# Markdown SHA-256:   31168513f04609b1daeb53410abdc9b742f806e8ba44a2ab5100bbc69e5a3fd4
# Code AST SHA-256:   7cacb91b27514b449d1395559d719a616532fe07b68f7bfe1c207dd4b626b721
# Verified Classes:   RecallBoundaryViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class RecallBoundaryViolation(RuntimeError):
    """Raised when a proposed compaction drop-set crosses the recall-loss boundary."""
    pass


def check_compaction_safety(
    drop_set: list[dict],
    retained: list[dict],
    pointer_index: dict[str, str],
) -> None:
    """
    Validate a candidate drop-set BEFORE summarization.

    Each item in drop_set is expected to carry:
      - 'id': stable identifier (entity, path, error code, ticket)
      - 'polarity': +1 / -1 for propositions
      - 'order_key': sortable sequence marker, or None
      - 'pointers': list of node ids this fact references

    `retained` is the set of facts that will survive this cycle.
    `pointer_index` maps node id -> retained node id (resolvable pointers).
    """
    retained_ids = {r["id"] for r in retained}
    retained_polarity = {r["id"]: r.get("polarity") for r in retained}

    for fact in drop_set:
        fid = fact["id"]

        # 1. Orphaned identifier: the id is the sole anchor for a future query.
        if fid not in retained_ids:
            raise RecallBoundaryViolation(
                f"orphaned identifier {fid!r}: dropped with no retained anchor"
            )

        # 2. Negation loss: polarity of the dropped fact is not preserved.
        if fact.get("polarity") is not None:
            if retained_polarity.get(fid) != fact["polarity"]:
                raise RecallBoundaryViolation(
                    f"negation loss on {fid!r}: polarity {fact['polarity']} "
                    f"would be flattened into {retained_polarity.get(fid)!r}"
                )

        # 3. Pointer decay: a retained reference resolves to nothing.
        for ptr in fact.get("pointers", []):
            if ptr not in pointer_index:
                raise RecallBoundaryViolation(
                    f"dangling pointer {ptr!r} from {fid!r}: "
                    f"target removed by a prior compaction cycle"
                )

        # 4. Temporal flattening: ordering constraint dropped into an unordered set.
        if fact.get("order_key") is not None:
            if not any(r.get("order_key") is not None for r in retained):
                raise RecallBoundaryViolation(
                    f"temporal flattening near {fid!r}: "
                    f"no retained fact preserves ordering"
                )

    # If we reach here, every dropped fact is dominated by a retained
    # fact plus a resolvable pointer. Compaction may proceed.
    return None
