Skip to content

The platform for continuously improving AI agents.

30.9 KB
Raw Blame
"""Landing: rows arrive verbatim as cell 0, stamped with ``source_row``.

A trace source lands one row per trace, scoped to the selected capability when
present. Ambiguous invocations fail before publication. Landing never triggers scoring.
"""

from __future__ import annotations

import datetime as dt
import json
import logging
import shutil
import tempfile
import time
import uuid
from collections.abc import Callable, Iterable, Iterator
from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Any

import pandas as pd
from django.db import transaction
from django.utils import timezone

from overbae.models import Cell, Dataset
from overbae.models.traces import Span
from overbae.services import otel_collector
from overbae.services.activity import source_ready
from overbae.services.datasets import (
    alignment,
    contract,
    documents,
    files,
    lineage,
    measure,
    operations,
    paths,
    selection,
    spreadsheets,
    store,
)
from overbae.services.datasets.partition import split_rows

logger = logging.getLogger(__name__)


class LandError(ValueError):
    def __init__(self, detail: str, *, code: str = "import_failed") -> None:
        super().__init__(detail)
        self.code = code


SPLIT_POSITIONS = ("head", "tail", "random")


@dataclass
class Landing:
    """A source read once: the rows and how they arrived."""

    rows: Iterable[dict[str, Any]]
    kind: str = "file"
    spec: dict[str, Any] = field(default_factory=dict)
    manifest: list[dict] | None = None
    # The lineage keys each row carries from an earlier version, in row order.
    inherited: Iterable[lineage.Keys] | None = None

    def split(
        self, *, eval_percent: int, position: str, group_by=(), stratify_by=None, deduplicate=True
    ) -> tuple[Landing, Landing]:
        """The train part and the eval part. The eval slice is ``eval_percent`` of
        the rows, at least one and never all, taken from the head, the tail, or a
        fixed-seed random draw; both parts keep the source order."""
        if position not in SPLIT_POSITIONS:
            raise LandError(f"position must be one of {', '.join(SPLIT_POSITIONS)}.")
        try:
            train, evaluation, report = split_rows(
                self.rows,
                eval_percent=eval_percent,
                position=position,
                group_by=group_by,
                stratify_by=stratify_by,
                deduplicate=deduplicate,
            )
        except ValueError as exc:
            raise LandError(str(exc)) from exc
        spec = {**self.spec, "contamination_report": report}
        return replace(self, rows=train, spec=spec), replace(self, rows=evaluation, spec=spec)


def _stamp_source_rows(rows):
    for offset, row in enumerate(rows):
        row = dict(row)
        row[store.SOURCE_ROW] = offset
        yield row


@dataclass
class PreparedLanding:
    dataset_id: Any
    cell_id: uuid.UUID
    path: Path
    dataset_fields: dict[str, Any]
    cell_fields: dict[str, Any]
    sources: list[dict]


def prepare(
    dataset, landing, *, path, state=Dataset.State.IDLE, infer_capability=True, on_progress=None
):
    manifest = landing.manifest
    # Traces stream with no count up front; the counter then has no total.
    total = len(landing.rows) if hasattr(landing.rows, "__len__") else None

    def progress(detail):
        if on_progress:
            on_progress(detail)

    def checked_rows():
        for index, row in enumerate(_stamp_source_rows(landing.rows)):
            if index % 1000 == 0:
                operations.check_cancelled(dataset.id)
                progress({"stage": "writing", "rows_done": index, "rows_total": total})
            yield row

    path.parent.mkdir(parents=True, exist_ok=True)
    started = time.monotonic()
    store.write_rows(path, checked_rows(), manifest)
    written = time.monotonic()
    operations.check_cancelled(dataset.id)
    sources = landing.spec.get("sources", [])
    fields = {
        "source_kind": landing.kind,
        "source_spec": {
            **landing.spec,
            "sources": [
                {key: value for key, value in source.items() if key != "staged_path"}
                for source in sources
            ],
            "landed_at": timezone.now().isoformat(),
        },
        "state": state,
        "error": "",
        "capability_rank": alignment.rank(
            dataset.project_id, pd.DataFrame.from_records(store.head(path, 500))
        ),
    }
    # A dataset a landing splits off by columns is saved only when it publishes.
    measured = Dataset.objects.select_related("capability").filter(pk=dataset.pk).first() or dataset
    if infer_capability and measured.capability_id is None and fields["capability_rank"]:
        best = fields["capability_rank"][0]
        if best["score"] > 0:
            fields["capability_id"] = best["capability_id"]
            measured.capability_id = best["capability_id"]
    source = dataset.cells.filter(position=0).first()
    prepared = PreparedLanding(
        dataset.pk,
        source.pk if source else uuid.uuid4(),
        path,
        fields,
        {
            **measure.describe_frame(
                measured,
                path,
                inherited=landing.inherited,
                on_progress=lambda done: progress(
                    {"stage": "measuring", "rows_done": done, "rows_total": total}
                ),
            ),
            "input_fingerprint": "",
            "seconds": 0.0,
        },
        sources,
    )
    logger.info(
        "Landing measured",
        extra={
            "dataset": str(dataset.pk),
            "rows": prepared.cell_fields["rows"],
            "write_seconds": round(written - started, 3),
            "measure_seconds": round(time.monotonic() - written, 3),
        },
    )
    return prepared


