# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-context-compaction-has-severed-a-tool-call-causal-chain-before-acting-on-the-compacted-state.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-context-compaction-has-severed-a-tool-call-causal-chain-before-acting-on-the-compacted-state.warrant.json
# Markdown SHA-256:   79170d5cb8e67ea032251ab2dcef8f3b0f967b5183321b6d78f3dbcd67b0a6d7
# Code AST SHA-256:   f56a30e13d61d454914feaf9db7cd871cc3327bc9136d67b2060a55d3cf1dcdf
# Verified Classes:   CompactionCausalityError, CallFrame, CompactedView
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionCausalityError(RuntimeError):
    """Raised when a compacted transcript is not a causally valid resume point."""
    pass


@dataclass
class CallFrame:
    call_id: str
    name: str
    arguments: dict
    result_id: Optional[str] = None
    result_hash: Optional[str] = None


@dataclass
class CompactedView:
    # What the model will actually see after compaction.
    surviving_calls: dict = field(default_factory=dict)   # call_id -> CallFrame
    surviving_results: dict = field(default_factory=dict) # result_id -> call_id
    verbatim_arguments: dict = field(default_factory=dict) # call_id -> args the model may act on
    in_flight_call_id: Optional[str] = None


def assert_causally_resumable(view: CompactedView, durable_log_ids: set) -> None:
    """
    Enforce the compaction invariant before the next model step.
    Raises CompactionCausalityError on the first structural violation.
    """
    # 1. No in-flight call may survive a compaction boundary.
    if view.in_flight_call_id is not None:
        raise CompactionCausalityError(
            f"compaction occurred mid-call: call {view.in_flight_call_id!r} "
            f"has no matching result; refuse to resume, rehydrate or wait"
        )

    # 2. Every surviving result must bind to a surviving call frame.
    for result_id, call_id in view.surviving_results.items():
        if call_id not in view.surviving_calls:
            raise CompactionCausalityError(
                f"orphaned result {result_id!r}: originating call {call_id!r} "
                f"was evicted; model cannot bind observation to action"
            )

    # 3. Arguments the model will act upon must be verbatim, not paraphrased.
    for call_id, frame in view.surviving_calls.items():
        verbatim = view.verbatim_arguments.get(call_id)
        if verbatim is None:
            raise CompactionCausalityError(
                f"call {call_id!r} ({frame.name}) survives without verbatim "
                f"arguments; summary paraphrase is not a valid action input"
            )
        if verbatim != frame.arguments:
            raise CompactionCausalityError(
                f"argument drift on call {call_id!r}: summary altered "
                f"{frame.arguments!r} -> {verbatim!r}"
            )

    # 4. Idempotency continuity: executed ids must remain known post-compaction.
    lost = view.surviving_calls.keys() - durable_log_ids
    if lost:
        raise CompactionCausalityError(
            f"calls {sorted(lost)!r} present in view but absent from durable "
            f"log; re-execution guard cannot be trusted"
        )
