# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-attribute-emission-as-a-transactional-boundary-rather-than-a-fire-and-forget-log.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-attribute-emission-as-a-transactional-boundary-rather-than-a-fire-and-forget-log.warrant.json
# Markdown SHA-256:   32989f7cedc42bd33d230c09b848f272223a3264d314b5942f53f895797ceb38
# Code AST SHA-256:   52a5b5efdfeb0609b8cfa27d12723526ccff0632581884789a8a0af2426604fb
# Verified Classes:   ReconstructiveAttributeMisuse
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ReconstructiveAttributeMisuse(RuntimeError):
    """Raised when agent state is derived from a sampled/async span attribute."""
    pass


# Attributes whose loss changes a downstream decision are reconstructive.
RECONSTRUCTIVE_ATTRS = frozenset({
    "gen_ai.usage.input_tokens",
    "gen_ai.usage.output_tokens",
    "gen_ai.response.finish_reasons",
    "gen_ai.tool.call.id",
})


def resolve_attribute(
    attr_name: str,
    *,
    span_attrs: dict,
    checkpoint: dict,
    export_is_synchronous_and_unsampled: bool,
) -> object:
    """Resolve a gen_ai.* attribute for a state-affecting decision.

    Reconstructive attributes MUST come from the durable checkpoint unless the
    exporter path is synchronous, unsampled, and transactional with the
    checkpoint (rare). Otherwise the span is a sample, not a fact.
    """
    if attr_name not in RECONSTRUCTIVE_ATTRS:
        # Decorative: span is fine, may be absent.
        return span_attrs.get(attr_name)

    if export_is_synchronous_and_unsampled:
        # Only configuration where span attribute is authoritative.
        if attr_name not in span_attrs:
            raise ReconstructiveAttributeMisuse(
                f"{attr_name} missing from synchronous span; state transition "
                f"did not commit — aborting turn."
            )
        return span_attrs[attr_name]

    # Async/sampled path: span may have been dropped. Checkpoint is truth.
    if attr_name not in checkpoint:
        raise ReconstructiveAttributeMisuse(
            f"{attr_name} is reconstructive but absent from checkpoint. "
            f"Reading it from a sampled span would fabricate agent state. "
            f"Refusing to resume/replay/bill from trace."
        )
    return checkpoint[attr_name]


def commit_turn(
    *,
    finish_reasons: list[str],
    usage: dict,
    tool_call_ids: list[str],
    checkpoint_store,
    span,
) -> None:
    """Dual-write: checkpoint is the commit, span is the echo."""
    record = {
        "gen_ai.response.finish_reasons": finish_reasons,
        "gen_ai.usage.input_tokens": usage["input_tokens"],
        "gen_ai.usage.output_tokens": usage["output_tokens"],
        "gen_ai.tool.call.id": tool_call_ids,
    }
    # Commit first; if this fails, the turn did not happen.
    checkpoint_store.write_atomic(record)

    # Echo to span; loss here is observational, not correctness.
    span.set_attribute("gen_ai.response.finish_reasons", finish_reasons)
    span.set_attribute("gen_ai.usage.input_tokens", usage["input_tokens"])
    span.set_attribute("gen_ai.usage.output_tokens", usage["output_tokens"])
    span.end()


def resume_session(
    *,
    checkpoint: dict,
    sampled_trace_attrs: dict,
    export_is_synchronous_and_unsampled: bool = False,
) -> dict:
    """Resume must never reconstruct state from a sampled trace."""
    finish = resolve_attribute(
        "gen_ai.response.finish_reasons",
        span_attrs=sampled_trace_attrs,
        checkpoint=checkpoint,
        export_is_synchronous_and_unsampled=export_is_synchronous_and_unsampled,
    )
    call_ids = resolve_attribute(
        "gen_ai.tool.call.id",
        span_attrs=sampled_trace_attrs,
        checkpoint=checkpoint,
        export_is_synchronous_and_unsampled=export_is_synchronous_and_unsampled,
    )
    return {"finish_reasons": finish, "pending_tool_calls": call_ids}
