# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-lossy-summary-compaction-against-retrieval-inverted-facts-to-preserve-long-horizon-session-fidelity.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-lossy-summary-compaction-against-retrieval-inverted-facts-to-preserve-long-horizon-session-fidelity.warrant.json
# Markdown SHA-256:   0305bf59833196a2a08b70f608d89285317e193e75d78eafe7ecc773a53a8947
# Code AST SHA-256:   b31e37d210280e51507edd5e88936034512a355273e25665b58e1dd674588214
# Verified Classes:   CompactionFidelityError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CompactionFidelityError(RuntimeError):
    """Raised when a lossy summary becomes the sole authority for a
    write-gating constraint, or when a constraint sentence in the summary
    cannot be traced to a verbatim source turn."""
    pass


CONSTRAINT_MARKERS = ("must", "must not", "shall", "may not", "do not", "ceiling", "floor")


def is_constraint_sentence(sentence: str) -> bool:
    low = sentence.lower()
    return any(m in low for m in CONSTRAINT_MARKERS)


def validate_compaction(summary_sentences, source_index):
    """source_index maps each summary sentence -> verbatim source turn text or None.
    A constraint sentence with no verbatim source is an untraceable paraphrase
    and must be rejected before the summary is admitted to the window."""
    for sent in summary_sentences:
        if not is_constraint_sentence(sent):
            continue
        src = source_index.get(sent)
        if src is None:
            raise CompactionFidelityError(
                f"constraint sentence has no verbatim source and would be "
                f"admitted as authoritative: {sent!r}"
            )
        # polarity check: numeric literal must appear in source verbatim
        digits = [t for t in sent.split() if t.strip(".,;").isdigit()]
        for d in digits:
            if d.strip(".,;") not in src:
                raise CompactionFidelityError(
                    f"numeric bound {d!r} in summary absent from source turn; "
                    f"possible polarity inversion: {sent!r}"
                )


def resolve_gated_write(constraint_id, summary_claim, retrieved_source, write_value):
    """Adjudicate a write gated by a constraint. The summary is untrusted cache;
    the store wins. If only the summary speaks, refuse the write."""
    if retrieved_source is None:
        raise CompactionFidelityError(
            f"gated write for {constraint_id!r} has summary-only authority "
            f"({summary_claim!r}); re-fetch primary source before writing"
        )
    if summary_claim is not None and summary_claim.strip() != retrieved_source.strip():
        # store wins; log defect, do not silently proceed on summary
        raise CompactionFidelityError(
            f"summary/store conflict on {constraint_id!r}: summary={summary_claim!r} "
            f"store={retrieved_source!r}; store is authoritative, write blocked for review"
        )
    return write_value


def attempt_pool_raise(summary_claim, retrieved_source):
    # Reproduces the observed trace: summary says "headroom exists to increase",
    # store says "must stay at 40". Store wins; write refused.
    return resolve_gated_write(
        constraint_id="DB_POOL_MAX",
        summary_claim="headroom exists to increase further",
        retrieved_source="must stay at 40; do not raise above 40",
        write_value=48,
    )


if __name__ == "__main__":
    try:
        attempt_pool_raise(
            summary_claim="headroom exists to increase further",
            retrieved_source="must stay at 40; do not raise above 40",
        )
    except CompactionFidelityError as e:
        print("BLOCKED:", e)
