Skip to content

The platform for continuously improving AI agents.

33.2 KB
Raw Blame
# /// script
# requires-python = ">=3.10"
# dependencies = [
#     "httpx>=0.27",
#     "pyarrow>=15.0",
# ]
# ///
"""Import Exgentic/agent-llm-traces from Hugging Face into Overmind via OTLP/HTTP JSON.

Examples:
    uv run packages/otel/examples/import_exgentic.py --limit 600
    uv run packages/otel/examples/import_exgentic.py --limit 0  # all 1,781 traces
    uv run packages/otel/examples/import_exgentic.py --benchmark swebench --limit 100
"""

from __future__ import annotations

import argparse
import gzip
import hashlib
import json
import math
import sys
import time
from collections import Counter
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

import httpx
import pyarrow.parquet as pq

DATASET_ID = "Exgentic/agent-llm-traces"
PARQUET_LIST_URL = f"https://datasets-server.huggingface.co/parquet?dataset={DATASET_ID}"
DEFAULT_ENDPOINT = "http://127.0.0.1:4318/v1/traces"
DEFAULT_CACHE_DIR = Path.home() / ".cache" / "overmind-exgentic-traces"

EPOCH = datetime(1970, 1, 1, tzinfo=UTC)
NS_PER_SEC = 1_000_000_000
NS_PER_MS = 1_000_000
NS_PER_HOUR = 3600 * NS_PER_SEC
NS_PER_DAY = 24 * NS_PER_HOUR

SPAN_KIND_MAP = {
    "SPAN_KIND_UNSPECIFIED": 0,
    "SPAN_KIND_INTERNAL": 1,
    "SPAN_KIND_SERVER": 2,
    "SPAN_KIND_CLIENT": 3,
    "SPAN_KIND_PRODUCER": 4,
    "SPAN_KIND_CONSUMER": 5,
}

KNOWN_PROVIDERS = ("aws", "azure", "gcp", "openai", "anthropic", "google", "deepseek", "openrouter")


def deterministic_hex(seed: str, length: int) -> str:
    digest = hashlib.sha256(seed.encode("utf-8")).hexdigest()[:length]
    # OTel treats all-zero IDs as invalid/absent.
    if set(digest) == {"0"}:
        return "1" + digest[1:]
    return digest


def parse_iso_ns(raw: str | None) -> int | None:
    if not raw or not isinstance(raw, str):
        return None
    text = raw.strip()
    if not text:
        return None
    if text.endswith("Z"):
        text = text[:-1] + "+00:00"
    try:
        dt = datetime.fromisoformat(text)
    except ValueError:
        return None
    dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
    delta = dt - EPOCH
    return (delta.days * 86_400 + delta.seconds) * NS_PER_SEC + delta.microseconds * 1_000


def otlp_any_value(value: Any) -> dict[str, Any] | None:
    if value is None:
        return None
    if isinstance(value, bool):
        return {"boolValue": value}
    if isinstance(value, int):
        return {"intValue": str(value)}
    if isinstance(value, float):
        if not math.isfinite(value):
            return None
        return {"doubleValue": value}
    if isinstance(value, str):
        if value == "":
            return None
        return {"stringValue": value}
    if isinstance(value, (list, tuple)):
        items = [v for item in value if (v := otlp_any_value(item)) is not None]
        if not items:
            return None
        return {"arrayValue": {"values": items}}
    if isinstance(value, dict):
        return {"stringValue": json.dumps(value, ensure_ascii=False)}
    return {"stringValue": str(value)}


def otlp_attributes(mapping: dict[str, Any]) -> list[dict[str, Any]]:
    out: list[dict[str, Any]] = []
    for key, val in mapping.items():
        encoded = otlp_any_value(val)
        if encoded is not None:
            out.append({"key": key, "value": encoded})
    return out


def infer_provider(model: str | None) -> str | None:
    if not model or "/" not in model:
        return None
    prefix = model.split("/", 1)[0].strip().lower()
    if prefix in KNOWN_PROVIDERS:
        return prefix
    return prefix or None


def safe_json_loads(raw: str | None) -> Any:
    if not raw or not isinstance(raw, str):
        return None
    try:
        return json.loads(raw)
    except (ValueError, TypeError):
        return None


