# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-replay-a-trace-it-cannot-re-derive-non-determinism-provenance-loss-in-agentic-safety-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-replay-a-trace-it-cannot-re-derive-non-determinism-provenance-loss-in-agentic-safety-reconstruction.warrant.json
# Markdown SHA-256:   3ba9f4bf613440fb960cd085c1d59d878afb2924abf668e700f4d076b4d1151d
# Code AST SHA-256:   28cd25990f99040f2a03de425edc240922f343c3f1ae5c97027c809299240c1b
# Verified Classes:   UnrederivableTraceError, Step, Trace
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnrederivableTraceError(RuntimeError):
    """Raised when a trace lacks provenance required for re-execution replay."""
    pass


@dataclass
class Step:
    index: int
    action: str
    candidate_set: Optional[list] = None      # tools/slots/docs offered to model
    packing_order: Optional[list] = None       # context-window layout
    tool_return: Optional[str] = None          # verbatim, incl. timestamps/ids
    model_pin: Optional[str] = None            # provider + version hash


@dataclass
class Trace:
    steps: list
    model_pin: Optional[str] = None


def assess_replay_admissibility(trace: Trace, replay_model_pin: str) -> str:
    """
    Returns one of: 're-execution', 're-derivation', and raises
    UnrederivableTraceError when even re-derivation is unsound.
    """
    if trace.model_pin is None:
        raise UnrederivableTraceError(
            "trace has no model identity pin; replay distribution unknown"
        )
    if trace.model_pin != replay_model_pin:
        raise UnrederivableTraceError(
            f"model version drift: trace={trace.model_pin!r} "
            f"replay={replay_model_pin!r}; scaffolding may have shifted"
        )

    # Min-over-chain: the least-complete step bounds the whole chain.
    for step in trace.steps:
        if step.candidate_set is None or step.packing_order is None:
            # Candidate set or packing order missing -> cannot re-sample
            # the model and claim decision-surface agreement.
            # Downgrade whole downstream chain to re-derivation.
            return "re-derivation"

    return "re-execution"


def replay_and_assert(trace: Trace, replay_model_pin: str, observed_actions: list) -> str:
    mode = assess_replay_admissibility(trace, replay_model_pin)

    if mode == "re-execution":
        # Action match alone is insufficient; decision surface must match.
        for step, observed in zip(trace.steps, observed_actions):
            if observed.get("action") != step.action:
                # Divergence is a negative result, not a nondeterminism excuse.
                raise UnrederivableTraceError(
                    f"step {step.index}: action diverged under re-execution; "
                    "causal chain unverified"
                )
            if observed.get("candidate_set") != step.candidate_set:
                # Same action, different decision surface: false convergence.
                raise UnrederivableTraceError(
                    f"step {step.index}: action matched but candidate set differed; "
                    "mechanism-level divergence, explanation invalid"
                )
        return "re-execution: decision-surface agreement confirmed"

    # re-derivation: recorded outputs fixed, only scaffolding recomputed.
    return "re-derivation: input-output implication only; causal claim downgraded"
