# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-missing-gen-ai-tool-call-id-on-a-child-span-as-a-lineage-break-rather-than-a-benign-omission.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-missing-gen-ai-tool-call-id-on-a-child-span-as-a-lineage-break-rather-than-a-benign-omission.warrant.json
# Markdown SHA-256:   63fd30820a4293b6305a8e4887af3a10e0e5deb8808534498aa76c60b25f32b5
# Code AST SHA-256:   fcb24c4001cd00b31d56796132e3e854a5b08e49f5dac529e41bcb2d979e38e0
# Verified Classes:   GenAILineageBreak, CrossContextContamination
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class GenAILineageBreak(RuntimeError):
    """Raised when a parent span's declared gen_ai.tool.call.id set is not
    fully accounted for by descendant tool spans."""
    pass


class CrossContextContamination(GenAILineageBreak):
    """Raised when a child tool span carries a gen_ai.tool.call.id that
    appears in no ancestor's declared set."""
    pass


def verify_tool_lineage(parent_span: dict, child_spans: list[dict]) -> None:
    declared = parent_span.get("gen_ai.tool.call.id") or []
    if not declared:
        # No fan-out obligation: missing child IDs are benign.
        parent_span["gen_ai.lineage.unverified"] = True
        return

    declared_set = set(declared)
    child_ids = {
        c["gen_ai.tool.call.id"]
        for c in child_spans
        if c.get("gen_ai.tool.call.id")
    }

    unaccounted = declared_set - child_ids
    if unaccounted:
        raise GenAILineageBreak(
            f"parent {parent_span['span_id']} declared tool calls "
            f"{sorted(unaccounted)} with no matching child span; "
            f"likely retry re-entry or dropped attribute on child instrumentation"
        )

    foreign = child_ids - declared_set
    if foreign:
        raise CrossContextContamination(
            f"child spans under {parent_span['span_id']} carry tool call ids "
            f"{sorted(foreign)} not declared by any ancestor; "
            f"likely A2A namespace contamination or model-synthesized id"
        )
