# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-non-determinism-leakage-when-replaying-an-mcp-tool-call-transcript-for-audit.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-non-determinism-leakage-when-replaying-an-mcp-tool-call-transcript-for-audit.warrant.json
# Markdown SHA-256:   61944f7a32cb9e0a2b6afb45fea891f7a3111a7d86dd86fd5b6e7449cacee05a
# Code AST SHA-256:   b754e231ad0dae92fdfc0e0a2f76a718c0faec592cd94d84ab09fa3859896f43
# Verified Classes:   ReplayFidelityError, RecordedStep
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import base64
from dataclasses import dataclass
from typing import Optional


class ReplayFidelityError(RuntimeError):
    """Raised when a replay cannot reproduce the original model input byte-for-byte."""
    pass


@dataclass
class RecordedStep:
    step_index: int
    raw_tool_result_b64: Optional[str]   # None means the step had no tool result
    render_template_id: Optional[str]
    sampling_params: dict
    model_version_string: str
    context_hash: str                     # sha256 over assembled prompt bytes


def assemble_context(step: RecordedStep, renderer) -> bytes:
    """Rebuild the exact bytes the model saw. Must be lossless."""
    if step.raw_tool_result_b64 is None:
        return b""
    raw = base64.b64decode(step.raw_tool_result_b64)
    return renderer.render(step.render_template_id, raw)


def verify_and_replay(step: RecordedStep, renderer, model_call) -> dict:
    # Guard 1: fidelity metadata must be present. Fail closed, never degrade.
    if step.raw_tool_result_b64 is None and step.render_template_id is not None:
        raise ReplayFidelityError(
            f"step {step.step_index}: render_template_id set but raw bytes missing; "
            "transcript was captured in parsed-object mode and cannot support prompt replay"
        )
    if not step.sampling_params or "seed" not in step.sampling_params:
        raise ReplayFidelityError(
            f"step {step.step_index}: sampling_params incomplete (seed required)"
        )

    context = assemble_context(step, renderer)

    # Guard 2: byte-fidelity invariant. If the reassembled bytes differ from
    # what was recorded, the replay has no authority over this step's output.
    actual = hashlib.sha256(context).hexdigest()
    if actual != step.context_hash:
        raise ReplayFidelityError(
            f"step {step.step_index}: context_hash mismatch "
            f"(recorded={step.context_hash[:12]} actual={actual[:12]}); "
            "serialization drift detected — refusing to attribute divergence to the agent"
        )

    # Guard 3: model identity. Necessary, not sufficient (provider may not bump string).
    result = model_call(context, **step.sampling_params)
    if result.get("model_version_string") != step.model_version_string:
        raise ReplayFidelityError(
            f"step {step.step_index}: model version drift "
            f"(recorded={step.model_version_string} actual={result.get('model_version_string')})"
        )
    return result
