# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-span-lineage-when-gen-ai-attributes-are-emitted-after-a-mid-invocation-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-span-lineage-when-gen-ai-attributes-are-emitted-after-a-mid-invocation-context-compaction.warrant.json
# Markdown SHA-256:   41e736657d20ced81843bb6cb8c52e41b3170e57e32311cc9ea7ea43d865bbea
# Code AST SHA-256:   eb09e73f7b0a37dbe1286f2bd89eee95368f3b0fea284f43057994405b9a8c67
# Verified Classes:   GenAICompactionLineageError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class GenAICompactionLineageError(RuntimeError):
    """Raised when a gen_ai.* span would straddle a context compaction,
    violating the one-span-one-payload invariant of the GenAI conventions."""


def emit_genai_span(span, prompt_tokens: int, payload_hash: str, compacted: bool) -> None:
    if compacted:
        raise GenAICompactionLineageError(
            f"span {span.name!r} would close after a context compaction; "
            f"payload_hash={payload_hash} no longer matches the prompt the model saw. "
            "Close the span before compaction and open a new per-call child span."
        )
    span.set_attribute("gen_ai.usage.input_tokens", prompt_tokens)
    span.set_attribute("gen_ai.content.prompt.hash", payload_hash)


def close_invocation(span, prompt_tokens: int, payload_hash: str, compaction_fired: bool) -> None:
    try:
        emit_genai_span(span, prompt_tokens, payload_hash, compaction_fired)
    except GenAICompactionLineageError:
        span.add_event("gen_ai.compaction", {"gen_ai.compaction.reason": "mid_invocation"})
        span.end()
        raise
    span.end()
