# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-spans-when-genai-trace-correlation-ids-are-reused-across-divergent-rollouts.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-spans-when-genai-trace-correlation-ids-are-reused-across-divergent-rollouts.warrant.json
# Markdown SHA-256:   df123d6385cb41ab338f5b1ebc2090c61aa1c56aa5a6ac6630dc17b50f181561
# Code AST SHA-256:   099f1a3c23a3d1a63c0c1e9370ea04c8cfa7598cf67b2cf4c7182566a8ce43cb
# Verified Classes:   BranchCorrelationError, BranchOutcome, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class BranchCorrelationError(RuntimeError):
    """Raised when a speculative branch span violates causal-exclusivity invariants."""


class BranchOutcome(Enum):
    PENDING = "pending"
    COMMITTED = "committed"
    DISCARDED = "discarded"


@dataclass
class GenAISpan:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    operation: str
    branch_id: Optional[str] = None
    outcome: BranchOutcome = BranchOutcome.PENDING
    input_tokens: int = 0
    output_tokens: int = 0
    links: list[str] = field(default_factory=list)


def emit_speculative_branch(
    orchestrator: GenAISpan,
    branch_id: str,
    *,
    re_root: bool,
    input_tokens: int,
    output_tokens: int,
) -> GenAISpan:
    """
    Emit a chat span for a speculative rollout. Enforces that a branch is
    causally exclusive: it must NOT share the orchestrator's span_id as parent
    when post-hoc consumers will join on the trace.
    """
    if not branch_id:
        raise BranchCorrelationError(
            "speculative branch emitted without agent.branch_id; trace join is ambiguous"
        )

    if re_root:
        # Correct model: own trace, link back to orchestrator, no shared parent.
        return GenAISpan(
            trace_id=f"{orchestrator.trace_id}#{branch_id}",
            span_id=f"{orchestrator.span_id}/{branch_id}",
            parent_span_id=None,
            operation="chat",
            branch_id=branch_id,
            input_tokens=input_tokens,
            output_tokens=output_tokens,
            links=[orchestrator.span_id],
        )

    # Shared-parent model: legal ONLY if no consumer joins on parent.
    # We cannot know that here, so we refuse unless the caller has opted in
    # via an explicit marker on the orchestrator.
    if not getattr(orchestrator, "trace_is_write_only", False):
        raise BranchCorrelationError(
            f"branch {branch_id!r} would share parent {orchestrator.span_id!r} "
            "on a consumer-joined trace; re-root the branch or mark the trace "
            "write-only before emitting"
        )

    return GenAISpan(
        trace_id=orchestrator.trace_id,
        span_id=f"{orchestrator.span_id}/{branch_id}",
        parent_span_id=orchestrator.span_id,
        operation="chat",
        branch_id=branch_id,
        input_tokens=input_tokens,
        output_tokens=output_tokens,
    )


def recompute_committed_budget(spans: list[GenAISpan], per_token_cost: float) -> float:
    """
    Sum spend over the committed causal chain only. Refuses to guess when the
    commit decision is missing — that is the corruption we are guarding against.
    """
    committed = [s for s in spans if s.outcome is BranchOutcome.COMMITTED]
    if len(committed) != 1:
        raise BranchCorrelationError(
            f"expected exactly one committed branch, found {len(committed)}; "
            "trace cannot be used for budget recomputation"
        )
    winner = committed[0]
    if not winner.branch_id:
        raise BranchCorrelationError(
            "committed span lacks agent.branch_id; provenance is unrecoverable"
        )
    return (winner.input_tokens + winner.output_tokens) * per_token_cost
