# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-compacted-context-fidelity-metrics-versus-semantic-drift-under-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-compacted-context-fidelity-metrics-versus-semantic-drift-under-eviction.warrant.json
# Markdown SHA-256:   37cb4eb105cd84f24a178e6f047848f0400458f2be95fd3f41ea84b2fa1bd6bf
# Code AST SHA-256:   5a82b27a08ec5a0e3b3b68e53389882b0ff678d1794be132f889dd1a1ee9f325
# Verified Classes:   ScopeOrphanedContextError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ScopeOrphanedContextError(RuntimeError):
    """Raised when a compacted context retains a proposition whose
    scope/polarity modifiers were evicted, making the proposition
    semantically unsafe to reason over despite high extractive fidelity."""
    pass


SCOPE_OPERATORS = {"not", "unless", "only", "if", "until", "before",
                   "after", "except", "without", "when", "provided"}


def validate_compaction(compacted_props, evicted_spans,
                        fidelity_score, fidelity_floor=0.85,
                        drift_variance_ceiling=0.15,
                        task_is_extractive=False):
    """
    compacted_props: list of dicts with keys:
        'text', 'dependency_neighborhood' (set of source token ids)
    evicted_spans: list of dicts with keys:
        'tokens' (set of source token ids), 'text'
    Returns True if safe to consume; raises otherwise.
    """
    if not task_is_extractive and fidelity_score < fidelity_floor:
        raise ScopeOrphanedContextError(
            f"fidelity {fidelity_score:.2f} below floor {fidelity_floor:.2f}"
        )

    # Drift probe: every evicted span intersecting a retained proposition's
    # dependency neighborhood that carries a scope operator orphans it.
    orphans = []
    for prop in compacted_props:
        hood = prop["dependency_neighborhood"]
        for span in evicted_spans:
            if not (span["tokens"] & hood):
                continue
            if any(tok.lower() in SCOPE_OPERATORS for tok in span["text"].split()):
                orphans.append((prop["text"], span["text"]))

    if orphans and not task_is_extractive:
        raise ScopeOrphanedContextError(
            "scope-orphaned propositions detected despite fidelity "
            f"{fidelity_score:.2f}: {orphans[:3]}"
        )

    # Aggregate fidelity hides localized drift; high variance is a red flag.
    if drift_variance_ceiling is not None and fidelity_score > 0.9:
        per_prop = [p.get("drift_estimate", 0.0) for p in compacted_props]
        if per_prop:
            mean = sum(per_prop) / len(per_prop)
            var = sum((x - mean) ** 2 for x in per_prop) / len(per_prop)
            if var > drift_variance_ceiling:
                raise ScopeOrphanedContextError(
                    f"drift variance {var:.3f} exceeds ceiling "
                    f"{drift_variance_ceiling:.3f} under fidelity "
                    f"{fidelity_score:.2f}; localized drift suspected"
                )

    return True
