# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-span-attribute-cardinality-explosion-from-silently-truncating-tool-call-lineage-in-agent-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-span-attribute-cardinality-explosion-from-silently-truncating-tool-call-lineage-in-agent-traces.warrant.json
# Markdown SHA-256:   bb248a7bead864d2e5b65a5f57a7d3bcd76cc26857bcee6b962b1a7e1df4ed9d
# Code AST SHA-256:   20eb44da196d274d2fe3f3515c7ab51df66d657d8b0f5732bfb2ae7ac997e255
# Verified Classes:   LineageTruncationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import json
from typing import Any


class LineageTruncationError(RuntimeError):
    """Raised when a lineage attribute would be exported without a completeness marker."""
    pass


def encode_lineage(
    entries: list[dict[str, Any]],
    byte_limit: int,
    *,
    allow_truncation: bool = True,
) -> tuple[str, dict[str, Any]]:
    """
    Serialize tool-call lineage into a single attribute value that is safe to export.

    Invariants enforced:
      - entry-atomicity: the returned JSON is a prefix of whole entries, never a
        partial object.
      - completeness self-description: the accompanying attribute dict always
        states whether the lineage is complete and, if not, how many entries were
        omitted.

    Returns (serialized_value, extra_attributes).
    """
    if byte_limit <= 0:
        raise LineageTruncationError(f"invalid byte_limit={byte_limit}")

    full = json.dumps(entries, separators=(",", ":"))
    if len(full.encode("utf-8")) <= byte_limit:
        return full, {
            "gen_ai.tool.call.lineage.complete": True,
            "gen_ai.tool.call.lineage.omitted": 0,
        }

    if not allow_truncation:
        raise LineageTruncationError(
            f"lineage of {len(entries)} entries exceeds {byte_limit} bytes "
            f"and truncation is disallowed"
        )

    # Greedily keep the longest prefix of whole entries that fits.
    kept: list[dict[str, Any]] = []
    for entry in entries:
        candidate = kept + [entry]
        encoded = json.dumps(candidate, separators=(",", ":"))
        if len(encoded.encode("utf-8")) > byte_limit:
            break
        kept = candidate

    if not kept:
        # Even one entry does not fit: refuse to emit a misleading empty list.
        raise LineageTruncationError(
            f"no single lineage entry fits within {byte_limit} bytes; "
            f"drop the attribute and reconstruct from the span tree"
        )

    omitted = len(entries) - len(kept)
    value = json.dumps(kept, separators=(",", ":"))
    return value, {
        "gen_ai.tool.call.lineage.complete": False,
        "gen_ai.tool.call.lineage.omitted": omitted,
    }