@transaction.atomic
def publish(dataset, prepared, *, user=None):
    if prepared.dataset_id != dataset.pk:
        raise LandError("The prepared source belongs to another dataset.")
    locked = Dataset.objects.select_for_update().get(pk=dataset.pk)
    operations.check_cancelled(locked.pk)
    source = locked.cells.filter(position=0).first()
    if source is not None and source.pk != prepared.cell_id:
        raise LandError("The source changed before publication.")
    for artifact in prepared.sources:
        if artifact.get("staged_path"):
            destination = paths.source_path(locked.pk, artifact["id"])
            destination.parent.mkdir(parents=True, exist_ok=True)
            shutil.copyfile(artifact["staged_path"], destination)
    destination = paths.cell_path(locked.pk, prepared.cell_id)
    destination.parent.mkdir(parents=True, exist_ok=True)
    prepared.path.replace(destination)
    lineage.keys_path(prepared.path).replace(lineage.keys_path(destination))
    if source is None:
        Cell.objects.create(
            id=prepared.cell_id,
            dataset=locked,
            position=0,
            title="Source",
            created_by=user if getattr(user, "pk", None) else None,
            **prepared.cell_fields,
        )
    else:
        Cell.objects.filter(pk=source.pk).update(**prepared.cell_fields)
    Dataset.objects.filter(pk=locked.pk).update(
        **prepared.dataset_fields, updated_at=timezone.now()
    )
    dataset.refresh_from_db()
    return dataset


def commit(dataset, landing, *, user=None, state=Dataset.State.IDLE, infer_capability=True):
    parent = paths.dataset_dir(dataset.pk)
    parent.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(prefix="source-", dir=parent) as directory:
        prepared = prepare(
            dataset,
            landing,
            path=Path(directory) / "source.parquet",
            state=state,
            infer_capability=infer_capability,
        )
        with transaction.atomic():
            dataset = publish(dataset, prepared, user=user)
            if not {"derived_from", "partition_plan"} & landing.spec.keys():
                source_ready(dataset, prepared.cell_id, user)
    return dataset


def read_file(path: Path, **options) -> list[Landing]:
    """The file's rows, one landing per sheet of a workbook, else one."""
    return [_require_rows(group) for group in _group(_read_one(path, **options))]


def single(groups: list[Landing]) -> Landing:
    """The one column set a split or an added batch needs."""
    if len(groups) > 1:
        raise LandError(
            f"These files hold {len(groups)} different sets of columns. "
            "Add files that share one set of columns."
        )
    return groups[0]


def _require_rows(landing: Landing) -> Landing:
    # A document without text lands as an empty, recorded part of a batch; a source with
    # no rows at all is still an upload mistake.
    if not len(landing.rows):
        reasons = [
            source["extraction"]["limitations"][-1]
            for source in landing.spec["sources"]
            if source["extraction"].get("status") == "no_text"
        ]
        raise LandError(reasons[0] if reasons else "The file has no rows.")
    return landing


