diff --git a/docs/content/docs/framework/ve-tracing.en.mdx b/docs/content/docs/framework/ve-tracing.en.mdx index 95ef72015..1d3340247 100644 --- a/docs/content/docs/framework/ve-tracing.en.mdx +++ b/docs/content/docs/framework/ve-tracing.en.mdx @@ -87,6 +87,8 @@ python agent.py Define an APMPlus data exporter to connect your agent's trace and metrics data to the Volcengine APMPlus platform. +The VeADK APMPlus exporter also writes the effective values of the five headers above to identically named tags on every span. Set `MODEL_AGENT_CLIENT_REQ_ID` to search APMPlus by `X-Client-Request-Id`. The `ListSpan` API returns these case-sensitive names in each span’s `Tags`. + ### Preparation Fill in the apmplus attributes under the `observability` field of `config.yaml`: diff --git a/docs/content/docs/framework/ve-tracing.mdx b/docs/content/docs/framework/ve-tracing.mdx index 01dbd3ae3..f6ee776f6 100644 --- a/docs/content/docs/framework/ve-tracing.mdx +++ b/docs/content/docs/framework/ve-tracing.mdx @@ -87,6 +87,8 @@ python agent.py 定义 APMPlus 数据导出器,即可将智能体的 Trace 与 Metrics 数据接入火山引擎 APMPlus 平台。 +VeADK 的 APMPlus exporter 也会把这五个请求头的有效值写入每条 span 的同名标签。设置 `MODEL_AGENT_CLIENT_REQ_ID` 后,可在 APMPlus 按 `X-Client-Request-Id` 检索,再用 `ListSpan` 查看各条 span 的 `Tags`。标签区分大小写。 + ### 准备工作 在 `config.yaml` 的 `observability` 字段中填写 apmplus 属性: diff --git a/tests/test_portal_metrics.py b/tests/test_portal_metrics.py index 62cea9b0f..d7ecfc5e2 100644 --- a/tests/test_portal_metrics.py +++ b/tests/test_portal_metrics.py @@ -288,7 +288,10 @@ def test_apmplus_trace_and_metric_export_headers( lambda exporter: reader, ) with ( - patch.object(apmplus_exporter_module, "OTLPSpanExporter") as span_transport, + patch.object( + apmplus_exporter_module.OTLPSpanExporter, "__init__", return_value=None + ) as span_transport, + patch.object(apmplus_exporter_module.OTLPSpanExporter, "shutdown"), patch.object(apmplus_exporter_module, "OTLPMetricExporter") as metric_transport, ): exporter = APMPlusExporter( diff --git a/tests/test_tracing.py b/tests/test_tracing.py index 9bdc4af53..b7e993b36 100644 --- a/tests/test_tracing.py +++ b/tests/test_tracing.py @@ -222,6 +222,64 @@ def test_http_export_headers(monkeypatch, exporter_cls, config, platform_headers } +def test_apmplus_sends_header_tags_on_each_span(monkeypatch): + monkeypatch.setenv("MODEL_AGENT_CLIENT_REQ_ID", "agentkit/test-runtime") + monkeypatch.setenv("MODEL_AGENT_ENCRYPTED", "false") + monkeypatch.setattr( + apmplus_exporter_module, "ensure_apmplus_meter_provider", lambda **kwargs: None + ) + exporter = APMPlusExporter( + config=APMPlusExporterConfig( + endpoint="http://localhost:4317", app_key="test", service_name="probe" + ), + headers={ + "VEADK-SOURCE": "custom-source", + "user-agent": "custom-agent", + "X-Private": "private", + }, + ) + provider = trace_sdk.TracerProvider() + other = OTelInMemorySpanExporter() + provider.add_span_processor(SimpleSpanProcessor(other)) + try: + exporter.register(provider) + with patch.object(exporter._exporter._client, "Export") as send: + tracer = provider.get_tracer("veadk") + with tracer.start_as_current_span("runner_request"): + with tracer.start_as_current_span( + "model_request", attributes={"veadk-source": "old", "keep": "yes"} + ): + pass + assert provider.force_flush() + payload = send.call_args.kwargs["request"] + spans = [ + span + for resource in payload.resource_spans + for scope in resource.scope_spans + for span in scope.spans + ] + assert {span.name for span in spans} == {"runner_request", "model_request"} + expected = { + "veadk-source": "custom-source", + "veadk-version": VERSION, + "User-Agent": "custom-agent", + "X-Client-Request-Id": "agentkit/test-runtime", + "x-is-encrypted": "false", + } + for span in spans: + attrs = {attr.key: attr.value.string_value for attr in span.attributes} + assert len(attrs) == len(span.attributes) + assert attrs == ( + expected | {"keep": "yes"} if span.name == "model_request" else expected + ) + assert other.get_finished_spans()[0].attributes == { + "veadk-source": "old", + "keep": "yes", + } + finally: + provider.shutdown() + + def init_exporters(): cozeloop_exporter = CozeloopExporter( config=CozeloopExporterConfig( diff --git a/veadk/tracing/telemetry/exporters/apmplus_exporter.py b/veadk/tracing/telemetry/exporters/apmplus_exporter.py index 5c7cd9ac4..b46a79099 100644 --- a/veadk/tracing/telemetry/exporters/apmplus_exporter.py +++ b/veadk/tracing/telemetry/exporters/apmplus_exporter.py @@ -12,17 +12,23 @@ # See the License for the specific language governing permissions and # limitations under the License. +from collections.abc import Sequence from typing import Any from opentelemetry import metrics as metrics_api from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter from opentelemetry.metrics._internal import _ProxyMeterProvider +from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ( + ExportTraceServiceRequest, +) from opentelemetry.sdk import metrics as metrics_sdk from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader from opentelemetry.sdk.resources import Resource +from opentelemetry.sdk.trace import ReadableSpan from opentelemetry.sdk.trace.export import BatchSpanProcessor from pydantic import BaseModel, Field +from requests.structures import CaseInsensitiveDict from typing_extensions import override from veadk.config import settings @@ -42,6 +48,47 @@ def _grpc_header_options(headers: dict) -> dict[str, Any]: return options +class _APMPlusSpanExporter(OTLPSpanExporter): + """Include VeADK attribution in the span payload indexed by APMPlus.""" + + def __init__(self, endpoint: str, headers: dict): + super().__init__( + endpoint=endpoint, insecure=True, **_grpc_header_options(headers) + ) + effective_headers = CaseInsensitiveDict(headers) + # Only these five public fields may become searchable span tags. + self._header_tags = { + key: effective_headers[key] + for key in ( + "veadk-source", + "veadk-version", + "User-Agent", + "X-Client-Request-Id", + "x-is-encrypted", + ) + } + + @override + def _translate_data( + self, data: Sequence[ReadableSpan] + ) -> ExportTraceServiceRequest: + request = super()._translate_data(data) + for resource in request.resource_spans: + for scope in resource.scope_spans: + for span in scope.spans: + existing = { + attr.key: attr + for attr in span.attributes + if attr.key in self._header_tags + } + for key, value in self._header_tags.items(): + attr = existing.get(key) + if attr is None: + attr = span.attributes.add(key=key) + attr.value.string_value = value + return request + + def ensure_apmplus_meter_provider( endpoint: str, headers: dict, @@ -159,11 +206,7 @@ def model_post_init(self, context: Any) -> None: } self.resource_attributes |= resource_attributes - self._exporter = OTLPSpanExporter( - endpoint=self.config.endpoint, - insecure=True, - **_grpc_header_options(self.headers), - ) + self._exporter = _APMPlusSpanExporter(self.config.endpoint, self.headers) self.processor = BatchSpanProcessor(self._exporter) ensure_apmplus_meter_provider(