# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-compaction-induced-recall-drift-when-post-compaction-embeddings-remain-distributionally-in-distribution.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-compaction-induced-recall-drift-when-post-compaction-embeddings-remain-distributionally-in-distribution.warrant.json
# Markdown SHA-256:   1643ec95bf4cd2979549cacbded5ec95a515fa2e5a4948b4f60320dfd9023929
# Code AST SHA-256:   229c93c26cd4ebbf14e9b416afc96a2935537a42fc9db244c20dbb1d836d1b6b
# Verified Classes:   CompactionFidelityError, CompactionRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

import math
from dataclasses import dataclass


class CompactionFidelityError(RuntimeError):
    """Raised when compaction degrades recall without geometric signature."""
    pass


@dataclass
class CompactionRecord:
    source_id: str
    summary_id: str
    cosine_pre: float
    cosine_post: float
    rank_pre: int
    rank_post: int
    entities_dropped: list[str]


def audit_compaction_cycle(
    records: list[CompactionRecord],
    recall_at_5_pre: float,
    recall_at_5_post: float,
    recall_drop_threshold: float = 0.10,
    cosine_delta_floor: float = -0.03,
) -> dict:
    if not records:
        raise CompactionFidelityError("empty compaction batch; audit cannot run")

    mean_cos_delta = sum(r.cosine_post - r.cosine_pre for r in records) / len(records)
    recall_delta = recall_at_5_post - recall_at_5_pre

    # Geometric crowding signature: recall collapses while cosine holds.
    crowding = (
        recall_delta < -recall_drop_threshold
        and mean_cos_delta > cosine_delta_floor
    )

    displaced = [
        r for r in records
        if (r.rank_post - r.rank_pre) > 5 and r.entities_dropped
    ]

    if crowding and not displaced:
        # Recall dropped but no entity-dropping records explain it:
        # register homogenization across the whole batch. Re-prompting
        # the summarizer will not fix this; must re-anchor.
        raise CompactionFidelityError(
            f"register homogenization: recall {recall_at_5_pre:.2f}->{recall_at_5_post:.2f} "
            f"with mean cosine delta {mean_cos_delta:+.3f}; no entity-drop attribution"
        )

    if recall_delta < -recall_drop_threshold and mean_cos_delta <= cosine_delta_floor:
        # Genuine semantic loss: cosine moved too. Summarizer is the culprit.
        raise CompactionFidelityError(
            f"semantic loss: recall {recall_at_5_pre:.2f}->{recall_at_5_post:.2f} "
            f"and cosine delta {mean_cos_delta:+.3f}; re-prompt summarizer"
        )

    return {
        "crowding": crowding,
        "mean_cosine_delta": round(mean_cos_delta, 4),
        "recall_delta": round(recall_delta, 4),
        "displaced_with_entity_drop": [r.source_id for r in displaced],
        "remediation": "pin_verbatim_anchors" if crowding else "none",
    }
