# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-attribute-drift-when-tool-call-telemetry-is-emitted-by-a-non-conforming-sub-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-attribute-drift-when-tool-call-telemetry-is-emitted-by-a-non-conforming-sub-agent.warrant.json
# Markdown SHA-256:   0b29ca41df9d23bc224b5e0c682a3e34d82ce1926b5608c1d6888aaac0a8f24c
# Code AST SHA-256:   4f26ed747fb31c5f7f6c0ac2e9052703fb6444db7d017701039866ff15329003
# Verified Classes:   NonReconcilableSubAgentError, SubAgentManifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field

CANONICAL_VERSION = "1.28.0"

# Attributes whose absence breaks join/dedup correctness -> must reject.
CORRELATION_KEYS = frozenset({
    "gen_ai.conversation.id",
    "gen_ai.tool.call.id",
    "gen_ai.agent.name",
})

# Lossless aliases only. Never include span-name string extraction here.
ALIAS_MAP = {
    "gen_ai.usage.prompt_tokens": "gen_ai.usage.input_tokens",
    "gen_ai.usage.completion_tokens": "gen_ai.usage.output_tokens",
    "gen_ai.system": "gen_ai.provider.name",
}


class NonReconcilableSubAgentError(RuntimeError):
    """Raised when a sub-agent's GenAI instrumentation cannot be joined
    into the parent's accounting/dedup pipeline without silent loss."""


@dataclass
class SubAgentManifest:
    version: str
    emitted_keys: set = field(default_factory=set)


def _normalize_keys(emitted: set) -> set:
    normalized = set(emitted)
    for alias, canonical in ALIAS_MAP.items():
        if alias in emitted:
            normalized.add(canonical)
    return normalized


def assert_reconcilable(manifest: SubAgentManifest) -> set:
    """Return the set of canonical keys the child can supply, or raise.

    Called during A2A capability negotiation, BEFORE the sub-agent runs,
    so that a rejected handoff cannot leave a side effect behind.
    """
    normalized = _normalize_keys(manifest.emitted_keys)

    # Reject string-embedded call ids: span names are free text and the
    # extraction is a regex over unvalidated input -> not a safe join key.
    for key in manifest.emitted_keys:
        if re.search(r"\[call_[0-9a-f]+\]", key):
            raise NonReconcilableSubAgentError(
                f"sub-agent {manifest.version} embeds tool.call.id in span "
                f"name '{key}'; correlation key is not machine-joinable"
            )

    missing = CORRELATION_KEYS - normalized
    if missing:
        raise NonReconcilableSubAgentError(
            f"sub-agent {manifest.version} omits correlation keys "
            f"{sorted(missing)}; refusing handoff to avoid silent dedup "
            f"failure and duplicate side effects on resume"
        )

    if manifest.version != CANONICAL_VERSION:
        # Version drift is tolerable ONLY because all correlation keys
        # resolved via declared aliases. Record it for audit.
        print(
            f"[gen_ai.attr.alias_applied] child={manifest.version} "
            f"parent={CANONICAL_VERSION} keys={sorted(normalized & CORRELATION_KEYS)}"
        )

    return normalized


def delegate(manifest: SubAgentManifest, run_subtask) -> object:
    assert_reconcilable(manifest)  # fail closed, pre-execution
    return run_subtask()