def _read_one(
    path: Path,
    *,
    filename: str,
    on_progress: Callable[[dict], None] | None = None,
    json_rows_field: str | None = None,
    options: dict | None = None,
    project_id=None,
    ocr_languages=None,
) -> list[Landing]:
    """The file's rows: one part per sheet of a workbook, else one part."""
    spool = None

    def progress(detail):
        if on_progress:
            on_progress({"filename": filename, **detail})

    progress(
        {"stage": "extracting" if filename.lower().endswith(documents.SUFFIXES) else "reading"}
    )
    try:
        if filename.lower().endswith(documents.SUFFIXES):
            extracted, extraction = documents.extract(
                path,
                filename=filename,
                on_progress=progress,
                project_id=project_id,
                ocr_languages=ocr_languages,
            )
            spool = tempfile.TemporaryDirectory(prefix="overmind-document-")
            cached = Path(spool.name) / "extracted.jsonl"
            with cached.open("w") as output:
                for row in extracted:
                    output.write(json.dumps(row) + "\n")
            parts = [(files.FileRows(cached, filename="extracted.jsonl"), extraction)]
        elif filename.lower().endswith(".xlsx"):
            chosen = (options or {}).get("sheet")
            parts = [
                (
                    files.FileRows(path, filename=filename, sheet=sheet, options=options),
                    {"sheet": sheet, **({"read_options": options} if options else {})},
                )
                for sheet in ([chosen] if chosen else spreadsheets.sheets(path))
            ]
        else:
            rows = files.FileRows(
                path, filename=filename, json_rows_field=json_rows_field, options=options
            )
            extraction = (
                {"json_rows_field": json_rows_field, "selection": "explicit"}
                if json_rows_field
                else {}
            )
            if options:
                extraction["read_options"] = options
            parts = [(rows, extraction)]
    except (files.FileError, documents.DocumentError, spreadsheets.SpreadsheetError) as exc:
        progress({"stage": "failed"})
        raise LandError(str(exc), code=getattr(exc, "code", "import_failed")) from exc
    if not any(len(rows) for rows, _ in parts) and not any(
        extraction.get("status") == "no_text" for _, extraction in parts
    ):
        raise LandError("The file has no rows.")
    identity = store.file_sha256(path)
    size = files.stored_stat(path).st_size
    return [
        Landing(
            SourceRows(rows, spool),
            spec={
                "filename": filename,
                "sources": [
                    {
                        "id": identity,
                        "sha256": identity,
                        "filename": filename,
                        "bytes": size,
                        "rows": len(rows),
                        "extraction": extraction,
                        "staged_path": str(path),
                    }
                ],
            },
        )
        for rows, extraction in parts
    ]


@dataclass
class SourceRows:
    """A file's rows, and the extraction spool they are read from while the landing runs."""

    source: files.FileRows
    spool: tempfile.TemporaryDirectory | None = field(default=None, repr=False)

    def __len__(self):
        return len(self.source)

    def __iter__(self):
        return iter(self.source)

    @property
    def columns(self) -> frozenset[str]:
        return frozenset(name.lower() for name in self.source.names.values())


@dataclass
class UploadRows:
    sources: list[SourceRows]

    def __len__(self):
        return sum(len(source) for source in self.sources)

    def __iter__(self):
        for source in self.sources:
            yield from source


def _group(parts: list[Landing]) -> list[Landing]:
    """Parts with the same column names land together, in the order they came; each sheet
    of a workbook lands alone. Names compare as the store does, ignoring case; types do not
    split a group, so a column of integers in one file and decimals in another stays one. A
    document with no text has no columns: its source is recorded with the first group."""
    groups: dict[Any, list[Landing]] = {}
    empty = []
    for index, part in enumerate(parts):
        if not len(part.rows):
            empty.append(part)
            continue
        sheet = part.spec["sources"][0]["extraction"].get("sheet")
        key = ("sheet", index) if sheet is not None else part.rows.columns
        groups.setdefault(key, []).append(part)
    if empty:
        first = next(iter(groups.values()), None)
        if first is None:
            groups[None] = empty
        else:
            first.extend(empty)
    landings = []
    for members in groups.values():
        # The store matches names ignoring case: a later file writes the first file's spelling.
        spelling = {}
        for part in members:
            names = part.rows.source.names
            for name in names.values():
                spelling.setdefault(name.lower(), name)
            part.rows.source.names = {raw: spelling[name.lower()] for raw, name in names.items()}
        sources = [source for part in members for source in part.spec["sources"]]
        landings.append(
            Landing(
                UploadRows([part.rows for part in members]),
                spec={
                    "sources": sources,
                    "files": [
                        {
                            **{k: item[k] for k in ("filename", "bytes", "rows")},
                            **(
                                {"sheet": item["extraction"]["sheet"]}
                                if "sheet" in item["extraction"]
                                else {}
                            ),
                        }
                        for item in sources
                    ],
                },
            )
        )
    return landings


