# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-branch-replay-diverge-from-the-recorded-trace-when-the-branch-was-marked-committed-but-its-parent-agent-had-alre.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-branch-replay-diverge-from-the-recorded-trace-when-the-branch-was-marked-committed-but-its-parent-agent-had-alre.warrant.json
# Markdown SHA-256:   88c757587bba4ca5cd6d3370dcf987e12d80729a0eb121c841c0c5a9998200e6
# Code AST SHA-256:   65d810252ffdb304a51ec7be66086409993c52ac832b2aea88f6dd7351e966d8
# Verified Classes:   UnreplayableBranchError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UnreplayableBranchError(RuntimeError):
    """Raised when a committed speculative branch cannot be faithfully replayed
    because its frozen input snapshot is absent and its parent context was
    reclaimed before the replay window closed."""
    pass


def replay_branch(branch_record, parent_store, event_log):
    # The frozen snapshot is the ONLY authoritative source of branch inputs.
    snapshot = branch_record.get("frozen_input_snapshot")
    if snapshot is None:
        # Do NOT fall back to reconstructing from parent_store. That is the bug.
        parent_id = branch_record.get("parent_agent_id")
        reclaimed = event_log.was_reclaimed(parent_id)
        raise UnreplayableBranchError(
            f"branch {branch_record['branch_id']} has no frozen input snapshot; "
            f"parent {parent_id} reclaimed={reclaimed}; "
            f"refusing to reconstruct context from parent state"
        )

    parent_ctx = parent_store.get(branch_record["parent_agent_id"])
    if parent_ctx is None and branch_record.get("commit_logical_time") is not None:
        # Parent gone but snapshot present: replay is still valid, but flag it
        # so the analyst knows the parent chain was truncated.
        branch_record["_parent_truncated"] = True

    return _execute_with_inputs(branch_record["agent_id"], snapshot)


def _execute_with_inputs(agent_id, snapshot):
    # Deterministic re-execution against frozen inputs only.
    return {"agent_id": agent_id, "inputs": snapshot, "status": "replayed"}
