|
| 1 | +"""Data-source reference capture for lineage: tools declare which sources they |
| 2 | +touch and the refs land in span data under the ``sgp.lineage.refs`` key.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import re |
| 7 | +import json |
| 8 | +from typing import Any, Literal, Callable, Iterable |
| 9 | + |
| 10 | +from pydantic import Field, BaseModel, field_validator |
| 11 | + |
| 12 | +try: |
| 13 | + from agentex.lib.utils.logging import make_logger |
| 14 | + |
| 15 | + logger = make_logger(__name__) |
| 16 | +except Exception: # ddtrace may be absent in some envs; fall back to stdlib |
| 17 | + import logging |
| 18 | + |
| 19 | + logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | +LINEAGE_REFS_KEY = "sgp.lineage.refs" |
| 22 | + |
| 23 | +_URI_NAMESPACE_RE = re.compile(r"^[a-z][a-z0-9+.-]*://.+$") |
| 24 | + |
| 25 | +RefResolver = Callable[[dict[str, Any]], "list[DataSourceRef]"] |
| 26 | + |
| 27 | + |
| 28 | +class DataSourceRef(BaseModel): |
| 29 | + """One data source a tool call touched, as a lineage coordinate.""" |
| 30 | + |
| 31 | + namespace: str = Field(max_length=512) |
| 32 | + name: str = Field(min_length=1, max_length=512) |
| 33 | + version: str | None = Field(default=None, max_length=256) |
| 34 | + role: Literal["input", "output"] = "input" |
| 35 | + |
| 36 | + def __init__(self, namespace: str | None = None, name: str | None = None, **kwargs: Any) -> None: |
| 37 | + if namespace is not None: |
| 38 | + kwargs["namespace"] = namespace |
| 39 | + if name is not None: |
| 40 | + kwargs["name"] = name |
| 41 | + super().__init__(**kwargs) |
| 42 | + |
| 43 | + @field_validator("namespace") |
| 44 | + @classmethod |
| 45 | + def _namespace_is_uri_form(cls, value: str) -> str: |
| 46 | + if not _URI_NAMESPACE_RE.match(value): |
| 47 | + raise ValueError(f"namespace must be URI-form (scheme://system), got: {value!r}") |
| 48 | + return value |
| 49 | + |
| 50 | + |
| 51 | +class _ToolSources(BaseModel): |
| 52 | + refs: list[DataSourceRef] = Field(default_factory=list) |
| 53 | + resolver: RefResolver | None = None |
| 54 | + |
| 55 | + model_config = {"arbitrary_types_allowed": True} |
| 56 | + |
| 57 | + |
| 58 | +_tool_sources: dict[str, _ToolSources] = {} |
| 59 | + |
| 60 | + |
| 61 | +def register_tool_sources( |
| 62 | + tool_name: str, |
| 63 | + refs: Iterable[DataSourceRef] | None = None, |
| 64 | + resolver: RefResolver | None = None, |
| 65 | +) -> None: |
| 66 | + """Declare the data sources a tool touches, keyed by its tool name. |
| 67 | +
|
| 68 | + Use for tools the agent does not own (e.g. MCP proxy tools). Static refs and |
| 69 | + a resolver over the tool's parsed arguments may be combined; repeated |
| 70 | + registration for the same name replaces the prior entry. |
| 71 | + """ |
| 72 | + _tool_sources[tool_name] = _ToolSources(refs=list(refs or []), resolver=resolver) |
| 73 | + |
| 74 | + |
| 75 | +def data_sources(*refs: DataSourceRef, resolver: RefResolver | None = None) -> Callable[[Any], Any]: |
| 76 | + """Decorator form of ``register_tool_sources`` for tools the agent owns. |
| 77 | +
|
| 78 | + Works below or above ``@function_tool``: the tool name is taken from the |
| 79 | + decorated object's ``name`` attribute when present, else ``__name__``. |
| 80 | + """ |
| 81 | + |
| 82 | + def _register(obj: Any) -> Any: |
| 83 | + tool_name = getattr(obj, "name", None) or getattr(obj, "__name__", None) |
| 84 | + if isinstance(tool_name, str) and tool_name: |
| 85 | + register_tool_sources(tool_name, refs=refs, resolver=resolver) |
| 86 | + else: |
| 87 | + logger.warning("data_sources could not determine a tool name for %r; refs not registered", obj) |
| 88 | + return obj |
| 89 | + |
| 90 | + return _register |
| 91 | + |
| 92 | + |
| 93 | +def clear_tool_sources() -> None: |
| 94 | + """Reset the registry (test isolation).""" |
| 95 | + _tool_sources.clear() |
| 96 | + |
| 97 | + |
| 98 | +def resolve_refs(tool_name: str, arguments: dict[str, Any] | None) -> list[dict[str, Any]]: |
| 99 | + """Resolve registered refs for one tool call to serialized, deduplicated dicts. |
| 100 | +
|
| 101 | + Resolver failures are logged and swallowed: ref capture must never break a |
| 102 | + tool call or its tracing. |
| 103 | + """ |
| 104 | + entry = _tool_sources.get(tool_name) |
| 105 | + if entry is None: |
| 106 | + return [] |
| 107 | + refs = list(entry.refs) |
| 108 | + if entry.resolver is not None: |
| 109 | + try: |
| 110 | + refs.extend(entry.resolver(arguments or {})) |
| 111 | + except Exception: |
| 112 | + logger.warning("data-source resolver for tool %s failed; static refs kept", tool_name, exc_info=True) |
| 113 | + return _dedupe(refs) |
| 114 | + |
| 115 | + |
| 116 | +def resolve_refs_from_items(items: Iterable[Any]) -> list[dict[str, Any]]: |
| 117 | + """Resolve refs across serialized run items, matching ``function_call`` entries. |
| 118 | +
|
| 119 | + Accepts the item dicts the providers already build for span output; string |
| 120 | + ``arguments`` are parsed as JSON for resolver-based registrations. |
| 121 | + """ |
| 122 | + refs: list[dict[str, Any]] = [] |
| 123 | + for item in items: |
| 124 | + if not isinstance(item, dict) or item.get("type") != "function_call": |
| 125 | + continue |
| 126 | + tool_name = item.get("name") |
| 127 | + if not isinstance(tool_name, str) or not tool_name: |
| 128 | + continue |
| 129 | + arguments = item.get("arguments") |
| 130 | + if isinstance(arguments, str): |
| 131 | + try: |
| 132 | + arguments = json.loads(arguments) |
| 133 | + except (ValueError, TypeError): |
| 134 | + arguments = {} |
| 135 | + refs.extend(resolve_refs(tool_name, arguments if isinstance(arguments, dict) else {})) |
| 136 | + return _dedupe_dicts(refs) |
| 137 | + |
| 138 | + |
| 139 | +def record(span: Any, refs: Iterable[DataSourceRef]) -> None: |
| 140 | + """Attach refs to a manually managed span (no-op when the span is None).""" |
| 141 | + if span is None: |
| 142 | + return |
| 143 | + merged = merge_refs_into_data(getattr(span, "data", None), _dedupe(list(refs))) |
| 144 | + span.data = merged |
| 145 | + |
| 146 | + |
| 147 | +def merge_refs_into_data(data: dict[str, Any] | None, refs: list[dict[str, Any]]) -> dict[str, Any]: |
| 148 | + """Merge serialized refs into a span data dict, deduplicating with any present.""" |
| 149 | + out = dict(data) if isinstance(data, dict) else {} |
| 150 | + if refs: |
| 151 | + existing = out.get(LINEAGE_REFS_KEY) |
| 152 | + combined = list(existing) if isinstance(existing, list) else [] |
| 153 | + combined.extend(refs) |
| 154 | + out[LINEAGE_REFS_KEY] = _dedupe_dicts(combined) |
| 155 | + return out |
| 156 | + |
| 157 | + |
| 158 | +def _dedupe(refs: list[DataSourceRef]) -> list[dict[str, Any]]: |
| 159 | + return _dedupe_dicts([ref.model_dump(exclude_none=True) for ref in refs]) |
| 160 | + |
| 161 | + |
| 162 | +def _dedupe_dicts(refs: list[dict[str, Any]]) -> list[dict[str, Any]]: |
| 163 | + seen: set[tuple[Any, ...]] = set() |
| 164 | + out: list[dict[str, Any]] = [] |
| 165 | + for ref in refs: |
| 166 | + key = (ref.get("namespace"), ref.get("name"), ref.get("version"), ref.get("role")) |
| 167 | + if key not in seen: |
| 168 | + seen.add(key) |
| 169 | + out.append(ref) |
| 170 | + return out |
0 commit comments