def read_uploads(
    upload_ids: list[str],
    *,
    on_progress: Callable[[dict], None] | None = None,
    project_id=None,
    ocr_languages=None,
) -> list[Landing]:
    """The uploads' rows, one landing per set of columns (``_group``)."""
    parts = []
    for index, upload_id in enumerate(upload_ids):
        filename = files.upload_filename(upload_id)
        path = files.upload_data_path(upload_id)
        if not filename or not path.exists():
            raise LandError("An upload has expired. Start it again.")

        def progress(detail, index=index):
            if on_progress:
                on_progress({"completed": index, "total": len(upload_ids), **detail})

        inspected = files.inspection(upload_id) or {}
        parts.extend(
            _read_one(
                path,
                filename=filename,
                on_progress=progress,
                project_id=project_id,
                ocr_languages=ocr_languages,
                json_rows_field=inspected.get("json_rows_field"),
                options=inspected.get("options"),
            )
        )
    if on_progress:
        on_progress({"completed": len(upload_ids), "total": len(upload_ids), "stage": "merging"})
    return [_require_rows(group) for group in _group(parts)]


def read_rows(rows: list[dict[str, Any]], *, spec: dict[str, Any] | None = None) -> Landing:
    rows = [dict(r) if isinstance(r, dict) else {"value": r} for r in rows]
    for row in rows:
        row.pop(store.SOURCE_ROW, None)
    return Landing(rows, kind=Dataset.SourceKind.FILE, spec=spec or {})


def land_rows(
    dataset: Dataset,
    rows: list[dict[str, Any]],
    *,
    spec: dict[str, Any] | None = None,
    user: Any = None,
) -> Dataset:
    return commit(dataset, read_rows(rows, spec=spec), user=user)


TRACE_CHUNK = 200

TRACE_MANIFEST = [
    {"name": "source_row", "type": "integer"},
    {"name": "trace_id", "type": "string"},
    {"name": "conversation_id", "type": "string"},
    {"name": "capability_id", "type": "string"},
    {"name": "capability", "type": "string"},
    {"name": "started_at", "type": "datetime"},
    {"name": "duration_ms", "type": "integer"},
    {"name": "status", "type": "string"},
    {"name": "error", "type": "string"},
    {"name": "model", "type": "string"},
    {"name": "prompt_tokens", "type": "integer"},
    {"name": "completion_tokens", "type": "integer"},
    {"name": "cost_usd", "type": "number"},
    {"name": "input", "type": "json"},
    {"name": "output", "type": "json"},
    {"name": "messages", "type": "json"},
    {"name": "tools", "type": "json"},
    {"name": "score", "type": "number"},
]

STATUS_ERROR = 2


def _ns_to_dt(ns: int | None) -> dt.datetime | None:
    if not ns:
        return None
    return dt.datetime.fromtimestamp(ns / 1e9, tz=dt.UTC)


def _attr(span: Span, key: str) -> Any:
    return (span.attributes or {}).get(key)


def _root(spans: list[Span]) -> Span:
    for span in spans:
        if span.parent_span_id is None:
            return span
    ids = {span.span_id for span in spans}
    roots = [span for span in spans if span.parent_span_id not in ids]
    if len(roots) == 1:
        return roots[0]
    return max(spans, key=lambda s: s.duration_ns or 0)