def clip_text(text: str, max_chars: int) -> str:
    if len(text) <= max_chars:
        return text
    return text[: max_chars - 24] + f"\n... [truncated {len(text) - max_chars + 24} chars]"


def stringify_value(val: Any, max_chars: int = 32_000) -> str | None:
    if val is None:
        return None
    s = val if isinstance(val, str) else json.dumps(val, ensure_ascii=False)
    if not s.strip():
        return None
    return clip_text(s, max_chars)


def extract_message_text(msg: dict[str, Any]) -> str:
    if isinstance(msg.get("content"), str) and msg["content"].strip():
        return msg["content"].strip()
    parts = msg.get("parts")
    if not isinstance(parts, list):
        return ""
    texts: list[str] = []
    tool_summaries: list[str] = []
    for part in parts:
        if not isinstance(part, dict):
            continue
        ptype = part.get("type")
        if ptype == "text":
            content = part.get("content") or part.get("text")
            if (
                isinstance(content, str)
                and content.strip()
                and content.strip() not in ("(no content)", "(no content")
            ):
                texts.append(content.strip())
        elif ptype == "tool_call":
            name = part.get("name") or "tool"
            args = part.get("arguments")
            args_str = json.dumps(args, ensure_ascii=False) if args is not None else "{}"
            tool_summaries.append(f"[tool_call: {name}({clip_text(args_str, 300)})]")
    if texts:
        return "\n".join(texts)
    if tool_summaries:
        return "\n".join(tool_summaries)
    return ""


def cap_messages_json(raw: str | None, max_bytes: int) -> str | None:
    if not raw or not isinstance(raw, str):
        return None
    if max_bytes <= 0 or len(raw.encode("utf-8")) <= max_bytes:
        return raw
    parsed = safe_json_loads(raw)
    if not isinstance(parsed, list) or not parsed:
        return clip_text(raw, max_bytes)

    # Keep the opening context message(s) and as many most-recent messages as fit in max_bytes.
    head = parsed[:1]
    tail: list[Any] = []
    budget = max_bytes - len(json.dumps(head, ensure_ascii=False).encode("utf-8")) - 128
    for msg in reversed(parsed[1:]):
        encoded_len = len(json.dumps(msg, ensure_ascii=False).encode("utf-8")) + 2
        if encoded_len <= budget:
            tail.append(msg)
            budget -= encoded_len
        elif not tail:
            # Even the single latest message exceeds budget; truncate its largest part cleanly.
            slim = dict(msg)
            if isinstance(slim.get("parts"), list):
                slim_parts = []
                for p in slim["parts"]:
                    if isinstance(p, dict):
                        pc = dict(p)
                        for field in ("content", "text", "result"):
                            if isinstance(pc.get(field), str) and len(pc[field]) > 4000:
                                pc[field] = clip_text(pc[field], 4000)
                        slim_parts.append(pc)
                slim["parts"] = slim_parts
            tail.append(slim)
            break
        else:
            break
    tail.reverse()
    omitted = len(parsed) - len(head) - len(tail)
    assembled = list(head)
    if omitted > 0:
        assembled.append(
            {
                "role": "system",
                "parts": [
                    {
                        "type": "text",
                        "content": f"[{omitted} intermediate messages omitted for size]",
                    }
                ],
            }
        )
    assembled.extend(tail)
    return json.dumps(assembled, ensure_ascii=False)


def extract_tool_def_summary(raw_spans: list[dict[str, Any]]) -> tuple[int | None, list[str]]:
    for s in raw_spans:
        attrs = s.get("attributes") or {}
        td_raw = attrs.get("gen_ai.tool.definitions")
        if not td_raw:
            continue
        parsed = safe_json_loads(td_raw)
        if isinstance(parsed, list):
            names: list[str] = []
            for item in parsed:
                if isinstance(item, dict):
                    name = item.get("name") or (item.get("function") or {}).get("name")
                    if isinstance(name, str) and name:
                        names.append(name)
            return len(parsed), names[:50]
    return None, []


