"""OTLP file interoperability and native SDK/REST execution lifecycle."""
import asyncio
import base64
import copy
import json
import re
from dataclasses import replace
from datetime import datetime, timedelta
from uuid import UUID
import langsmith as ls
import pytest
from conftest import ScriptedModel, call
from google.protobuf.json_format import ParseDict
from langchain_core.messages import AIMessage
from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest
from test_api import client_for, query, sse, terminal
from dataagent import create_agent
from dataagent.extensions.tracing import LocalLangChainTracer
from dataagent.lowlevel import build_graph
@pytest.fixture(autouse=True)
def no_trace_network(monkeypatch):
"""Block accidental remote tracing; allow local OTLP /v1/traces for live-export tests."""
import requests
attempts = []
original = requests.sessions.Session.request
def blocked(self, method, url, *args, **kwargs):
if "/v1/traces" in str(url):
return original(self, method, url, *args, **kwargs)
attempts.append(((self, method, url), kwargs))
raise AssertionError("Trace must not make HTTP requests")
monkeypatch.setattr("requests.sessions.Session.request", blocked)
yield
assert not attempts
def spans(data):
return [
span
for resource in data["resourceSpans"]
for scope in resource["scopeSpans"]
for span in scope["spans"]
]
def attributes(span):
return {item["key"]: next(iter(item["value"].values())) for item in span.get("attributes", [])}
def root(data):
(result,) = [span for span in spans(data) if not span.get("parentSpanId")]
return result
def validate_file(path):
data = json.loads(path.read_text())
assert set(data) == {"resourceSpans"}
records = spans(data)
ids = {span["spanId"] for span in records}
assert len(ids) == len(records)
assert path.stat().st_mode & 0o777 == 0o600
assert {span["traceId"] for span in records} == {UUID(path.stem).hex}
for span in records:
assert re.fullmatch("[0-9a-f]{32}", span["traceId"])
assert re.fullmatch("[0-9a-f]{16}", span["spanId"])
assert int(span["endTimeUnixNano"]) >= int(span["startTimeUnixNano"]) > 0
assert not span.get("parentSpanId") or span["parentSpanId"] in ids
root(data)
by_id = {span["spanId"]: span for span in records}
for span in records:
visited = set()
while span.get("parentSpanId"):
assert span["spanId"] not in visited
visited.add(span["spanId"])
span = by_id[span["parentSpanId"]]
protobuf_json = copy.deepcopy(data)
for span in spans(protobuf_json):
for record in (span, *span.get("links", [])):
for key in ("traceId", "spanId", "parentSpanId"):
if record.get(key):
record[key] = base64.b64encode(bytes.fromhex(record[key])).decode()
parsed = ParseDict(protobuf_json, ExportTraceServiceRequest())
assert parsed.resource_spans
return data
def read_trace(runtime, body):
matches = []
for path in runtime.paths.for_session(body["threadId"]).traces.glob("*.json"):
data = validate_file(path)
if attributes(root(data)).get("langsmith.metadata.dataagent_root_run_id") == body["runId"]:
matches.append(data)
assert len(matches) == 1
return matches[0]
def assert_collector_empty(graph):
collector = next(
item for item in graph.config["callbacks"] if isinstance(item, LocalLangChainTracer)
)
assert collector.latest_run is None
assert not collector.run_has_token_event_map
assert not collector.run_map
assert not collector.order_map
assert not collector.exporter._spans
assert not collector.client.otel_exporter._span_info
async def test_trace_preserves_subagent_model_tool_tree_and_redacts(runtime):
body = query("trace request test-secret sk-example-key Bearer example-token")
model = ScriptedModel(
responses=[
call("task", {"subagent_type": "general-purpose", "description": "Compute statistics"}),
call("common__summarize_numbers", {"numbers": [1, 2, 3]}),
AIMessage(content="mean 2"),
AIMessage(content="answer test-secret"),
]
)
async with client_for(runtime, model) as (client, _):
events = sse(await client.post("/api/v1/runs", json=body))
assert terminal(events) == ["RUN_FINISHED"]
assert [
event["toolCallName"] for event in events if event["type"] == "TOOL_CALL_START"
] == ["task"]
data = read_trace(runtime, body)
assert model.cursor == 4
records = spans(data)
assert root(data)["name"] == "dataagent"
(task,) = [s for s in records if s["name"] == "task"]
(child,) = [s for s in records if s["name"] == "general-purpose"]
assert child["parentSpanId"] == task["spanId"]
assert len([s for s in records if attributes(s).get("langsmith.span.kind") == "llm"]) == 4
assert any(s["name"] == "common__summarize_numbers" for s in records)
text = json.dumps(data)
assert "[REDACTED]" in text
assert all(secret not in text for secret in ("test-secret", "sk-example-key", "example-token"))
assert "new_token" not in text
@pytest.mark.parametrize("timeout", [False, True])
async def test_error_or_timeout_still_saves_native_trace(runtime, timeout):
entered = asyncio.Event()
class WaitingModel(ScriptedModel):
async def _agenerate(self, *args, **kwargs):
entered.set()
await asyncio.Event().wait()
if timeout:
runtime = replace(
runtime,
settings=runtime.settings.model_copy(
update={
"server": runtime.settings.server.model_copy(update={"run_timeout_seconds": 1}),
}
),
)
model = WaitingModel(responses=[]) if timeout else ScriptedModel(responses=[])
body = query()
async with client_for(runtime, model) as (client, _):
assert terminal(sse(await client.post("/api/v1/runs", json=body))) == ["RUN_ERROR"]
if timeout:
assert entered.is_set(), "Timeout must interrupt graph execution, not adapter startup"
data = read_trace(runtime, body)
assert root(data)["status"]["code"] == 2
(model_span,) = [s for s in spans(data) if attributes(s).get("langsmith.span.kind") == "llm"]
assert model_span["status"]["code"] == 2
if timeout:
assert "interrupted locally" in model_span["status"]["message"]
assert model_span["endTimeUnixNano"] == root(data)["endTimeUnixNano"]
assert json.loads(attributes(model_span).get("gen_ai.completion", "{}")) == {}
assert not any(k.startswith("gen_ai.usage.") for k in attributes(model_span))
async def test_traces_are_isolated_across_concurrent_sessions_and_turns(runtime):
model = ScriptedModel(responses=[AIMessage(content="ok") for _ in range(3)])
bodies = [query("first-only", thread="one"), query("second-only", thread="two")]
async with client_for(runtime, model) as (client, _):
responses = await asyncio.gather(
*(client.post("/api/v1/runs", json=body) for body in bodies)
)
assert all(terminal(sse(response)) == ["RUN_FINISHED"] for response in responses)
first = read_trace(runtime, bodies[0])
second = read_trace(runtime, bodies[1])
assert "second-only" not in json.dumps(first)
assert "first-only" not in json.dumps(second)
third = query("next", thread="one")
assert terminal(sse(await client.post("/api/v1/runs", json=third))) == ["RUN_FINISHED"]
assert read_trace(runtime, bodies[0]) == first
assert root(read_trace(runtime, third))["traceId"] != root(first)["traceId"]
@pytest.mark.parametrize("model_error", [False, True])
async def test_trace_write_failure_does_not_change_answer_or_session_status(
runtime, monkeypatch, caplog, model_error
):
def fail(*args):
raise OSError("disk failure test-secret")
monkeypatch.setattr("dataagent.extensions.trace_exporter.LocalFileExporter._write", fail)
model = ScriptedModel(responses=[] if model_error else [AIMessage(content="ok")])
async with client_for(runtime, model) as (client, _):
events = sse(await client.post("/api/v1/runs", json=query()))
assert terminal(events) == (["RUN_ERROR"] if model_error else ["RUN_FINISHED"])
if model_error:
assert "Scripted model ran out of responses" in events[-1]["message"]
assert (await client.get("/api/v1/sessions/thread-1")).json()["data"]["status"] == (
"error" if model_error else "completed"
)
assert "TRACE_SAVE_ERROR" in caplog.text and "test-secret" not in caplog.text
def test_sdk_sync_calls_save_distinct_traces_without_retaining_runs(runtime):
graph = build_graph(runtime, model=ScriptedModel(responses=[AIMessage(content="ok")] * 2))
for prompt in ("first-only", "second-only"):
graph.invoke({"messages": [("user", prompt)]})
assert_collector_empty(graph)
files = list(runtime.paths.for_session("sdk").traces.glob("*.json"))
assert len(files) == 2
for path in files:
text = json.dumps(validate_file(path))
assert sum(prompt in text for prompt in ("first-only", "second-only")) == 1
async def test_sdk_concurrent_invocations_and_stream_share_graph_not_trace(runtime):
class OverlappingModel(ScriptedModel):
async def _agenerate(self, *args, **kwargs):
await asyncio.sleep(0.02)
return await super()._agenerate(*args, **kwargs)
graph = build_graph(runtime, model=OverlappingModel(responses=[AIMessage(content="ok")] * 3))
await asyncio.gather(
*(
graph.ainvoke({"messages": [("user", prompt)]})
for prompt in ("first-only", "second-only")
)
)
assert_collector_empty(graph)
async for _ in graph.astream({"messages": [("user", "stream-only")]}):
pass
assert_collector_empty(graph)
files = list(runtime.paths.for_session("sdk").traces.glob("*.json"))
assert len(files) == 3
for path in files:
text = json.dumps(validate_file(path))
assert sum(prompt in text for prompt in ("first-only", "second-only", "stream-only")) == 1
@pytest.mark.parametrize("cancelled", [False, True])
async def test_sdk_failure_and_cancel_save_trace_and_release_collection(runtime, cancelled):
started = asyncio.Event()
class WaitingModel(ScriptedModel):
async def _agenerate(self, *args, **kwargs):
started.set()
await asyncio.Event().wait()
model = WaitingModel(responses=[]) if cancelled else ScriptedModel(responses=[])
graph = build_graph(runtime, model=model)
task = asyncio.create_task(graph.ainvoke({"messages": [("user", "hi")]}))
if cancelled:
await asyncio.wait_for(started.wait(), 5)
task.cancel()
with pytest.raises(asyncio.CancelledError if cancelled else RuntimeError):
await task
assert_collector_empty(graph)
(path,) = runtime.paths.for_session("sdk").traces.glob("*.json")
data = validate_file(path)
assert root(data)["status"]["code"] == 2
(model_span,) = [s for s in spans(data) if attributes(s).get("langsmith.span.kind") == "llm"]
assert model_span["status"]["code"] == 2
if cancelled:
assert "interrupted locally" in model_span["status"]["message"]
assert model_span["endTimeUnixNano"] == root(data)["endTimeUnixNano"]
assert json.loads(attributes(model_span).get("gen_ai.completion", "{}")) == {}
assert not any(k.startswith("gen_ai.usage.") for k in attributes(model_span))
async def test_cancel_closes_only_its_own_model_run_and_preserves_native_ids(runtime):
entered = {text: asyncio.Event() for text in ("cancel-only", "finish-only")}
release = asyncio.Event()
class WaitingModel(ScriptedModel):
async def _agenerate(self, messages, *args, **kwargs):
entered[messages[-1].content].set()
await release.wait()
return await super()._agenerate(messages, *args, **kwargs)
graph = build_graph(runtime, model=WaitingModel(responses=[AIMessage(content="finished")]))
collector = next(c for c in graph.config["callbacks"] if isinstance(c, LocalLangChainTracer))
tasks = [asyncio.create_task(graph.ainvoke({"messages": [("user", text)]})) for text in entered]
try:
await asyncio.wait_for(asyncio.gather(*(e.wait() for e in entered.values())), 5)
models = {
text: next(
r
for r in collector.run_map.values()
if r.run_type == "llm" and text in json.dumps(r.inputs)
)
for text in entered
}
tasks[0].cancel()
with pytest.raises(asyncio.CancelledError):
await tasks[0]
assert models["cancel-only"].end_time is not None
assert models["finish-only"].end_time is None
release.set()
await tasks[1]
finally:
release.set()
for task in tasks:
if not task.done():
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
assert_collector_empty(graph)
files = list(runtime.paths.for_session("sdk").traces.glob("*.json"))
assert len(files) == 2
for file in files:
data = validate_file(file)
(model_span,) = [
s for s in spans(data) if attributes(s).get("langsmith.span.kind") == "llm"
]
cancelled = "cancel-only" in attributes(model_span)["gen_ai.prompt"]
native = models["cancel-only" if cancelled else "finish-only"]
assert attributes(model_span)["langsmith.metadata.dataagent_run_id"] == str(native.id)
assert model_span["status"]["code"] == (2 if cancelled else 1)
assert native.parent_run_id is not None
async def test_model_close_failure_keeps_cancelled_root_and_redacts_log(
runtime, monkeypatch, caplog
):
from langsmith import RunTree
entered = asyncio.Event()
class WaitingModel(ScriptedModel):
async def _agenerate(self, *args, **kwargs):
entered.set()
await asyncio.Event().wait()
original = RunTree.end
def fail_model_end(run, **kwargs):
if run.run_type == "llm":
raise OSError("model close failed test-secret")
return original(run, **kwargs)
monkeypatch.setattr(RunTree, "end", fail_model_end)
graph = build_graph(runtime, model=WaitingModel(responses=[]))
task = asyncio.create_task(graph.ainvoke({"messages": [("user", "hi")]}))
await asyncio.wait_for(entered.wait(), 5)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert_collector_empty(graph)
(path,) = runtime.paths.for_session("sdk").traces.glob("*.json")
assert root(validate_file(path))["status"]["code"] == 2
assert "TRACE_SAVE_ERROR" in caplog.text
assert "model close failed" in caplog.text and "test-secret" not in caplog.text
async def test_cancel_before_model_start_does_not_create_a_model_span(tmp_path):
from langchain_core.runnables import RunnableLambda
entered = asyncio.Event()
async def wait(_):
entered.set()
await asyncio.Event().wait()
tracer = LocalLangChainTracer(tmp_path)
graph = RunnableLambda(wait).with_config(callbacks=[tracer])
task = asyncio.create_task(graph.ainvoke("before model"))
try:
await asyncio.wait_for(entered.wait(), 5)
finally:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
assert_collector_empty(graph)
(path,) = tmp_path.glob("*.json")
data = validate_file(path)
assert root(data)["status"]["code"] == 2
assert not any(attributes(s).get("langsmith.span.kind") == "llm" for s in spans(data))
async def test_trace_handles_wall_clock_rollback(tmp_path, monkeypatch):
from langchain_core.runnables import RunnableLambda
complete_chain_run = LocalLangChainTracer._complete_chain_run
def complete_after_rollback(tracer, *args, **kwargs):
run = complete_chain_run(tracer, *args, **kwargs)
run.end_time = run.start_time - timedelta(seconds=3)
return run
monkeypatch.setattr(LocalLangChainTracer, "_complete_chain_run", complete_after_rollback)
graph = RunnableLambda(lambda value: value).with_config(
callbacks=[LocalLangChainTracer(tmp_path)]
)
assert await graph.ainvoke("clock rollback") == "clock rollback"
(path,) = tmp_path.glob("*.json")
validate_file(path)
async def test_cancelled_subagent_model_keeps_its_native_parent(runtime):
entered = asyncio.Event()
class WaitingModel(ScriptedModel):
async def _agenerate(self, *args, **kwargs):
if self.cursor == 0:
return await super()._agenerate(*args, **kwargs)
entered.set()
await asyncio.Event().wait()
model = WaitingModel(
responses=[
call(
"task",
{
"subagent_type": "general-purpose",
"description": "Wait for this test",
},
)
]
)
graph = build_graph(runtime, model=model)
tracer = next(c for c in graph.config["callbacks"] if isinstance(c, LocalLangChainTracer))
task = asyncio.create_task(graph.ainvoke({"messages": [("user", "delegate")]}))
try:
await asyncio.wait_for(entered.wait(), 5)
(pending,) = [r for r in tracer.run_map.values() if r.run_type == "llm"]
native_id, parent_id = str(pending.id), str(pending.parent_run_id)
finally:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
assert_collector_empty(graph)
(path,) = runtime.paths.for_session("sdk").traces.glob("*.json")
data = validate_file(path)
models = [s for s in spans(data) if attributes(s).get("langsmith.span.kind") == "llm"]
assert len(models) == 2
(interrupted,) = [
s for s in models if attributes(s)["langsmith.metadata.dataagent_run_id"] == native_id
]
assert attributes(interrupted)["langsmith.metadata.dataagent_parent_run_id"] == parent_id
assert "interrupted locally" in interrupted["status"]["message"]
assert sorted(s["status"]["code"] for s in models) == [1, 2]
@pytest.mark.parametrize("enabled", [False, "local", True])
async def test_local_tracer_never_uploads_even_with_global_tracing(runtime, monkeypatch, enabled):
monkeypatch.setenv("LANGSMITH_TRACING", "true")
monkeypatch.setenv("LANGSMITH_TRACING_MODE", "hybrid")
monkeypatch.setenv("OTEL_TRACES_SAMPLER", "always_off")
graph = build_graph(runtime, model=ScriptedModel(responses=[AIMessage(content="ok")]))
with ls.tracing_context(enabled=enabled):
await graph.ainvoke({"messages": [("user", "hi")]})
assert_collector_empty(graph)
if enabled is False:
assert not list(runtime.paths.for_session("sdk").traces.glob("*.json"))
return
(path,) = runtime.paths.for_session("sdk").traces.glob("*.json")
validate_file(path)
def test_tracer_metadata_clones_keep_local_settings_and_shared_maps(runtime):
graph = build_graph(runtime, model=ScriptedModel(responses=[]))
tracer = graph.config["callbacks"][0]
clone = tracer.copy_with_metadata_defaults(
metadata={"ls_agent_type": "subagent"}, tags=["child"]
)
assert clone.directory == tracer.directory
assert clone.secrets == tracer.secrets
assert clone.run_map is tracer.run_map and clone.order_map is tracer.order_map
assert clone.client is tracer.client
assert clone.exporter is tracer.exporter and clone.provider is tracer.provider
assert clone.tracing_metadata["ls_agent_type"] == "subagent"
async def test_parallel_subagents_have_distinct_parent_tools(runtime):
from langchain_core.messages import HumanMessage, ToolMessage
from langchain_core.outputs import ChatGeneration, ChatResult
class ParallelModel(ScriptedModel):
def _generate(self, messages, **kwargs):
if isinstance(messages[-1], HumanMessage) and messages[-1].content == "delegate twice":
response = AIMessage(
content="",
tool_calls=[
{
"name": "task",
"args": {"subagent_type": "general-purpose", "description": job},
"id": job,
"type": "tool_call",
}
for job in ("job-left", "job-right")
],
)
else:
response = AIMessage(
content="same result" if not isinstance(messages[-1], ToolMessage) else "done"
)
return ChatResult(generations=[ChatGeneration(message=response)])
async def _agenerate(self, messages, **kwargs):
await asyncio.sleep(0.01)
return self._generate(messages)
graph = build_graph(runtime, model=ParallelModel(responses=[]))
await graph.ainvoke({"messages": [("user", "delegate twice")]})
assert_collector_empty(graph)
(path,) = runtime.paths.for_session("sdk").traces.glob("*.json")
records = spans(validate_file(path))
children = [s for s in records if s["name"] == "general-purpose"]
tools = [s for s in records if s["name"] == "task"]
assert len(children) == len(tools) == 2
assert {s["parentSpanId"] for s in children} == {s["spanId"] for s in tools}
assert {
json.loads(attributes(s)["gen_ai.prompt"])["messages"][0]["content"] for s in children
} == {"job-left", "job-right"}
async def test_sdk_trace_keeps_automatic_general_purpose_messages(runtime):
runtime = replace(
runtime,
settings=runtime.settings.model_copy(
update={
"plugins": runtime.settings.plugins.model_copy(update={"enabled": ()}),
}
),
)
model = ScriptedModel(
responses=[
call("task", {"subagent_type": "general-purpose", "description": "child input"}),
AIMessage(content="child answer"),
AIMessage(content="root answer"),
]
)
with create_agent(runtime, model=model) as agent:
await agent.ainvoke({"messages": [("user", "delegate")]})
(path,) = runtime.paths.for_session("sdk").traces.glob("*.json")
records = spans(validate_file(path))
(child,) = [s for s in records if s["name"] == "general-purpose"]
assert "child input" in attributes(child)["gen_ai.prompt"]
assert "child answer" in attributes(child)["gen_ai.completion"]
assert len([s for s in records if attributes(s).get("langsmith.span.kind") == "llm"]) == 3
async def test_sdk_trace_keeps_nested_compiled_subagent_messages(runtime, monkeypatch):
from dataagent.assembly.graph import create_deep_agent, load_extensions
model = ScriptedModel(
responses=[
call("task", {"subagent_type": "outer", "description": "outer input"}),
call("task", {"subagent_type": "nested-specialist", "description": "nested input"}),
AIMessage(content="nested answer"),
AIMessage(content="outer answer"),
AIMessage(content="root answer"),
]
)
nested = create_deep_agent(
model,
name="outer",
subagents=[
{
"name": "nested-specialist",
"description": "A nested specialist",
"system_prompt_file": "Help.",
}
],
)
def extensions(*args, **kwargs):
compiled = load_extensions(*args, **kwargs)
compiled["subagents"] = [{"name": "outer", "description": "Delegate", "runnable": nested}]
return compiled
monkeypatch.setattr("dataagent.assembly.graph.load_extensions", extensions)
with create_agent(runtime, model=model) as agent:
await agent.ainvoke({"messages": [("user", "delegate twice")]})
(path,) = runtime.paths.for_session("sdk").traces.glob("*.json")
records = spans(validate_file(path))
for name, label in (("outer", "outer"), ("nested-specialist", "nested")):
(child,) = [s for s in records if s["name"] == name]
assert f"{label} input" in attributes(child)["gen_ai.prompt"]
assert f"{label} answer" in attributes(child)["gen_ai.completion"]
assert len([s for s in records if attributes(s).get("langsmith.span.kind") == "llm"]) == 5
async def test_tool_failure_and_nested_traceable_are_exported(runtime):
from langchain_core.tools import tool
@ls.traceable(name="nested_compute", run_type="tool")
def compute():
raise RuntimeError("broken tool test-secret")
@tool
def broken() -> str:
"""Fail with a non-business error."""
return compute()
graph = build_graph(
runtime, model=ScriptedModel(responses=[call("broken", {})]), mcp_tools=[broken]
)
with pytest.raises(RuntimeError, match="broken tool"):
await graph.ainvoke({"messages": [("user", "hi")]})
assert_collector_empty(graph)
(path,) = runtime.paths.for_session("sdk").traces.glob("*.json")
data = validate_file(path)
assert root(data)["status"]["code"] == 2
assert "test-secret" not in path.read_text()
(tool_span,) = [s for s in spans(data) if s["name"] == "broken"]
(nested,) = [s for s in spans(data) if s["name"] == "nested_compute"]
assert nested["parentSpanId"] == tool_span["spanId"]
assert nested["status"]["code"] == tool_span["status"]["code"] == 2
async def test_tool_with_naive_nested_trace_end_is_exported(runtime):
from langchain_core.tools import tool
@tool
def lookup() -> str:
"""Return a result from a manually traced operation."""
with ls.trace("nested_lookup", run_type="tool") as span:
span.end(end_time=datetime.now())
return "lookup succeeded"
model = ScriptedModel(responses=[call("lookup", {}), AIMessage(content="done")])
graph = build_graph(runtime, model=model, mcp_tools=[lookup])
result = await graph.ainvoke({"messages": [("user", "look up")]})
assert any(message.content == "lookup succeeded" for message in result["messages"])
(path,) = runtime.paths.for_session("sdk").traces.glob("*.json")
by_name = {span["name"]: span for span in spans(validate_file(path))}
assert by_name["nested_lookup"]["parentSpanId"] == by_name["lookup"]["spanId"]
async def test_tool_error_result_does_not_mark_successful_root_as_error(runtime):
graph = build_graph(
runtime,
model=ScriptedModel(
responses=[
call("common__summarize_numbers", {"numbers": "invalid"}),
AIMessage(content="Please provide numbers"),
]
),
)
await graph.ainvoke({"messages": [("user", "hi")]})
assert_collector_empty(graph)
(path,) = runtime.paths.for_session("sdk").traces.glob("*.json")
data = validate_file(path)
assert root(data)["status"]["code"] == 1
assert "Please provide numbers" in json.dumps(data)
def test_exporter_preserves_binary_attributes_links_and_refuses_overwrite(tmp_path):
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import ReadableSpan
from opentelemetry.trace import Link, SpanContext, TraceFlags
from dataagent.extensions.trace_exporter import LocalFileExporter
run_id = "11111111-1111-4111-8111-111111111111"
other = SpanContext(0x123, 0x456, True, TraceFlags(1))
span = ReadableSpan(
"sample",
context=SpanContext(0xABC, 0xDEF, False, TraceFlags(1)),
resource=Resource({"service.name": "test"}),
attributes={
"binary": b"\x00\xff",
"langsmith.metadata.dataagent_trace_id": run_id,
"langsmith.metadata.dataagent_run_id": run_id,
"langsmith.metadata.dataagent_parent_run_id": "",
"langsmith.metadata.dataagent_dotted_order": "20260924T000000000000Z" + run_id,
},
links=[Link(other)],
start_time=10,
end_time=20,
status=trace.Status(trace.StatusCode.OK),
)
exporter = LocalFileExporter(tmp_path)
exporter.export([span])
exporter.finish(run_id, run_id)
path = tmp_path / f"{run_id}.json"
record = root(validate_file(path))
assert next(a for a in record["attributes"] if a["key"] == "binary")["value"] == {
"bytesValue": "AP8="
}
assert record["links"][0]["traceId"] == f"{0x123:032x}"
assert record["links"][0]["spanId"] == f"{0x456:016x}"
original = path.read_bytes()
exporter.export([span])
with pytest.raises(FileExistsError):
exporter.finish(run_id, run_id)
assert path.read_bytes() == original
assert not exporter._spans
def test_incomplete_file_is_not_published_on_write_error(tmp_path, monkeypatch):
from dataagent.extensions.trace_exporter import LocalFileExporter
def fail(data, stream, **kwargs):
stream.write('{"resourceSpans":')
raise OSError("disk full")
monkeypatch.setattr("dataagent.extensions.trace_exporter.json.dump", fail)
with pytest.raises(OSError, match="disk full"):
LocalFileExporter._write(tmp_path / "trace.json", {})
assert not list(tmp_path.iterdir())
async def test_large_parallel_trace_survives_sdk_batch_boundaries(tmp_path):
from langchain_core.runnables import RunnableLambda, RunnableParallel
async def identity(value):
await asyncio.sleep(0.01)
return value
tracer = LocalLangChainTracer(tmp_path)
graph = RunnableParallel({f"child-{i}": RunnableLambda(identity) for i in range(120)})
graph = graph.with_config(callbacks=[tracer])
assert len(await graph.ainvoke("test")) == 120
assert_collector_empty(graph)
(path,) = tmp_path.glob("*.json")
data = validate_file(path)
assert len(spans(data)) == 121
assert all(
s.get("parentSpanId") == root(data)["spanId"] for s in spans(data) if s is not root(data)
)
def test_resolve_otlp_endpoint_uses_dataagent_env_only(monkeypatch):
from dataagent.extensions.tracing import resolve_otlp_endpoint
monkeypatch.delenv("DATAAGENT_OTLP_TRACES_ENDPOINT", raising=False)
monkeypatch.setenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "http://127.0.0.1:1/v1/traces")
monkeypatch.setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://127.0.0.1:2")
assert resolve_otlp_endpoint() is None
assert resolve_otlp_endpoint(" http://127.0.0.1:9/v1/traces ") == "http://127.0.0.1:9/v1/traces"
monkeypatch.setenv("DATAAGENT_OTLP_TRACES_ENDPOINT", " http://127.0.0.1:3/v1/traces ")
assert resolve_otlp_endpoint() == "http://127.0.0.1:3/v1/traces"
assert resolve_otlp_endpoint("http://127.0.0.1:9/v1/traces") == "http://127.0.0.1:9/v1/traces"
def _otlp_capture_server():
"""Start a localhost OTLP HTTP sink; returns (endpoint, received, shutdown)."""
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
received = []
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
length = int(self.headers.get("Content-Length", "0"))
body = self.rfile.read(length)
received.append((self.path, body, dict(self.headers)))
self.send_response(200)
self.end_headers()
self.wfile.write(b"{}")
def log_message(self, *_args):
pass
server = HTTPServer(("127.0.0.1", 0), Handler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
endpoint = f"http://127.0.0.1:{port}/v1/traces"
return endpoint, received, server.shutdown
@pytest.mark.parametrize("inside_tool", [False, True])
async def test_cancelled_models_reach_both_sinks_and_keep_tool_filter(tmp_path, inside_tool):
from langchain_core.runnables import RunnableConfig, RunnableLambda
from langchain_core.tools import tool
entered = asyncio.Event()
class WaitingModel(ScriptedModel):
async def _agenerate(self, *args, **kwargs):
if self.cursor == 0:
return await super()._agenerate(*args, **kwargs)
entered.set()
await asyncio.Event().wait()
model = WaitingModel(responses=[AIMessage(content="done test-secret")])
async def two_calls(text, config: RunnableConfig):
await model.ainvoke(text, config)
await model.ainvoke(text, config)
endpoint, received, shutdown = _otlp_capture_server()
tracer = LocalLangChainTracer(
tmp_path,
secrets=("test-secret",),
agent_names=("dataagent",),
otlp_endpoint=endpoint,
otlp_headers={},
)
if inside_tool:
helper = tool(two_calls, description="Call the helper model twice.")
async def invoke_tool(text, config: RunnableConfig):
return await helper.ainvoke({"text": text}, config)
graph = RunnableLambda(invoke_tool)
else:
graph = RunnableLambda(two_calls)
graph = graph.with_config(callbacks=[tracer], run_name="dataagent")
task = asyncio.create_task(graph.ainvoke("input test-secret"))
try:
await asyncio.wait_for(entered.wait(), 5)
(pending_model,) = [r for r in tracer.run_map.values() if r.run_type == "llm"]
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert_collector_empty(graph)
(path,) = tmp_path.glob("*.json")
data = validate_file(path)
local = [s for s in spans(data) if attributes(s).get("langsmith.span.kind") == "llm"]
remote = []
for _, body, _ in received:
request = ExportTraceServiceRequest.FromString(body)
remote.extend(
s
for r in request.resource_spans
for scope in r.scope_spans
for s in scope.spans
if any(
a.key == "langsmith.span.kind" and a.value.string_value == "llm"
for a in s.attributes
)
)
assert len(local) == len(remote) == (0 if inside_tool else 2)
if not inside_tool:
(closed,) = [
s
for s in local
if attributes(s)["langsmith.metadata.dataagent_run_id"] == str(pending_model.id)
]
assert closed["status"]["code"] == 2
assert closed["endTimeUnixNano"] == root(data)["endTimeUnixNano"]
assert sorted(s["status"]["code"] for s in local) == [1, 2]
(interrupted_remote,) = [
s
for s in remote
if any(
a.key == "langsmith.metadata.dataagent_run_id"
and a.value.string_value == str(pending_model.id)
for a in s.attributes
)
]
assert any(
a.key == "langsmith.metadata.dataagent_error"
and "interrupted locally" in a.value.string_value
for a in interrupted_remote.attributes
)
assert "test-secret" not in path.read_text()
assert all(b"test-secret" not in body for _, body, _ in received)
finally:
if not task.done():
task.cancel()
await asyncio.gather(task, return_exceptions=True)
shutdown()
@pytest.mark.parametrize("model_error", [False, True])
@pytest.mark.parametrize("sync", [False, True])
async def test_tool_models_are_omitted_before_live_export(tmp_path, model_error, sync):
from langchain_core.runnables import RunnableConfig, RunnableLambda
from langchain_core.tools import tool
endpoint, received, shutdown = _otlp_capture_server()
model = ScriptedModel(responses=[] if model_error else [AIMessage(content="helper result")] * 2)
helper = RunnableLambda(lambda value: value) | model
@tool
def sync_helper(text: str, config: RunnableConfig) -> str:
"""Call a model through a chain."""
return helper.invoke(text, config=config).text
@tool
async def async_helper(text: str, config: RunnableConfig) -> str:
"""Call a model through a chain."""
return (await helper.ainvoke(text, config=config)).text
async def parallel_tools(text, config):
return await asyncio.gather(
*[async_helper.ainvoke({"text": text}, config=config) for _ in range(2)],
return_exceptions=True,
)
tracer = LocalLangChainTracer(tmp_path, otlp_endpoint=endpoint)
graph = (sync_helper if sync else RunnableLambda(parallel_tools)).with_config(
callbacks=[tracer]
)
try:
if sync:
if model_error:
with pytest.raises(RuntimeError, match="ran out of responses"):
graph.invoke({"text": "input"})
else:
assert graph.invoke({"text": "input"}) == "helper result"
else:
results = await graph.ainvoke("input")
if model_error:
assert all(isinstance(result, RuntimeError) for result in results)
else:
assert results == ["helper result", "helper result"]
assert len(model.requests) == (1 if sync else 2)
data = validate_file(next(tmp_path.glob("*.json")))
assert not any(attributes(s).get("langsmith.span.kind") == "llm" for s in spans(data))
assert any(attributes(s).get("langsmith.span.kind") == "tool" for s in spans(data))
assert_collector_empty(graph)
assert received
remote = []
for _, body, _ in received:
request = ExportTraceServiceRequest.FromString(body)
remote.extend(
s for r in request.resource_spans for scope in r.scope_spans for s in scope.spans
)
kinds = [
a.value.string_value
for s in remote
for a in s.attributes
if a.key == "langsmith.span.kind"
]
assert "tool" in kinds
assert "llm" not in kinds
finally:
shutdown()
def test_otlp_live_export_posts_ended_spans(tmp_path, monkeypatch):
"""SimpleSpanProcessor must POST ended spans to the configured OTLP endpoint."""
import time
from langchain_core.messages import AIMessage
from langchain_core.runnables import RunnableLambda
from dataagent.extensions.tracing import LocalLangChainTracer
endpoint, received, shutdown = _otlp_capture_server()
monkeypatch.setenv("DATAAGENT_OTLP_TRACES_ENDPOINT", endpoint)
try:
tracer = LocalLangChainTracer(tmp_path)
assert tracer.otlp_exporter is not None
graph = RunnableLambda(lambda _: AIMessage(content="ok")).with_config(callbacks=[tracer])
graph.invoke({"messages": [("user", "hello")]})
deadline = time.time() + 5
while not received and time.time() < deadline:
time.sleep(0.05)
assert received, "expected at least one OTLP POST"
path, body, headers = received[0]
assert path == "/v1/traces"
assert body
assert list(tmp_path.glob("*.json")), "local file export must still run"
finally:
shutdown()
def test_otlp_live_export_redacts_configured_secrets(tmp_path, monkeypatch):
"""Remote OTLP payloads must apply the same redaction as the local JSON file."""
import time
from langchain_core.messages import AIMessage
from langchain_core.runnables import RunnableLambda
from dataagent.extensions.trace_exporter import RedactingSpanExporter
from dataagent.extensions.tracing import LocalLangChainTracer
secret = "otlp-live-secret-value"
endpoint, received, shutdown = _otlp_capture_server()
monkeypatch.setenv("DATAAGENT_OTLP_TRACES_ENDPOINT", endpoint)
try:
tracer = LocalLangChainTracer(tmp_path, secrets=(secret,))
assert isinstance(tracer.otlp_exporter, RedactingSpanExporter)
graph = RunnableLambda(lambda _: AIMessage(content=f"answer {secret}")).with_config(
callbacks=[tracer]
)
graph.invoke({"messages": [("user", f"prompt {secret}")]})
deadline = time.time() + 5
while not received and time.time() < deadline:
time.sleep(0.05)
assert received, "expected at least one OTLP POST"
remote = b"".join(body for _, body, _ in received)
assert secret.encode() not in remote
assert b"[REDACTED]" in remote
local_text = "".join(path.read_text(encoding="utf-8") for path in tmp_path.glob("*.json"))
assert secret not in local_text
assert "[REDACTED]" in local_text
finally:
shutdown()