def _delivered(spans: list[Span]) -> Any:
    from overbae.services.transcripts import chatml

    for span in sorted(spans, key=lambda s: s.start_time_ns or 0, reverse=True):
        if str(_attr(span, "overmind.delivery")).lower() == "true":
            return chatml.maybe_parse_json(chatml.pick(span.attributes or {}, chatml.OUTPUT_KEYS))
    return None


def _reported(spans: list[Span], keys: tuple[str, ...]) -> float | None:
    """Summed over the spans that report it; ``None`` when none does, never zero."""
    total = None
    for span in spans:
        usage = span.usage or {}
        for key in keys:
            try:
                value = float(usage[key])
            except (KeyError, TypeError, ValueError):
                continue
            total = (total or 0.0) + value
            break
    return total


def _usage(spans: list[Span]) -> dict[str, Any]:
    """Summed over the trace from ``Span.usage``, which keeps the attribute names
    as sent (``genai.prompt_tokens``, ``gen_ai.usage.input_tokens``, ...)."""
    from overbae.services.transcripts import chatml

    prompt = _reported(spans, chatml.PROMPT_TOKEN_KEYS)
    completion = _reported(spans, chatml.COMPLETION_TOKEN_KEYS)
    cost = _reported(spans, chatml.COST_KEYS)
    models: list[str] = []
    for span in spans:
        usage = span.usage or {}
        model = next((usage.get(k) for k in chatml.MODEL_KEYS if usage.get(k)), None)
        if model and str(model) not in models:
            models.append(str(model))
    return {
        "prompt_tokens": None if prompt is None else int(prompt),
        "completion_tokens": None if completion is None else int(completion),
        "cost_usd": None if cost is None else round(cost, 6),
        "model": models[-1] if models else None,
    }


def _error(root: Span, spans: list[Span]) -> str | None:
    """The root's error first, else the earliest failed span's."""
    for span in (root, *spans):
        if span.status_code != STATUS_ERROR:
            continue
        text = _attr(span, "overmind.error.type") or span.status_message
        if text:
            return str(text)
    return None


_CONVERSATION_KEYS = ("conversation.id", "overmind.conversation.id", "gen_ai.conversation.id")


def _conversation_id(root: Span, spans: list[Span]) -> str | None:
    for span in (root, *spans):
        if span.conversation_id:
            return span.conversation.external_id or None
    for span in (root, *spans):
        attrs = span.attributes or {}
        res_attrs = span.resource_attrs or {}
        for key in _CONVERSATION_KEYS:
            value = attrs.get(key) or res_attrs.get(key)
            if value:
                return str(value)
    return None


def trace_row(
    spans: list[Span], *, score: float | None, capability_id: str | None = None
) -> dict[str, Any]:
    """``spans`` is one whole trace or selected invocation in start order."""
    from overbae.services.transcripts import chatml, normalizer

    root = _root(spans)
    trajectory = normalizer.reconstruct_spans(spans, promote_harness=True)
    # The OpenAI wire shape, so a product that keeps `messages` as-is already
    # satisfies the train contract.
    messages = chatml.openai_wire_messages(trajectory.get("messages") or [])
    tools = chatml.openai_wire_tools(trajectory.get("tool_definitions") or [])
    raw_in, raw_out = normalizer.capability_io(spans)
    delivered = _delivered(spans)
    usage = _usage(spans)
    capabilities = {s.capability_id: s.capability for s in spans if s.capability_id}
    capability = (
        root.capability
        if capability_id and str(root.capability_id) == capability_id
        else next(iter(capabilities.values()))
        if len(capabilities) == 1
        else None
    )
    conversation = _conversation_id(root, spans)
    failed = any(s.status_code == STATUS_ERROR for s in spans)
    return {
        "trace_id": root.trace_id,
        "conversation_id": conversation or None,
        "capability_id": str(capability.id) if capability is not None else None,
        "capability": capability.name if capability is not None else None,
        "started_at": _ns_to_dt(min(s.start_time_ns or 0 for s in spans) or None),
        "duration_ms": int((root.duration_ns or 0) / 1e6),
        "status": "error" if failed else "ok",
        "error": _error(root, spans),
        "model": usage["model"],
        "prompt_tokens": usage["prompt_tokens"],
        "completion_tokens": usage["completion_tokens"],
        "cost_usd": usage["cost_usd"],
        "input": raw_in,
        "output": delivered if delivered is not None else raw_out,
        "messages": messages or None,
        "tools": tools or None,
        "score": score,
    }


