# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-span-attribute-lineage-collapse-when-genai-tool-call-spans-are-exported-asynchronously.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-span-attribute-lineage-collapse-when-genai-tool-call-spans-are-exported-asynchronously.warrant.json
# Markdown SHA-256:   c15cb9d7f051c66578fcace18c16f31f8cb63ba1ef33fd157781fc9d949b1b63
# Code AST SHA-256:   8b6279c6a8e3b17649d5b339b9acc2e2a2b0dd4d035f88c1b83d27ccfdc97fa8
# Verified Classes:   LineageCollapseError, GenAISpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class LineageCollapseError(RuntimeError):
    """Raised when a GenAI tool-call span cannot be joined to a model-invocation span."""
    pass

@dataclass
class GenAISpan:
    operation: str                 # gen_ai.operation.name
    tool_call_id: Optional[str]    # gen_ai.tool.call.id (tool spans only)
    tool_call_ids: list = field(default_factory=list)  # gen_ai.response.tool_call_ids (chat spans)
    finish_reasons: list = field(default_factory=list)
    sampled: bool = True

def reconstruct_lineage(spans: list) -> dict:
    """
    Enforce the co-location invariant: a chat span that reports tool_calls
    in finish_reasons must either (a) carry the tool_call_ids redundantly,
    or (b) have all child tool spans present in the same sampled set.
    """
    chats = [s for s in spans if s.operation == "chat" and s.sampled]
    tools = [s for s in spans if s.operation == "execute_tool" and s.sampled]
    tool_ids_present = {t.tool_call_id for t in tools if t.tool_call_id}

    lineage = {}
    for chat in chats:
        if "tool_calls" not in chat.finish_reasons:
            continue
        declared = set(chat.tool_call_ids)
        if declared:
            resolvable = declared & tool_ids_present
            lineage[id(chat)] = {"declared": declared, "resolved": resolvable,
                                 "source": "redundant_attribute"}
            continue
        # No redundant attribute: must rely on child presence.
        # If children were sampled out, lineage is unrecoverable.
        if not declared and not tool_ids_present:
            raise LineageCollapseError(
                f"chat span finish_reasons={chat.finish_reasons} declares tool_calls "
                f"but carries no gen_ai.response.tool_call_ids and no child tool spans "
                f"survived sampling; lineage is unrecoverable without timestamp fallback "
                f"(which mis-attributes across turns)."
            )
        lineage[id(chat)] = {"declared": declared, "resolved": tool_ids_present,
                             "source": "child_presence"}
    return lineage

def safe_reconstruct(spans: list) -> dict:
    try:
        return reconstruct_lineage(spans)
    except LineageCollapseError as e:
        # Do NOT fall back to timestamp adjacency; emit an explicit gap marker.
        return {"_lineage_gap": str(e), "_fallback": None}
