# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-boundary-be-drawn-between-a-model-call-and-its-tool-side-effects-for-counterfactual-replay-to-be-sound.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-boundary-be-drawn-between-a-model-call-and-its-tool-side-effects-for-counterfactual-replay-to-be-sound.warrant.json
# Markdown SHA-256:   882326857ba7720ef6d20ab07be55306dffb3d05100932b70927b2f962ed9cad
# Code AST SHA-256:   130b65d1e3c77e518e43f550c863135cca41d400f2b9190f00b6763119d89fbb
# Verified Classes:   UnsoundReplayBoundaryError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnsoundReplayBoundaryError(RuntimeError):
    """Raised when a counterfactual branch attempts to re-bind a recorded
    tool output to arguments that differ from those recorded on the tool span."""
    pass


def bind_tool_output(model_span, tool_span):
    call_id = model_span.get("gen_ai.tool.call.id")
    if not call_id:
        raise UnsoundReplayBoundaryError(
            f"model span {model_span.get('span_id')} has no gen_ai.tool.call.id; "
            "counterfactual replay is unsound without call-ID binding"
        )
    if tool_span.get("gen_ai.tool.call.id") != call_id:
        raise UnsoundReplayBoundaryError(
            f"tool span {tool_span.get('span_id')} call-id mismatch: "
            f"{tool_span.get('gen_ai.tool.call.id')!r} != {call_id!r}"
        )
    recorded_args = tool_span.get("input.value")
    branch_args = model_span.get("gen_ai.tool.call.arguments")
    if recorded_args != branch_args:
        raise UnsoundReplayBoundaryError(
            f"tool span {tool_span.get('span_id')} recorded output is valid only for "
            f"arguments {recorded_args!r}; counterfactual arguments {branch_args!r} "
            "invalidate it. Truncate the branch at this model span."
        )
    return tool_span.get("output.value")