def _chunks(items: Iterable[str], size: int) -> Iterator[list[str]]:
    batch: list[str] = []
    for item in items:
        batch.append(item)
        if len(batch) >= size:
            yield batch
            batch = []
    if batch:
        yield batch


def _score(spans: list[Span]) -> float | None:
    # Scoped imports use their invocation root, never a sibling or enclosing trace score.
    attrs = _root(spans).eval_attributes or {}
    return (attrs.get("trajectory") or {}).get("score", attrs.get("score"))


def _ancestors(spans: list[Span], unit: Span) -> list[Span]:
    by_id = {span.span_id: span for span in spans}
    seen = {unit.span_id}
    chain = []
    cursor = by_id.get(unit.parent_span_id or "")
    while cursor is not None and cursor.span_id not in seen:
        seen.add(cursor.span_id)
        chain.append(cursor)
        cursor = by_id.get(cursor.parent_span_id or "")
    return chain


def _preferred_spans(spans: list[Span], capability_id: str | None) -> list[Span]:
    if not capability_id:
        return spans
    matches = [s for s in spans if str(s.capability_id) == capability_id]
    if not matches:
        return spans
    roots = [
        s
        for s in matches
        if not any(str(a.capability_id) == capability_id for a in _ancestors(spans, s))
    ]
    if len(roots) != 1:
        raise LandError(
            f"Trace {spans[0].trace_id} has {len(roots)} separate invocations of the selected "
            "capability. Select LLM calls or import explicit invocation rows."
        )
    return sorted(
        [s for s in spans if s == roots[0] or roots[0] in _ancestors(spans, s)],
        key=lambda s: s.start_time_ns or 0,
    )


def _spans_by_trace(project_id: Any, chunk: list[str]) -> dict[str, list[Span]]:
    by_trace: dict[str, list[Span]] = {}
    remaining = chunk
    if otel_collector.enabled():
        try:
            by_trace = otel_collector.fetch_traces(project_id, chunk)
        except otel_collector.CollectorError as exc:
            raise LandError(str(exc)) from exc
        remaining = [tid for tid in chunk if tid not in by_trace]
    if remaining:
        spans = (
            Span.objects.filter(project_id=project_id, trace_id__in=remaining)
            .select_related("capability", "conversation")
            .order_by("start_time_ns")
        )
        for span in spans:
            by_trace.setdefault(span.trace_id, []).append(span)
    return by_trace


def iter_trace_rows(
    project_id: Any,
    trace_ids: Iterable[str],
    *,
    on_progress: Any = None,
    preferred_capability_id: str | None = None,
) -> Iterator[dict[str, Any]]:
    """One query per chunk of traces, then pure assembly; a trace whose spans
    are gone is skipped."""
    done = 0
    for chunk in _chunks(trace_ids, TRACE_CHUNK):
        by_trace = _spans_by_trace(project_id, chunk)
        for trace_id in chunk:
            trace_spans = by_trace.get(trace_id)
            if not trace_spans:
                continue
            scoped = _preferred_spans(trace_spans, preferred_capability_id)
            score = _score(scoped)
            try:
                row = trace_row(scoped, score=score, capability_id=preferred_capability_id)
            except Exception:  # noqa: BLE001 — one unreadable trace must not sink the batch
                logger.warning("trace %s did not land", trace_id, exc_info=True)
                continue
            yield bounded_row(row)
        done += len(chunk)
        if on_progress:
            on_progress(done)


def read_traces(project_id: Any, spec: dict[str, Any], *, on_progress: Any = None) -> Landing:
    """One row per trace, in selection order. ``spec`` is a ``TraceSource`` payload."""
    try:
        source = selection.TraceSource.parse(spec)
        rows = list(
            iter_trace_rows(
                project_id,
                source.iter_trace_ids(project_id),
                on_progress=on_progress,
                preferred_capability_id=source.preferred_capability_id,
            )
        )
    except selection.TraceSourceError as exc:
        raise LandError(str(exc)) from exc
    if not rows:
        raise LandError("No traces matched. Widen the selection or check the project.")
    return Landing(
        rows, kind=Dataset.SourceKind.TRACES, spec=source.spec(), manifest=list(TRACE_MANIFEST)
    )


