# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-convention-drift-in-its-own-emitted-agent-spans-before-downstream-trace-assembly-silently-misattributes-causality.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-convention-drift-in-its-own-emitted-agent-spans-before-downstream-trace-assembly-silently-misattributes-causality.warrant.json
# Markdown SHA-256:   283a6b4d0bc01367acef8d7f4c743e8b69c395b5151479597beb7749a911b911
# Code AST SHA-256:   b144b658a1539ad20c946fdcb2750a2804dd68ec863d965a9c7f96ec40cbd002
# Verified Classes:   ConventionDriftError, AssemblerContract
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ConventionDriftError(RuntimeError):
    """Raised when an agent is about to emit a span whose causal correlation
    the configured downstream assembler revision cannot be shown to parse."""
    pass


@dataclass(frozen=True)
class AssemblerContract:
    revision: str
    # attribute name under which the chat span records the tool-call id
    chat_correlation_key: str
    # whether the assembler reparents uncorrelated tool spans (dangerous)
    reparents_uncorrelated: bool


# The emitting agent's own SDK convention revision.
EMITTER_REVISION = "genai-1.27"

# Known-good assembler contracts the emitter has been validated against.
VALIDATED_CONTRACTS = {
    "genai-1.27": AssemblerContract("genai-1.27", "gen_ai.tool.call.id", False),
    "genai-1.29": AssemblerContract("genai-1.29", "gen_ai.tool.call.event", False),
}


def assert_emission_safe(contract: AssemblerContract, chat_span_writer) -> None:
    """Called immediately before emitting an execute_tool span.

    chat_span_writer is the callable the agent uses to write the parent chat
    span's correlation record. We verify the key it writes is the key the
    assembler reads, and that the assembler will not silently reparent.
    """
    if contract.revision not in VALIDATED_CONTRACTS:
        raise ConventionDriftError(
            f"assembler revision {contract.revision!r} has no validated "
            f"emitter contract; refusing to emit unverifiable causal edge"
        )

    validated = VALIDATED_CONTRACTS[contract.revision]
    written_key = chat_span_writer.correlation_key

    if written_key != validated.chat_correlation_key:
        raise ConventionDriftError(
            f"emitter writes tool-call correlation under {written_key!r} but "
            f"assembler revision {contract.revision!r} reads "
            f"{validated.chat_correlation_key!r}; correlation would be lost"
        )

    if contract.reparents_uncorrelated:
        raise ConventionDriftError(
            "assembler reparents uncorrelated tool spans to the most recent "
            "chat span; retry paths would be silently misattributed. "
            "Require fallback-hostile assembler config before emitting."
        )


def emit_tool_span(contract: AssemblerContract, chat_span_writer, tool_span) -> None:
    assert_emission_safe(contract, chat_span_writer)
    # Only reached when the causal edge is verifiable end-to-end.
    tool_span.set_attribute("gen_ai.tool.call.id", chat_span_writer.last_call_id)
    tool_span.end()