def anchor_delta_ns(session_id: str, min_start: int, max_end: int, now_ns: int) -> int:
    # Keep timestamps inside the last 1–6 days if missing, older than 30 days, or in the future.
    thirty_days_ago = now_ns - 30 * NS_PER_DAY
    if thirty_days_ago <= max_end <= now_ns:
        return 0
    # Deterministic spread across [now - 6 days, now - 1 hour].
    h = int(hashlib.sha256(f"exgentic:anchor:{session_id}".encode()).hexdigest()[:8], 16)
    frac = h / 0xFFFFFFFF
    span_window = 6 * NS_PER_DAY - NS_PER_HOUR
    target_end = now_ns - NS_PER_HOUR - int(frac * span_window)
    duration = max(max_end - min_start, NS_PER_MS)
    # Cap pathological multi-day trace durations only if timestamps were corrupted.
    if duration > 12 * NS_PER_HOUR:
        duration = 12 * NS_PER_HOUR
    target_start = target_end - duration
    return target_start - min_start


def convert_row_to_resource_spans(
    row: dict[str, Any],
    now_ns: int,
    max_message_bytes: int,
) -> tuple[tuple[str, str], dict[str, Any], list[dict[str, Any]]] | None:
    raw_spans = row.get("spans") or []
    if not raw_spans:
        return None

    benchmark = (row.get("benchmark") or "unknown").strip()
    harness = (row.get("harness") or "unknown").strip()
    session_id = (row.get("session_id") or "").strip() or deterministic_hex(
        json.dumps(row, default=str)[:256], 16
    )
    models = [m for m in (row.get("models") or []) if isinstance(m, str) and m]
    collected_at = row.get("collected_at")
    service_name = f"exgentic/{benchmark}"

    trace_id = deterministic_hex(f"exgentic:trace:{session_id}", 32)
    root_span_id = deterministic_hex(f"exgentic:root:{session_id}", 16)

    # Parse timestamps and sort spans chronologically while preserving original order on ties.
    indexed_spans: list[tuple[int, int, int, dict[str, Any]]] = []
    parsed_times: list[tuple[int | None, int | None]] = []
    for s in raw_spans:
        st = parse_iso_ns(s.get("start_time"))
        et = parse_iso_ns(s.get("end_time"))
        parsed_times.append((st, et))

    valid_starts = [t for t, _ in parsed_times if t is not None]
    base_fallback_ns = min(valid_starts) if valid_starts else (now_ns - 2 * NS_PER_HOUR)

    cursor_ns = base_fallback_ns
    for idx, (s, (st, et)) in enumerate(zip(raw_spans, parsed_times, strict=True)):
        start_ns = st if st is not None else cursor_ns
        end_ns = et if et is not None else start_ns
        if end_ns < start_ns:
            end_ns = start_ns
        cursor_ns = max(cursor_ns, end_ns)
        indexed_spans.append((start_ns, idx, end_ns, s))

    indexed_spans.sort(key=lambda item: (item[0], item[1]))

    min_start = min(item[0] for item in indexed_spans)
    max_end = max(item[2] for item in indexed_spans)
    delta_ns = anchor_delta_ns(session_id, min_start, max_end, now_ns)

    # Pre-scan all input messages across the trace to collect tool_call_response results by call_id.
    tool_results_by_id: dict[str, Any] = {}
    parsed_in_msgs: list[list[dict[str, Any]] | None] = []
    parsed_out_msgs: list[list[dict[str, Any]] | None] = []
    for _, _, _, s in indexed_spans:
        attrs = s.get("attributes") or {}
        im = safe_json_loads(attrs.get("gen_ai.input.messages"))
        om = safe_json_loads(attrs.get("gen_ai.output.messages"))
        im_list = im if isinstance(im, list) else None
        om_list = om if isinstance(om, list) else None
        parsed_in_msgs.append(im_list)
        parsed_out_msgs.append(om_list)
        if im_list:
            for msg in im_list:
                if not isinstance(msg, dict):
                    continue
                for part in msg.get("parts") or []:
                    if isinstance(part, dict) and part.get("type") == "tool_call_response":
                        cid = part.get("id")
                        if isinstance(cid, str) and cid and cid not in tool_results_by_id:
                            tool_results_by_id[cid] = part.get("result")

    # Extract initial user input and final assistant output for the root agent span.
    root_input: str | None = None
    for im_list in parsed_in_msgs:
        if not im_list:
            continue
        for msg in im_list:
            if isinstance(msg, dict) and msg.get("role") == "user":
                text = extract_message_text(msg)
                if text:
                    root_input = clip_text(text, 16_000)
                    break
        if root_input:
            break

    root_output: str | None = None
    for om_list in reversed(parsed_out_msgs):
        if not om_list:
            continue
        for msg in reversed(om_list):
            if isinstance(msg, dict):
                text = extract_message_text(msg)
                if text:
                    root_output = clip_text(text, 16_000)
                    break
        if root_output:
            break

    tool_def_count, tool_def_names = extract_tool_def_summary(raw_spans)

    child_spans: list[dict[str, Any]] = []
    failed_llm_calls = 0
    total_tool_calls = 0
    last_error_message = ""
    last_llm_failed = False
    shifted_max_end = max_end + delta_ns
    shifted_min_start = min_start + delta_ns

    for turn_idx, (orig_start, orig_idx, orig_end, s) in enumerate(indexed_spans):
        start_ns = orig_start + delta_ns
        end_ns = orig_end + delta_ns
        raw_span_id = str(s.get("span_id") or orig_idx)
        llm_span_id = deterministic_hex(f"exgentic:llm:{session_id}:{orig_idx}:{raw_span_id}", 16)

        raw_attrs = s.get("attributes") or {}
        req_model = raw_attrs.get("gen_ai.request.model")
        resp_model = raw_attrs.get("gen_ai.response.model")
        op_name = raw_attrs.get("gen_ai.operation.name") or "chat"
        provider = infer_provider(resp_model or req_model)

        raw_status = s.get("status") or {}
        status_code = raw_status.get("code")
        if status_code not in (0, 1, 2):
            status_code = 1
        status_message = (raw_status.get("message") or "").strip()

        is_err = status_code == 2
        if is_err:
            failed_llm_calls += 1
            if not status_message:
                status_message = "LLM call failed"
            last_error_message = status_message
        last_llm_failed = is_err

        in_tokens = raw_attrs.get("gen_ai.usage.input_tokens")
        out_tokens = raw_attrs.get("gen_ai.usage.output_tokens")

        llm_attr_map: dict[str, Any] = {
            "overmind.span.type": "llm",
            "gen_ai.operation.name": op_name,
            "gen_ai.provider.name": provider,
            "gen_ai.request.model": req_model,
            "gen_ai.response.model": resp_model,
            "gen_ai.response.id": raw_attrs.get("gen_ai.response.id"),
            "gen_ai.response.finish_reasons": raw_attrs.get("gen_ai.response.finish_reasons"),
            "gen_ai.input.messages": cap_messages_json(
                raw_attrs.get("gen_ai.input.messages"), max_message_bytes
            ),
            "gen_ai.output.messages": cap_messages_json(
                raw_attrs.get("gen_ai.output.messages"), max_message_bytes
            ),
            "gen_ai.conversation.id": session_id,
            "exgentic.benchmark": benchmark,
            "exgentic.harness": harness,
            "exgentic.turn_index": turn_idx,
        }
        # Follow pkg/tracing.md: omit unknown token counts rather than zero-filling.
        if isinstance(in_tokens, int) and in_tokens >= 0:
            llm_attr_map["gen_ai.usage.input_tokens"] = in_tokens
        if isinstance(out_tokens, int) and out_tokens >= 0:
            llm_attr_map["gen_ai.usage.output_tokens"] = out_tokens
        if is_err:
            llm_attr_map["error.type"] = "LLMInferenceError"

        span_kind = SPAN_KIND_MAP.get(str(s.get("kind") or ""), 3)
        child_spans.append(
            {
                "traceId": trace_id,
                "spanId": llm_span_id,
                "parentSpanId": root_span_id,
                "name": s.get("name") or f"{op_name} {resp_model or req_model or 'llm'}",
                "kind": span_kind,
                "startTimeUnixNano": str(start_ns),
                "endTimeUnixNano": str(end_ns),
                "attributes": otlp_attributes(llm_attr_map),
                "status": {"code": status_code, "message": status_message},
            }
        )

        # Synthesize child tool execution spans for any tool_call parts emitted by this LLM turn.
        om_list = parsed_out_msgs[turn_idx] or []
        tool_calls: list[dict[str, Any]] = []
        for msg in om_list:
            if not isinstance(msg, dict):
                continue
            for part in msg.get("parts") or []:
                if isinstance(part, dict) and part.get("type") == "tool_call":
                    tool_calls.append(part)

        if tool_calls:
            next_start_ns = (
                indexed_spans[turn_idx + 1][0] + delta_ns
                if turn_idx + 1 < len(indexed_spans)
                else end_ns + 50 * NS_PER_MS
            )
            gap_ns = next_start_ns - end_ns
            n_tools = len(tool_calls)
            if gap_ns >= n_tools * NS_PER_MS:
                # Place tool spans sequentially across the gap between LLM turn i and turn i+1.
                slot_ns = min(gap_ns // n_tools, 60 * NS_PER_SEC)
            else:
                slot_ns = 25 * NS_PER_MS

            for tc_idx, tc in enumerate(tool_calls):
                total_tool_calls += 1
                t_name = str(tc.get("name") or "unknown_tool")
                call_id = str(tc.get("id") or f"call_{turn_idx}_{tc_idx}")
                t_start = end_ns + tc_idx * slot_ns
                t_end = t_start + slot_ns
                if t_end > shifted_max_end:
                    shifted_max_end = t_end

                args_str = stringify_value(tc.get("arguments"), max_chars=32_000)
                result_str = stringify_value(tool_results_by_id.get(call_id), max_chars=32_000)
                tool_span_id = deterministic_hex(
                    f"exgentic:tool:{session_id}:{orig_idx}:{tc_idx}:{call_id}", 16
                )
                tool_attr_map: dict[str, Any] = {
                    "overmind.span.type": "tool",
                    "gen_ai.operation.name": "execute_tool",
                    "gen_ai.tool.name": t_name,
                    "gen_ai.tool.call.id": call_id,
                    "gen_ai.tool.call.arguments": args_str,
                    "gen_ai.tool.call.result": result_str,
                    "overmind.input": args_str,
                    "overmind.output": result_str,
                    "gen_ai.conversation.id": session_id,
                    "exgentic.benchmark": benchmark,
                    "exgentic.harness": harness,
                    "exgentic.turn_index": turn_idx,
                }
                child_spans.append(
                    {
                        "traceId": trace_id,
                        "spanId": tool_span_id,
                        "parentSpanId": root_span_id,
                        "name": f"tool.{t_name}",
                        "kind": 1,
                        "startTimeUnixNano": str(t_start),
                        "endTimeUnixNano": str(t_end),
                        "attributes": otlp_attributes(tool_attr_map),
                        "status": {"code": 1, "message": ""},
                    }
                )

    if shifted_max_end <= shifted_min_start:
        shifted_max_end = shifted_min_start + NS_PER_MS

    root_failed = last_llm_failed or (failed_llm_calls == len(indexed_spans))
    root_attr_map: dict[str, Any] = {
        "overmind.span.type": "agent",
        "gen_ai.operation.name": "invoke_agent",
        "gen_ai.conversation.id": session_id,
        "overmind.input": root_input,
        "overmind.output": root_output,
        "exgentic.benchmark": benchmark,
        "exgentic.harness": harness,
        "exgentic.session_id": session_id,
        "exgentic.models": models,
        "exgentic.collected_at": collected_at,
        "exgentic.llm_calls": len(indexed_spans),
        "exgentic.tool_calls": total_tool_calls,
        "exgentic.failed_calls": failed_llm_calls,
    }
    if tool_def_count is not None:
        root_attr_map["exgentic.tool_definitions.count"] = tool_def_count
    if tool_def_names:
        root_attr_map["exgentic.tool_definitions.names"] = tool_def_names
    if root_failed:
        root_attr_map["error.type"] = "AgentRunError"

    root_span = {
        "traceId": trace_id,
        "spanId": root_span_id,
        "parentSpanId": "",
        "name": f"agent.{harness}",
        "kind": 1,
        "startTimeUnixNano": str(shifted_min_start),
        "endTimeUnixNano": str(shifted_max_end),
        "attributes": otlp_attributes(root_attr_map),
        "status": {
            "code": 2 if root_failed else 1,
            "message": (last_error_message or "agent run ended with error") if root_failed else "",
        },
    }

    first_res = (raw_spans[0].get("resource_attributes") or {}) if raw_spans else {}
    resource_attrs = otlp_attributes(
        {
            "service.name": service_name,
            "service.version": first_res.get("service.version") or "1.0.0",
            "deployment.environment.name": "benchmark",
            "telemetry.sdk.name": first_res.get("telemetry.sdk.name") or "opentelemetry",
            "telemetry.sdk.language": first_res.get("telemetry.sdk.language") or "python",
            "exgentic.dataset": DATASET_ID,
            "exgentic.benchmark": benchmark,
            "exgentic.harness": harness,
        }
    )

    return (service_name, harness), {"attributes": resource_attrs}, [root_span, *child_spans]


def post_otlp_batch(
    client: httpx.Client,
    endpoint: str,
    grouped: dict[tuple[str, str], tuple[dict[str, Any], list[dict[str, Any]]]],
    max_retries: int = 8,
) -> int:
    resource_spans = []
    span_count = 0
    for resource, spans in grouped.values():
        if not spans:
            continue
        span_count += len(spans)
        resource_spans.append(
            {
                "resource": resource,
                "scopeSpans": [
                    {
                        "scope": {"name": "exgentic.importer", "version": "1.0.0"},
                        "spans": spans,
                    }
                ],
            }
        )
    if not resource_spans:
        return 0

    payload_bytes = json.dumps({"resourceSpans": resource_spans}, ensure_ascii=False).encode(
        "utf-8"
    )
    compressed = gzip.compress(payload_bytes, compresslevel=5)
    headers = {
        "Content-Type": "application/json",
        "Content-Encoding": "gzip",
    }

    backoff = 0.5
    last_exc: Exception | None = None
    for attempt in range(1, max_retries + 1):
        try:
            resp = client.post(endpoint, content=compressed, headers=headers, timeout=60.0)
            if resp.status_code == 200:
                return span_count
            if resp.status_code in (429, 500, 502, 503, 504) and attempt < max_retries:
                print(
                    f"  [retry {attempt}/{max_retries}] HTTP {resp.status_code}: {resp.text[:200]}",
                    file=sys.stderr,
                )
            else:
                raise RuntimeError(f"OTLP ingest failed HTTP {resp.status_code}: {resp.text[:400]}")
        except (httpx.TransportError, httpx.TimeoutException) as exc:
            last_exc = exc
            if attempt == max_retries:
                raise RuntimeError(
                    f"OTLP ingest failed after {max_retries} retries: {exc}"
                ) from exc
            print(
                f"  [retry {attempt}/{max_retries}] connection error: {exc} (sleeping {backoff:.1f}s)",
                file=sys.stderr,
            )
        time.sleep(backoff)
        backoff = min(backoff * 1.8, 10.0)

    raise RuntimeError(f"OTLP ingest failed: {last_exc}")


def fetch_parquet_manifest(client: httpx.Client) -> list[dict[str, Any]]:
    resp = client.get(PARQUET_LIST_URL, timeout=30.0)
    resp.raise_for_status()
    return resp.json()["parquet_files"]


def download_shard(client: httpx.Client, shard: dict[str, Any], cache_dir: Path) -> Path:
    cache_dir.mkdir(parents=True, exist_ok=True)
    target = cache_dir / shard["filename"]
    expected_size = shard.get("size")
    if target.exists() and (expected_size is None or target.stat().st_size == expected_size):
        return target
    tmp = target.with_suffix(".parquet.part")
    with client.stream("GET", shard["url"], follow_redirects=True, timeout=180.0) as resp:
        resp.raise_for_status()
        with tmp.open("wb") as fp:
            for chunk in resp.iter_bytes(chunk_size=1024 * 1024):
                fp.write(chunk)
    tmp.replace(target)
    return target


def select_shards_for_limit(
    files: list[dict[str, Any]], limit: int
) -> list[tuple[dict[str, Any], int | None]]:
    """Return list of (shard_info, max_rows_from_shard).

    When limit == 0, returns all shards with no per-shard cap.
    When limit > 0, selects evenly spaced shards across the full dataset so all
    benchmarks, harnesses, and models are represented without downloading every
    large shard unnecessarily.
    """
    if limit <= 0:
        return [(f, None) for f in files]

    n = len(files)
    # Each shard has ~45 rows. Pick enough evenly spaced shards across 0..n-1
    # so we cover all benchmarks, harnesses, and models while keeping downloads lean.
    desired_shards = min(n, max(20, math.ceil(limit / 25)))
    if desired_shards >= n:
        chosen = list(range(n))
    else:
        chosen = sorted({round(i * (n - 1) / (desired_shards - 1)) for i in range(desired_shards)})

    base_quota = limit // len(chosen)
    remainder = limit % len(chosen)
    plan: list[tuple[dict[str, Any], int | None]] = []
    for i, idx in enumerate(chosen):
        quota = base_quota + (1 if i < remainder else 0)
        if quota > 0:
            plan.append((files[idx], quota))
    return plan


def pick_rows_evenly(rows: list[dict[str, Any]], quota: int | None) -> list[dict[str, Any]]:
    if quota is None or quota >= len(rows):
        return rows
    if quota <= 0:
        return []
    if quota == 1:
        return [rows[0]]
    n = len(rows)
    indices = [round(i * (n - 1) / (quota - 1)) for i in range(quota)]
    seen: set[int] = set()
    selected: list[dict[str, Any]] = []
    for idx in indices:
        if idx not in seen:
            seen.add(idx)
            selected.append(rows[idx])
    return selected


class SpanBatcher:
    def __init__(
        self,
        client: httpx.Client,
        endpoint: str,
        max_spans: int = 80,
        max_bytes: int = 6 * 1024 * 1024,
    ) -> None:
        self.client = client
        self.endpoint = endpoint
        self.max_spans = max_spans
        self.max_bytes = max_bytes
        self.grouped: dict[tuple[str, str], tuple[dict[str, Any], list[dict[str, Any]]]] = {}
        self.buffered_spans = 0
        self.buffered_bytes = 0
        self.total_spans_sent = 0
        self.total_batches = 0

    def add(
        self, key: tuple[str, str], resource: dict[str, Any], spans: list[dict[str, Any]]
    ) -> None:
        for span in spans:
            span_bytes = len(json.dumps(span, ensure_ascii=False).encode("utf-8"))
            if self.buffered_spans > 0 and (
                self.buffered_spans >= self.max_spans
                or self.buffered_bytes + span_bytes > self.max_bytes
            ):
                self.flush()
            if key not in self.grouped:
                self.grouped[key] = (resource, [])
            self.grouped[key][1].append(span)
            self.buffered_spans += 1
            self.buffered_bytes += span_bytes

    def flush(self) -> None:
        if self.buffered_spans == 0:
            return
        sent = post_otlp_batch(self.client, self.endpoint, self.grouped)
        self.total_spans_sent += sent
        self.total_batches += 1
        self.grouped.clear()
        self.buffered_spans = 0
        self.buffered_bytes = 0


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Import Exgentic/agent-llm-traces into Overmind OTLP."
    )
    parser.add_argument(
        "--endpoint",
        default=DEFAULT_ENDPOINT,
        help=f"OTLP HTTP traces URL (default: {DEFAULT_ENDPOINT})",
    )
    parser.add_argument(
        "--limit",
        type=int,
        default=0,
        help="Maximum traces to import (0 = all 1,781 traces; >0 = stratified sample across shards)",
    )
    parser.add_argument(
        "--batch-size", type=int, default=80, help="Max spans per OTLP HTTP POST (default: 80)"
    )
    parser.add_argument(
        "--max-message-bytes",
        type=int,
        default=262_144,
        help="Max UTF-8 bytes per span gen_ai.*.messages JSON attribute (default: 262144; 0 = unlimited)",
    )
    parser.add_argument(
        "--benchmark", default="", help="Optional benchmark filter (e.g. swebench, appworld)"
    )
    parser.add_argument(
        "--cache-dir", type=Path, default=DEFAULT_CACHE_DIR, help="Local parquet cache directory"
    )
    args = parser.parse_args()

    t0 = time.monotonic()
    now_ns = time.time_ns()

    with httpx.Client() as hf_client, httpx.Client() as otlp_client:
        files = fetch_parquet_manifest(hf_client)
        total_mb = sum(f["size"] for f in files) / (1024 * 1024)
        print(f"Dataset {DATASET_ID}: {len(files)} parquet shards ({total_mb:.1f} MB total)")

        if args.benchmark:
            # When filtering by benchmark, scan all shards until limit is met.
            plan = [(f, None) for f in files]
        else:
            plan = select_shards_for_limit(files, args.limit)

        print(
            f"Selected {len(plan)} shard(s) for import (limit={'all' if args.limit <= 0 else args.limit})"
        )

        batcher = SpanBatcher(otlp_client, args.endpoint, max_spans=max(1, args.batch_size))
        traces_imported = 0
        failed_traces = 0
        service_counts: Counter[str] = Counter()
        harness_counts: Counter[str] = Counter()
        span_type_counts: Counter[str] = Counter()
        model_counts: Counter[str] = Counter()
        sample_trace_ids: dict[str, str] = {}

        for shard_pos, (shard, quota) in enumerate(plan, start=1):
            if args.limit > 0 and traces_imported >= args.limit:
                break

            sz_mb = shard["size"] / (1024 * 1024)
            print(
                f"[{shard_pos}/{len(plan)}] Downloading/reading {shard['filename']} ({sz_mb:.2f} MB)...",
                flush=True,
            )
            local_path = download_shard(hf_client, shard, args.cache_dir)
            rows = pq.read_table(local_path).to_pylist()

            if args.benchmark:
                rows = [r for r in rows if (r.get("benchmark") or "") == args.benchmark]
                if not rows:
                    continue
                if args.limit > 0:
                    remaining = args.limit - traces_imported
                    rows = rows[:remaining]
            else:
                effective_quota = quota
                if args.limit > 0:
                    remaining = args.limit - traces_imported
                    effective_quota = min(quota, remaining) if quota is not None else remaining
                rows = pick_rows_evenly(rows, effective_quota)

            shard_traces = 0
            shard_spans = 0
            for row in rows:
                try:
                    converted = convert_row_to_resource_spans(row, now_ns, args.max_message_bytes)
                    if converted is None:
                        continue
                    key, resource, spans = converted
                    batcher.add(key, resource, spans)
                    traces_imported += 1
                    shard_traces += 1
                    shard_spans += len(spans)
                    svc, harness = key
                    service_counts[svc] += 1
                    harness_counts[harness] += 1
                    if svc not in sample_trace_ids:
                        sample_trace_ids[svc] = spans[0]["traceId"]
                    for sp in spans:
                        for kv in sp["attributes"]:
                            if kv["key"] == "overmind.span.type":
                                span_type_counts[kv["value"]["stringValue"]] += 1
                            elif kv["key"] == "gen_ai.request.model":
                                model_counts[kv["value"]["stringValue"]] += 1
                except Exception as exc:
                    failed_traces += 1
                    print(
                        f"  [error] trace session={row.get('session_id')}: {exc}", file=sys.stderr
                    )

            batcher.flush()
            print(
                f"  -> ingested {shard_traces} traces ({shard_spans} spans); "
                f"cumulative: {traces_imported} traces, {batcher.total_spans_sent} spans in {batcher.total_batches} batches",
                flush=True,
            )

        batcher.flush()

    elapsed = time.monotonic() - t0
    print("\n=== Import Summary ===")
    print(f"Elapsed:        {elapsed:.1f}s")
    print(f"Traces:         {traces_imported} (failed: {failed_traces})")
    print(f"Spans sent:     {batcher.total_spans_sent} across {batcher.total_batches} HTTP batches")
    print(f"Span types:     {dict(span_type_counts)}")
    print(f"Services:       {dict(sorted(service_counts.items()))}")
    print(f"Harnesses:      {dict(sorted(harness_counts.items()))}")
    print(f"Top models:     {dict(model_counts.most_common(10))}")
    print(f"Sample traces:  {dict(sorted(sample_trace_ids.items()))}")


if __name__ == "__main__":
    main()