def land_traces(
    dataset: Dataset,
    spec: dict[str, Any],
    *,
    user: Any = None,
    on_progress: Any = None,
) -> Dataset:
    from overbae.services.datasets.dispatch import _trace_preference

    spec = _trace_preference({"traces": spec}, dataset.capability_id)["traces"]
    return commit(
        dataset, read_traces(dataset.project_id, spec, on_progress=on_progress), user=user
    )


# A tool call whose arguments carry a serialised agent state can weigh hundreds of
# megabytes; a row cell keeps a preview of anything past this and notes the cut.
MAX_CELL_CHARS = 200_000
_PREVIEW_CHARS = 4_000


def _json_prefix(value: Any, limit: int) -> tuple[str, bool]:
    """Up to ``limit`` chars of ``value``'s JSON and whether more followed. The
    streaming encoder stops early, so a huge blob costs ``limit`` work, not its size."""
    chunks: list[str] = []
    total = 0
    for chunk in json.JSONEncoder(default=str).iterencode(value):
        chunks.append(chunk)
        total += len(chunk)
        if total > limit:
            return "".join(chunks)[:limit], True
    return "".join(chunks), False


def _marker(preview: str) -> dict[str, Any]:
    return {contract.CUT_KEY: True, "preview": preview[:_PREVIEW_CHARS]}


def bounded(value: Any, limit: int = MAX_CELL_CHARS, *, depth: int = 0) -> Any:
    """``value`` if its JSON fits ``limit``; otherwise strings are cut and oversized
    members are shrunk in turn, three levels deep, after which a preview marker
    stands in."""
    if value is None or isinstance(value, (bool, int, float)):
        return value
    if isinstance(value, str):
        return value if len(value) <= limit else value[:limit] + f"…[+{len(value) - limit} chars]"
    text, more = _json_prefix(value, limit)
    if not more:
        return value
    if depth >= 3 or not isinstance(value, (list, dict)):
        return _marker(text)
    if isinstance(value, list):
        per = max(limit // max(len(value), 1), _PREVIEW_CHARS)
        return [bounded(item, per, depth=depth + 1) for item in value]
    per = max(limit // max(len(value), 1), _PREVIEW_CHARS)
    return {key: bounded(item, per, depth=depth + 1) for key, item in value.items()}


def _bounded_tool_call(call: Any, limit: int) -> Any:
    """A wire tool call keeps its shape; only ``function.arguments`` is cut, and the
    cut stays a JSON string so the row still validates."""
    fn = call.get("function") if isinstance(call, dict) else None
    if not isinstance(fn, dict):
        return bounded(call, limit)
    args = fn.get("arguments")
    if isinstance(args, str) and len(args) > limit:
        clipped = json.dumps({contract.CUT_KEY: True, "preview": args[:_PREVIEW_CHARS]})
        return {**call, "function": {**fn, "arguments": clipped}}
    return call


def bounded_messages(messages: Any, limit: int = MAX_CELL_CHARS) -> Any:
    """Per-message bound: keeps every turn's role and shape, cuts only the payloads."""
    if not isinstance(messages, list):
        return bounded(messages, limit)
    out = []
    for message in messages:
        if not isinstance(message, dict):
            out.append(bounded(message, limit))
            continue
        clipped = dict(message)
        calls = clipped.get("tool_calls")
        if isinstance(calls, list) and calls:
            per = max(limit // len(calls), _PREVIEW_CHARS)
            clipped["tool_calls"] = [_bounded_tool_call(c, per) for c in calls]
        for key in ("content", "result", "arguments"):
            if key in clipped:
                clipped[key] = bounded(clipped[key], limit)
        out.append(clipped)
    return out


def bounded_row(row: dict[str, Any]) -> dict[str, Any]:
    for key, value in row.items():
        if key == "messages":
            row[key] = bounded_messages(value)
        elif (
            isinstance(value, (dict, list))
            or isinstance(value, str)
            and len(value) > MAX_CELL_CHARS
        ):
            row[key] = bounded(value)
    return row