# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-tool-call-lineage-when-agent-identity-session-and-span-correlation-diverge-under-concurrent-sub-agent-fan-ou.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-tool-call-lineage-when-agent-identity-session-and-span-correlation-diverge-under-concurrent-sub-agent-fan-ou.warrant.json
# Markdown SHA-256:   851780b1e228f0feff32c6b95aec1b3328627061bb3a1ff710fa5f0cdf3ba816
# Code AST SHA-256:   6ed7c5a48eb6199946995c30e6b5a5f058e161871100df80c15a0fbf5cecc096
# Verified Classes:   LineageIntegrityError, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

import hashlib
from dataclasses import dataclass
from typing import Optional

class LineageIntegrityError(RuntimeError):
    """Raised when a tool-call span's correlation tuple is not unique/coherent."""
    pass

@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    session_id: str
    agent_instance_id: str
    agent_role: str
    kind: str
    start: float
    end: float
    parallel_tool_calls: bool = False
    cumulative_tokens: Optional[int] = None
    semantic_key: Optional[str] = None  # e.g., query string

def derive_instance_id(session_id: str, role: str) -> str:
    # The buggy derivation: collides across concurrent same-role siblings.
    return hashlib.sha1(f"{session_id}:{role}".encode()).hexdigest()

def validate_lineage(spans: list[Span]) -> None:
    by_id = {s.span_id: s for s in spans}
    # 1. Parent must exist and share session.
    for s in spans:
        if s.parent_span_id is None:
            continue
        parent = by_id.get(s.parent_span_id)
        if parent is None:
            continue
        if parent.session_id != s.session_id:
            raise LineageIntegrityError(
                f"span {s.span_id} parent crosses session boundary "
                f"({parent.session_id} != {s.session_id})"
            )
        if (s.semantic_key and parent.semantic_key
                and s.semantic_key != parent.semantic_key
                and s.kind == "fetch_page" and parent.kind == "web_search"):
            raise LineageIntegrityError(
                f"semantic parent-child mismatch: {s.span_id} "
                f"({s.semantic_key}) under {parent.span_id} ({parent.semantic_key})"
            )
    # 2. Overlapping siblings under one agent span require explicit parallel flag.
    for parent in spans:
        if parent.kind != "agent":
            continue
        children = [c for c in spans if c.parent_span_id == parent.span_id
                    and c.kind.startswith("tool_call")]
        for i in range(len(children)):
            for j in range(i + 1, len(children)):
                a, b = children[i], children[j]
                overlap = a.start < b.end and b.start < a.end
                if overlap and not parent.parallel_tool_calls:
                    raise LineageIntegrityError(
                        f"overlapping tool spans {a.span_id},{b.span_id} "
                        f"under {parent.span_id} without parallel_tool_calls=true"
                    )
    # 3. Cumulative counters monotonic per unique instance id.
    per_instance: dict[str, list[Span]] = {}
    for s in spans:
        if s.cumulative_tokens is not None:
            per_instance.setdefault(s.agent_instance_id, []).append(s)
    for iid, group in per_instance.items():
        group.sort(key=lambda s: s.start)
        for prev, cur in zip(group, group[1:]):
            if cur.cumulative_tokens < prev.cumulative_tokens:
                raise LineageIntegrityError(
                    f"non-monotonic tokens for instance {iid}: "
                    f"{prev.cumulative_tokens} -> {cur.cumulative_tokens}"
                )

def assert_unique_instances(spans: list[Span]) -> None:
    # Collision detector: two distinct agent spans sharing one instance id
    # while not being the same span is a derivation bug.
    seen: dict[str, str] = {}
    for s in spans:
        if s.kind != "agent":
            continue
        prior = seen.get(s.agent_instance_id)
        if prior is not None and prior != s.span_id:
            raise LineageIntegrityError(
                f"agent identity collision: {s.agent_instance_id} "
                f"maps to spans {prior} and {s.span_id}"
            )
        seen[s.agent_instance_id] = s.span_id
