diff --git a/.release-please-manifest.json b/.release-please-manifest.json
index 730f11673..45258062b 100644
--- a/.release-please-manifest.json
+++ b/.release-please-manifest.json
@@ -33,7 +33,7 @@
"python/frameworks/huggingface": "0.1.0",
"python/frameworks/instructor": "0.2.1",
"python/frameworks/lancedb": "0.1.2",
- "python/frameworks/langchain": "0.2.1",
+ "python/frameworks/langchain": "0.2.2",
"python/frameworks/litellm": "0.1.11",
"python/frameworks/livekit": "0.2.1",
"python/frameworks/llama_index": "0.1.11",
@@ -45,7 +45,7 @@
"python/frameworks/mongodb-vector": "0.1.2",
"python/frameworks/ollama": "0.1.0",
"python/frameworks/openwebui": "0.1.0",
- "python/frameworks/openai": "0.1.13",
+ "python/frameworks/openai": "0.1.14",
"python/frameworks/openai-agents": "0.1.7",
"python/frameworks/openai-realtime": "0.1.0",
"python/frameworks/parallel": "0.1.1",
@@ -119,7 +119,7 @@
"typescript/packages/traceai_voltagent": "0.1.0",
"typescript/packages/traceai_weaviate": "0.1.3",
"typescript/packages/traceai_xai": "0.1.1",
- "java": "1.0.2",
+ "java": "1.0.3",
"go/a2a": "0.1.1",
"go/anthropic": "0.1.0",
"go/eino": "0.1.0",
@@ -127,7 +127,7 @@
"go/lambda": "0.1.1",
"go/openai": "0.1.0",
"csharp/src/FIInstrumentation": "1.0.1",
- "python": "1.3.0",
+ "python": "1.3.1",
"typescript/packages/traceai_elevenlabs": "0.1.1",
"go/bedrock": "0.1.1",
"typescript/packages/traceai_huggingface_transformers": "0.1.0",
diff --git a/java/CHANGELOG.md b/java/CHANGELOG.md
index bae06d945..9b5c0e9fe 100644
--- a/java/CHANGELOG.md
+++ b/java/CHANGELOG.md
@@ -1,5 +1,16 @@
# Changelog
+## [1.0.3](https://github.com/future-agi/traceAI/compare/java-v1.0.2...java-v1.0.3) (2026-11-10)
+
+### Features
+
+* **semconv:** add cost, time-to-first-token and coding-agent attribute constants to `SemanticConventions` ([#605](https://github.com/future-agi/traceAI/pull/605)).
+
+### Bug Fixes
+
+* **java-core:** respect the `FI_HIDE_INPUTS`, `FI_HIDE_OUTPUTS`, `FI_HIDE_INPUT_MESSAGES` and `FI_HIDE_OUTPUT_MESSAGES` environment flags in `TraceConfig` defaults; explicit builder settings still take precedence ([#543](https://github.com/future-agi/traceAI/pull/543)).
+* **ollama-java:** restore legacy Ollama4j 1.0.79 generation with empty default options ([#425](https://github.com/future-agi/traceAI/pull/425)).
+
## [1.0.2](https://github.com/future-agi/traceAI/compare/java-v1.0.1...java-v1.0.2) (2026-11-05)
diff --git a/java/README.md b/java/README.md
index 1ed28e0f7..c3f5fa3de 100644
--- a/java/README.md
+++ b/java/README.md
@@ -6,7 +6,7 @@ OpenTelemetry instrumentation for Java AI applications. Trace LLM calls, embeddi
Release coordinates use **`com.futureagi`**. Artifact names are unchanged, and **Java package names remain `ai.traceai.*`**; existing imports do not change.
-The install examples track Java SDK `1.0.2`, matching [`pom.xml`](pom.xml); release-please updates them together. All SDK modules inherit that version, and the BOM aligns them.
+The install examples track Java SDK `1.0.3`, matching [`pom.xml`](pom.xml); release-please updates them together. All SDK modules inherit that version, and the BOM aligns them.
> **Unreleased API:** the [provider ownership and shutdown](#provider-ownership-and-shutdown) behavior below, including `TraceAI.init(TraceConfig, OpenTelemetry)`, is not in the immutable Central releases `1.0.0` or `1.0.1`. Until a new release containing it is published and passes the [external-consumer check](#validate-readme-coordinates), that section requires a verified source build of this checkout. Installing an older Central release or the historical JitPack commit below is not sufficient. The basic OpenAI quickstart remains available from Central.
@@ -20,7 +20,7 @@ Import the BOM once, then add the instrumentation you need:
Only calls through this wrapper's blocking methods are traced. Streaming + * callbacks, tool calls and calls through {@link #unwrap()} are not instrumented. + * Token usage is not captured.
* *Usage:
*
@@ -72,8 +79,8 @@ public OllamaResult generate(String model, String prompt) throws Exception {
tracer.setInputValue(span, prompt);
tracer.setInputMessages(span, Collections.singletonList(FITracer.message("user", prompt)));
- // Execute request
- OllamaResult result = api.generate(model, prompt, false, null);
+ // Ollama4j 1.0.79 dereferences Options even when using server defaults.
+ OllamaResult result = api.generate(model, prompt, false, new Options(Collections.emptyMap()));
// Capture output
if (result.getResponse() != null) {
diff --git a/java/traceai-java-ollama/src/test/java/ai/traceai/ollama/TracedOllamaAPITest.java b/java/traceai-java-ollama/src/test/java/ai/traceai/ollama/TracedOllamaAPITest.java
new file mode 100644
index 000000000..3de35a9df
--- /dev/null
+++ b/java/traceai-java-ollama/src/test/java/ai/traceai/ollama/TracedOllamaAPITest.java
@@ -0,0 +1,168 @@
+package ai.traceai.ollama;
+
+import ai.traceai.FITracer;
+import ai.traceai.SemanticConventions;
+import ai.traceai.TraceConfig;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.sun.net.httpserver.HttpServer;
+import io.github.ollama4j.OllamaAPI;
+import io.github.ollama4j.exceptions.OllamaBaseException;
+import io.github.ollama4j.models.chat.OllamaChatMessage;
+import io.github.ollama4j.models.chat.OllamaChatMessageRole;
+import io.opentelemetry.api.common.AttributeKey;
+import io.opentelemetry.api.trace.StatusCode;
+import io.opentelemetry.sdk.testing.junit5.OpenTelemetryExtension;
+import io.opentelemetry.sdk.trace.data.SpanData;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Real Ollama4j 1.0.79 transport against a synthetic loopback server; no models or credentials. */
+class TracedOllamaAPITest {
+ @RegisterExtension
+ static final OpenTelemetryExtension telemetry = OpenTelemetryExtension.create();
+
+ private HttpServer server;
+ private OllamaAPI api;
+ private TracedOllamaAPI traced;
+ private final List paths = new CopyOnWriteArrayList<>();
+ private final List requests = new CopyOnWriteArrayList<>();
+ private volatile int status = 200;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.createContext("/", exchange -> {
+ String path = exchange.getRequestURI().getPath();
+ paths.add(path);
+ String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
+ if (!body.isEmpty()) {
+ requests.add(JsonParser.parseString(body).getAsJsonObject());
+ }
+ String response = status != 200 ? "{\"error\":\"synthetic failure\"}" : switch (path) {
+ case "/api/generate" -> "{\"model\":\"test-model\",\"response\":\"Hello\",\"done\":true}";
+ case "/api/chat" -> "{\"model\":\"test-model\",\"message\":{\"role\":\"assistant\",\"content\":\"Hello\"},\"done\":true}";
+ case "/api/embeddings" -> "{\"embedding\":[0.1,0.2,0.3]}";
+ case "/api/tags" -> "{\"models\":[{\"name\":\"test-model\",\"model\":\"test-model\"}]}";
+ default -> throw new IllegalStateException("Unexpected path: " + path);
+ };
+ byte[] bytes = response.getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().set("Content-Type", "application/json");
+ exchange.sendResponseHeaders(status, bytes.length);
+ try (var output = exchange.getResponseBody()) {
+ output.write(bytes);
+ }
+ });
+ server.start();
+ api = new OllamaAPI("http://127.0.0.1:" + server.getAddress().getPort());
+ api.setRequestTimeoutSeconds(5);
+ traced = new TracedOllamaAPI(api, new FITracer(telemetry.getOpenTelemetry().getTracer("test"),
+ TraceConfig.builder().hideInputs(false).hideOutputs(false)
+ .hideInputMessages(false).hideOutputMessages(false).hideErrorDetails(false).build()));
+ }
+
+ @AfterEach
+ void tearDown() {
+ if (server != null) {
+ server.stop(0);
+ }
+ }
+
+ @Test
+ void generateUsesEmptyOptionsAndPreservesResponse() throws Exception {
+ var result = traced.generate("test-model", "Hello?");
+
+ assertThat(result.getResponse()).isEqualTo("Hello");
+ assertThat(result.getHttpStatusCode()).isEqualTo(200);
+ assertThat(paths).containsExactly("/api/generate");
+ JsonObject request = requests.get(0);
+ assertThat(request.get("model").getAsString()).isEqualTo("test-model");
+ assertThat(request.get("prompt").getAsString()).isEqualTo("Hello?");
+ assertThat(request.getAsJsonObject("options").size()).isZero();
+ assertThat(request.get("raw").getAsBoolean()).isFalse();
+ assertThat(request.get("stream").getAsBoolean()).isFalse();
+ SpanData span = onlySpan("Ollama Generate", StatusCode.OK);
+ assertThat(attribute(span, SemanticConventions.FI_SPAN_KIND)).isEqualTo("LLM");
+ assertThat(attribute(span, SemanticConventions.LLM_MODEL_NAME)).isEqualTo("test-model");
+ assertThat(attribute(span, SemanticConventions.OUTPUT_VALUE)).isEqualTo("Hello");
+ }
+
+ @Test
+ void chatPreservesMessagesAndResponse() throws Exception {
+ var result = traced.chat("test-model", List.of(
+ new OllamaChatMessage(OllamaChatMessageRole.USER, "Hello?")));
+
+ assertThat(result.getResponse()).isEqualTo("Hello");
+ assertThat(paths).containsExactly("/api/chat");
+ JsonObject message = requests.get(0).getAsJsonArray("messages").get(0).getAsJsonObject();
+ assertThat(message.get("role").getAsString()).isEqualTo("user");
+ assertThat(message.get("content").getAsString()).isEqualTo("Hello?");
+ SpanData span = onlySpan("Ollama Chat", StatusCode.OK);
+ assertThat(attribute(span, SemanticConventions.LLM_INPUT_MESSAGES)).contains("Hello?");
+ assertThat(attribute(span, SemanticConventions.OUTPUT_VALUE)).isEqualTo("Hello");
+ }
+
+ @Test
+ void embedPreservesVectorAndRecordsDimensions() throws Exception {
+ assertThat(traced.embed("test-model", "hello")).containsExactly(0.1, 0.2, 0.3);
+ assertThat(paths).containsExactly("/api/embeddings");
+ SpanData span = onlySpan("Ollama Embed", StatusCode.OK);
+ assertThat(attribute(span, SemanticConventions.FI_SPAN_KIND)).isEqualTo("EMBEDDING");
+ assertThat(span.getAttributes().get(AttributeKey.longKey(SemanticConventions.EMBEDDING_DIMENSIONS)))
+ .isEqualTo(3L);
+ }
+
+ @Test
+ void embedBatchUsesOneSpanForAllRequests() throws Exception {
+ assertThat(traced.embedBatch("test-model", List.of("first", "second")))
+ .containsExactly(List.of(0.1, 0.2, 0.3), List.of(0.1, 0.2, 0.3));
+ assertThat(paths).containsExactly("/api/embeddings", "/api/embeddings");
+ SpanData span = onlySpan("Ollama Embed Batch", StatusCode.OK);
+ assertThat(span.getAttributes().get(AttributeKey.longKey(SemanticConventions.EMBEDDING_VECTOR_COUNT)))
+ .isEqualTo(2L);
+ }
+
+ @Test
+ void listModelsPreservesNames() throws Exception {
+ assertThat(traced.listModels()).containsExactly("test-model");
+ assertThat(paths).containsExactly("/api/tags");
+ onlySpan("Ollama List Models", StatusCode.OK);
+ }
+
+ @Test
+ void generatePreservesSdkExceptionAndEndsSpan() {
+ status = 400;
+ assertThatThrownBy(() -> traced.generate("test-model", "hello"))
+ .isInstanceOf(OllamaBaseException.class).hasMessageContaining("synthetic failure");
+ assertThat(paths).containsExactly("/api/generate");
+ assertThat(onlySpan("Ollama Generate", StatusCode.ERROR).getEvents()).hasSize(1);
+ }
+
+ @Test
+ void unwrapKeepsTheOriginalClient() {
+ assertThat(traced.unwrap()).isSameAs(api);
+ assertThat(telemetry.getSpans()).isEmpty();
+ }
+
+ private SpanData onlySpan(String name, StatusCode statusCode) {
+ assertThat(telemetry.getSpans()).hasSize(1);
+ SpanData span = telemetry.getSpans().get(0);
+ assertThat(span.getName()).isEqualTo(name);
+ assertThat(span.getStatus().getStatusCode()).isEqualTo(statusCode);
+ return span;
+ }
+
+ private String attribute(SpanData span, String name) {
+ return span.getAttributes().get(AttributeKey.stringKey(name));
+ }
+}
diff --git a/java/traceai-java-openai/pom.xml b/java/traceai-java-openai/pom.xml
index 5468b5bd4..e327a3063 100644
--- a/java/traceai-java-openai/pom.xml
+++ b/java/traceai-java-openai/pom.xml
@@ -5,7 +5,7 @@
com.futureagi
traceai-java-parent
- 1.0.2
+ 1.0.3
traceai-java-openai
diff --git a/java/traceai-java-pgvector/pom.xml b/java/traceai-java-pgvector/pom.xml
index 1f35d27ee..e544dc982 100644
--- a/java/traceai-java-pgvector/pom.xml
+++ b/java/traceai-java-pgvector/pom.xml
@@ -5,7 +5,7 @@
com.futureagi
traceai-java-parent
- 1.0.2
+ 1.0.3
traceai-java-pgvector
diff --git a/java/traceai-java-pinecone/pom.xml b/java/traceai-java-pinecone/pom.xml
index 07d15c75b..59f02b8e1 100644
--- a/java/traceai-java-pinecone/pom.xml
+++ b/java/traceai-java-pinecone/pom.xml
@@ -5,7 +5,7 @@
com.futureagi
traceai-java-parent
- 1.0.2
+ 1.0.3
traceai-java-pinecone
diff --git a/java/traceai-java-qdrant/pom.xml b/java/traceai-java-qdrant/pom.xml
index d8ba9d1d1..3785e2b75 100644
--- a/java/traceai-java-qdrant/pom.xml
+++ b/java/traceai-java-qdrant/pom.xml
@@ -5,7 +5,7 @@
com.futureagi
traceai-java-parent
- 1.0.2
+ 1.0.3
traceai-java-qdrant
diff --git a/java/traceai-java-quarkus-langchain4j/pom.xml b/java/traceai-java-quarkus-langchain4j/pom.xml
index 94cf18a93..01c1a8c2c 100644
--- a/java/traceai-java-quarkus-langchain4j/pom.xml
+++ b/java/traceai-java-quarkus-langchain4j/pom.xml
@@ -4,7 +4,7 @@
com.futureagi
traceai-java-parent
- 1.0.2
+ 1.0.3
traceai-java-quarkus-langchain4j
TraceAI Quarkus LangChain4j
diff --git a/java/traceai-java-redis/pom.xml b/java/traceai-java-redis/pom.xml
index faa4d5b2c..8d59e6641 100644
--- a/java/traceai-java-redis/pom.xml
+++ b/java/traceai-java-redis/pom.xml
@@ -5,7 +5,7 @@
com.futureagi
traceai-java-parent
- 1.0.2
+ 1.0.3
traceai-java-redis
diff --git a/java/traceai-java-semantic-kernel/pom.xml b/java/traceai-java-semantic-kernel/pom.xml
index 7e9037608..4b10d14f7 100644
--- a/java/traceai-java-semantic-kernel/pom.xml
+++ b/java/traceai-java-semantic-kernel/pom.xml
@@ -5,7 +5,7 @@
com.futureagi
traceai-java-parent
- 1.0.2
+ 1.0.3
traceai-java-semantic-kernel
diff --git a/java/traceai-java-vertexai/pom.xml b/java/traceai-java-vertexai/pom.xml
index 3b993922a..f1cd6d2fe 100644
--- a/java/traceai-java-vertexai/pom.xml
+++ b/java/traceai-java-vertexai/pom.xml
@@ -5,7 +5,7 @@
com.futureagi
traceai-java-parent
- 1.0.2
+ 1.0.3
traceai-java-vertexai
diff --git a/java/traceai-java-watsonx/pom.xml b/java/traceai-java-watsonx/pom.xml
index 0325cd219..58ebe3bde 100644
--- a/java/traceai-java-watsonx/pom.xml
+++ b/java/traceai-java-watsonx/pom.xml
@@ -5,7 +5,7 @@
com.futureagi
traceai-java-parent
- 1.0.2
+ 1.0.3
traceai-java-watsonx
diff --git a/java/traceai-java-weaviate/README.md b/java/traceai-java-weaviate/README.md
index 214df4069..0bc5171d6 100644
--- a/java/traceai-java-weaviate/README.md
+++ b/java/traceai-java-weaviate/README.md
@@ -17,7 +17,7 @@ After building and installing this checkout locally, add these dependencies. For
com.futureagi
traceai-java-weaviate
- 1.0.2
+ 1.0.3
io.weaviate
diff --git a/java/traceai-java-weaviate/pom.xml b/java/traceai-java-weaviate/pom.xml
index 7ec4bd958..697a7fa74 100644
--- a/java/traceai-java-weaviate/pom.xml
+++ b/java/traceai-java-weaviate/pom.xml
@@ -5,7 +5,7 @@
com.futureagi
traceai-java-parent
- 1.0.2
+ 1.0.3
traceai-java-weaviate
diff --git a/java/traceai-langchain4j/pom.xml b/java/traceai-langchain4j/pom.xml
index 7795c6bd7..04c2b7b87 100644
--- a/java/traceai-langchain4j/pom.xml
+++ b/java/traceai-langchain4j/pom.xml
@@ -5,7 +5,7 @@
com.futureagi
traceai-java-parent
- 1.0.2
+ 1.0.3
traceai-langchain4j
diff --git a/java/traceai-spring-ai/pom.xml b/java/traceai-spring-ai/pom.xml
index 3a0adfd15..2b7b4f92f 100644
--- a/java/traceai-spring-ai/pom.xml
+++ b/java/traceai-spring-ai/pom.xml
@@ -5,7 +5,7 @@
com.futureagi
traceai-java-parent
- 1.0.2
+ 1.0.3
traceai-spring-ai
diff --git a/java/traceai-spring-boot-starter/pom.xml b/java/traceai-spring-boot-starter/pom.xml
index 7c1a763cd..c0b2cac84 100644
--- a/java/traceai-spring-boot-starter/pom.xml
+++ b/java/traceai-spring-boot-starter/pom.xml
@@ -5,7 +5,7 @@
com.futureagi
traceai-java-parent
- 1.0.2
+ 1.0.3
traceai-spring-boot-starter
diff --git a/python/CHANGELOG.md b/python/CHANGELOG.md
index cb0279420..2e1aa00f1 100644
--- a/python/CHANGELOG.md
+++ b/python/CHANGELOG.md
@@ -1,12 +1,23 @@
-## [Unreleased]
+## [1.3.1] - 2026-11-10
### Fixed
- PII redaction (`pii_redaction` / `FI_PII_REDACTION`) no longer corrupts correlation identifiers (#195):
`session.id`, `user.id` and conversation ids are exported unchanged, numbers inside a longer
identifier are no longer read as phone numbers, and card numbers must be card-shaped and pass the
Luhn check. Free text and metadata are still redacted when the flag is on; hide flags and the image
cap apply to every field.
-
-## [1.3.0] - pending release
+- With `FI_PII_REDACTION` on, a phone number that follows a JSON escape (`\n`, `\t`, `\r`) in serialized
+ text is now redacted; digits inside longer identifiers stay intact.
+- Exporter credentials (#155): an empty `Authorization` header no longer hides valid
+ `FI_API_KEY`/`FI_SECRET_KEY` environment keys, and explicit `X-Api-Key`/`X-Secret-Key`
+ headers are sent once instead of alongside case-variant copies from the environment.
+ Explicit credential headers still take precedence; header names are sent lower-case.
+ Blank credential headers are skipped before case variants are merged.
+ Known limitation: with `opentelemetry-exporter-otlp-proto-http` 1.45 or later, a blank
+ `Authorization=` entry in `OTEL_EXPORTER_OTLP_HEADERS` or `OTEL_EXPORTER_OTLP_TRACES_HEADERS` is
+ still sent as an empty header next to the FI keys, because the exporter re-reads those variables.
+ Remove blank entries from the environment; headers passed in code are unaffected.
+
+## [1.3.0] - 2026-11-07
### Added
- Semantic conventions for agent cost, time to first token and coding-agent spans in
`fi_instrumentation.fi_types` (#605): `tool_call.id`, `tool.name`, `fi.usage.*`, `fi.cost.kind`
diff --git a/python/README.md b/python/README.md
index 5eb967518..bbacdaaeb 100644
--- a/python/README.md
+++ b/python/README.md
@@ -119,6 +119,14 @@ Pass your own OpenTelemetry `TracerProvider` to `OpenAIInstrumentor().instrument
[Provider setup](fi_instrumentation/otel.py) ยท [Examples](examples/)
+## Troubleshooting: 401 Unauthorized when exporting traces
+
+- **Check the export URL.** Set `FI_BASE_URL` to the deployment you intend to use. The default HTTP exporter sends to `/tracer/v1/traces` and replaces any path in `FI_BASE_URL`; an explicit `HTTPSpanExporter(endpoint=...)` is used unchanged. A successful health check does not validate your export credentials.
+- **Use one pair of keys.** Set `FI_API_KEY` and `FI_SECRET_KEY` from the same key, in the exporting process, before the exporter is created. Do not use a masked secret.
+- **Use one credential source.** Explicit `Authorization`, `X-Api-Key` or `X-Secret-Key` headers take precedence and the environment keys are then not added. Remove an unrelated `Authorization` header rather than mixing sources. An empty credential header is ignored.
+- **Retired or disabled keys.** If the service reports a retired key, create a personal key at `/dashboard/keys`, and confirm that its owner still has access to the organization (and workspace, when scoped).
+- **When reporting an issue**, share the sanitized URL, SDK and exporter versions, the response status, error code and request id, and the header *names* you send. Never share key values, `Authorization` values or an unredacted environment dump.
+
## Packages
Each package below links to its own installation instructions, supported SDK versions, and examples. Package availability and framework support are independent; do not assume every package supports the same upstream version.
diff --git a/python/examples/openlit/README.md b/python/examples/openlit/README.md
index a00eeb6c3..9832fb5b0 100644
--- a/python/examples/openlit/README.md
+++ b/python/examples/openlit/README.md
@@ -31,7 +31,7 @@ pip install -r requirements.txt
export FI_API_KEY="YOUR_API_KEY"
export FI_SECRET_KEY="YOUR_SECRET_KEY"
-export OTEL_EXPORTER_OTLP_ENDPOINT="https://YOUR_FI_COLLECTOR_ORIGIN" # no path
+export OTEL_EXPORTER_OTLP_ENDPOINT="https://api.futureagi.com/tracer"
export OTEL_RESOURCE_ATTRIBUTES="project_name=my-chatbot,project_type=observe"
export OPENAI_API_KEY="YOUR_OPENAI_KEY" # optional: OPENAI_BASE_URL, OPENAI_MODEL
@@ -99,12 +99,15 @@ there shows up as a log line, not an exception.
### Endpoint
-Set `otlp_endpoint` to the collector origin, with no path. OpenLIT copies
-it into `OTEL_EXPORTER_OTLP_ENDPOINT` (`openlit/otel/tracing.py:72-73`) and
-creates OpenTelemetry's OTLP/HTTP span exporter with no arguments
-(`tracing.py:121-128`). That exporter (`opentelemetry-exporter-otlp-proto-http`
-1.45.0, `_common/__init__.py:129-138`) removes one trailing `/` and always
-appends `/v1/traces`. Tested results:
+Set `otlp_endpoint` to the collector base URL: `https://api.futureagi.com/tracer`
+for Cloud. For self-hosted deployments, use your collector's base URL,
+including any deployment path prefix. Do not include `/v1/traces`.
+OpenLIT copies the base URL into `OTEL_EXPORTER_OTLP_ENDPOINT`
+(`openlit/otel/tracing.py:72-73`) and creates OpenTelemetry's OTLP/HTTP span
+exporter with no arguments (`tracing.py:121-128`). The exporter preserves the
+base path and appends `/v1/traces`, so Cloud traces go to
+`https://api.futureagi.com/tracer/v1/traces`. A trailing `/` on the base URL
+is optional. Endpoint examples:
| `otlp_endpoint` | Request path | Reply from a fi-collector-like mux |
|---|---|---|
diff --git a/python/examples/openlit/src/app.py b/python/examples/openlit/src/app.py
index 2fbe1289b..59dea0527 100644
--- a/python/examples/openlit/src/app.py
+++ b/python/examples/openlit/src/app.py
@@ -34,7 +34,10 @@ def init_tracing() -> None:
endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")
if not endpoint:
# Without an endpoint OpenLIT prints every span to stdout instead.
- raise SystemExit("Set OTEL_EXPORTER_OTLP_ENDPOINT to the fi-collector origin.")
+ raise SystemExit(
+ "Set OTEL_EXPORTER_OTLP_ENDPOINT to your collector base URL "
+ "(https://api.futureagi.com/tracer for Cloud), without /v1/traces."
+ )
api_key = os.environ.get("FI_API_KEY")
secret_key = os.environ.get("FI_SECRET_KEY")
if not (api_key and secret_key):
@@ -49,7 +52,8 @@ def init_tracing() -> None:
)
openlit.init(
service_name=APP_NAME,
- # The origin, no path: the OTLP/HTTP exporter appends /v1/traces.
+ # The base URL (Cloud: https://api.futureagi.com/tracer), not the
+ # full trace URL: OTLP/HTTP preserves the prefix and appends /v1/traces.
otlp_endpoint=endpoint,
# OpenLIT joins this dict into OTEL_EXPORTER_OTLP_HEADERS, which the
# exporter splits on commas and percent-decodes: encode the values.
diff --git a/python/examples/openlit/tests/test_openlit_recipe.py b/python/examples/openlit/tests/test_openlit_recipe.py
index 19b6f14dc..3329d18f0 100644
--- a/python/examples/openlit/tests/test_openlit_recipe.py
+++ b/python/examples/openlit/tests/test_openlit_recipe.py
@@ -518,9 +518,11 @@ def test_no_secret_in_the_export_or_output(recipe_run: dict[str, Any]) -> None:
("/v1/traces", ("/v1/traces/v1/traces", 404)),
# fi-collector also serves /tracer/v1/traces.
("/tracer", ("/tracer/v1/traces", 200)),
+ ("/tracer/", ("/tracer/v1/traces", 200)),
+ ("/tracer/v1/traces", ("/tracer/v1/traces/v1/traces", 404)),
],
)
-def test_endpoint_is_the_origin_and_v1_traces_is_appended(
+def test_endpoint_preserves_the_base_path_and_appends_v1_traces(
tmp_path: Path, suffix: str, expected: tuple[str, int]
) -> None:
result, calls, guard_attempts = _run_against_recorder(tmp_path, suffix)
@@ -807,7 +809,11 @@ def test_a_later_otlp_exporter_in_the_process_sends_the_future_agi_keys(tmp_path
@pytest.mark.parametrize(
("unset", "message"),
[
- ("OTEL_EXPORTER_OTLP_ENDPOINT", "Set OTEL_EXPORTER_OTLP_ENDPOINT"),
+ (
+ "OTEL_EXPORTER_OTLP_ENDPOINT",
+ "Set OTEL_EXPORTER_OTLP_ENDPOINT to your collector base URL "
+ "(https://api.futureagi.com/tracer for Cloud), without /v1/traces.",
+ ),
("OTEL_RESOURCE_ATTRIBUTES", "Set OTEL_RESOURCE_ATTRIBUTES"),
("FI_API_KEY", "Set FI_API_KEY and FI_SECRET_KEY"),
("FI_SECRET_KEY", "Set FI_API_KEY and FI_SECRET_KEY"),
@@ -1025,6 +1031,33 @@ def test_readme_run_block_sets_what_app_py_checks(monkeypatch: pytest.MonkeyPatc
assert OTELResourceDetector().detect().attributes.get("project_name")
+def test_readme_cloud_endpoint_preserves_the_base_path_on_the_wire(tmp_path: Path) -> None:
+ """Use the documented base path with a loopback collector, never Cloud."""
+ (block,) = _code_blocks(_readme_section("Run"), "bash")
+ exports = dict(re.findall(r'^export (\w+)="([^"]*)"', block, flags=re.MULTILINE))
+ endpoint = urlsplit(exports["OTEL_EXPORTER_OTLP_ENDPOINT"])
+ assert (endpoint.scheme, endpoint.netloc, endpoint.path) == (
+ "https",
+ "api.futureagi.com",
+ "/tracer",
+ )
+ with Receiver() as receiver, FakeOpenAI(ANSWER) as fake:
+ result, guard_attempts = _launch(tmp_path, APP, receiver.origin + endpoint.path, fake)
+ requests, spans = receiver.requests(), receiver.spans()
+ assert not result.timed_out
+ assert result.returncode == 0, result.stderr.decode("utf-8", "replace")
+ assert guard_attempts == []
+ assert {request["path"] for request in requests} == {"/tracer/v1/traces"}
+ assert set(_by_name(spans)) == {LLM_SPAN, HTTP_SPAN}
+ for request in requests:
+ assert request["headers"]["x-api-key"] == FI_API_KEY
+ assert request["headers"]["x-secret-key"] == FI_SECRET_KEY
+ assert all(resource["project_name"] == PROJECT for resource in request["resource_attributes"])
+ payload = json.dumps(spans)
+ for marker in (*CONTENT_MARKERS, FI_API_KEY, FI_SECRET_KEY, OPENAI_KEY):
+ assert marker not in payload
+
+
def _collector_aliases() -> dict[str, Any]:
src = os.environ.get("FI_COLLECTOR_SRC")
if not src:
diff --git a/python/fi_instrumentation/instrumentation/version.py b/python/fi_instrumentation/instrumentation/version.py
index 35cff98c1..17bd5af46 100644
--- a/python/fi_instrumentation/instrumentation/version.py
+++ b/python/fi_instrumentation/instrumentation/version.py
@@ -1 +1 @@
-__version__ = "1.3.0" # x-release-please-version
+__version__ = "1.3.1" # x-release-please-version
diff --git a/python/fi_instrumentation/otel.py b/python/fi_instrumentation/otel.py
index 26f578632..7e4f5b2b3 100644
--- a/python/fi_instrumentation/otel.py
+++ b/python/fi_instrumentation/otel.py
@@ -8,7 +8,7 @@
import uuid
import warnings
from enum import Enum
-from typing import Any, Dict, List, Optional, Tuple, Type, Union
+from typing import Any, Dict, List, Mapping, Optional, Tuple, Type, Union
from urllib.parse import ParseResult, urlparse
import requests
@@ -589,6 +589,44 @@ def on_end(self, span: Any) -> None:
super().on_end(span)
+_CREDENTIAL_HEADERS = (AUTHORIZATION, "x-api-key", "x-secret-key")
+
+
+def _is_blank(value: Any) -> bool:
+ """None, or a str/bytes value that is empty after stripping whitespace."""
+ if value is None:
+ return True
+ if isinstance(value, (bytes, bytearray)):
+ return not bytes(value).strip()
+ return not str(value).strip()
+
+
+def _with_fi_auth_headers(headers: Any) -> Dict[str, Any]:
+ """Lower-case explicit headers and add the FI_API_KEY/FI_SECRET_KEY pair once.
+
+ Explicit credentials win: the environment pair is added only when no
+ Authorization, X-Api-Key or X-Secret-Key header was passed. A credential
+ header with an empty value is dropped rather than treated as a credential,
+ so an empty Authorization no longer hides valid environment keys. Keys are
+ lower-cased on both sides, so the request never carries case-variant
+ duplicates such as ``x-api-key`` and ``X-Api-Key``.
+ """
+ pairs = () if not headers else (headers.items() if isinstance(headers, Mapping) else headers)
+ merged: Dict[str, Any] = {}
+ for key, value in pairs:
+ name = (key.decode() if isinstance(key, bytes) else str(key)).lower()
+ # Skip a blank credential before collapsing case variants, so an empty
+ # duplicate can never erase an explicit one and pull in the env pair.
+ if name in _CREDENTIAL_HEADERS and _is_blank(value):
+ continue
+ merged[name] = value
+ if not any(name in merged for name in _CREDENTIAL_HEADERS):
+ auth_header = get_env_fi_auth_header()
+ if auth_header:
+ merged.update({k.lower(): v for k, v in auth_header.items()})
+ return merged
+
+
class GRPCSpanExporter(_GRPCSpanExporter):
"""
OTLP span exporter using gRPC.
@@ -604,31 +642,10 @@ def __init__(self, *args: Any, **kwargs: Any):
bound_args = sig.bind_partial(*args, **kwargs)
bound_args.apply_defaults()
- auth_header = get_env_fi_auth_header()
- lower_case_auth_header = (
- {k.lower(): v for k, v in auth_header.items()} if auth_header else None
+ bound_args.arguments["headers"] = (
+ _with_fi_auth_headers(bound_args.arguments.get("headers")) or None
)
- if not bound_args.arguments.get("headers"):
- headers = {
- **(lower_case_auth_header or dict()),
- }
- bound_args.arguments["headers"] = headers if headers else None
- else:
- passed_headers = bound_args.arguments["headers"]
- if isinstance(passed_headers, dict):
- headers = {k.lower(): v for k, v in passed_headers.items()}
- else:
- headers = {k.lower(): v for k, v in passed_headers}
-
- if AUTHORIZATION not in headers:
- bound_args.arguments["headers"] = {
- **headers,
- **(lower_case_auth_header or dict()),
- }
- else:
- bound_args.arguments["headers"] = headers
-
if bound_args.arguments.get("endpoint") is None:
bound_args.arguments["endpoint"] = get_env_grpc_collector_endpoint()
super().__init__(*bound_args.args, **bound_args.kwargs)
@@ -667,12 +684,7 @@ def __init__(self, *args: Any, **kwargs: Any):
_, endpoint = _normalized_endpoint(None)
bound_args.arguments["endpoint"] = endpoint
- final_headers = {k.lower(): v for k, v in (headers or {}).items()}
- if AUTHORIZATION not in final_headers:
- auth_header = get_env_fi_auth_header()
- if auth_header:
- final_headers.update(auth_header)
- bound_args.arguments["headers"] = final_headers or None
+ bound_args.arguments["headers"] = _with_fi_auth_headers(headers) or None
super().__init__(*bound_args.args, **bound_args.kwargs)
diff --git a/python/frameworks/langchain/CHANGELOG.md b/python/frameworks/langchain/CHANGELOG.md
index f92ecec2c..862169e51 100644
--- a/python/frameworks/langchain/CHANGELOG.md
+++ b/python/frameworks/langchain/CHANGELOG.md
@@ -1,3 +1,7 @@
+## [0.2.2] - 2026-11-10
+### Fixed
+- Restore the optional Protect hook when `LangChainInstrumentor.uninstrument()` runs, so subsequent calls and re-instrumentation do not retain a stale wrapper (#393).
+
## [0.2.1] - 2026-10-26
### Fixed
- LangGraph's `configurable.thread_id` is copied to `session.id` on every span, including Deep Agents subagents. Metadata `session_id` and `using_session(...)` retain precedence; blank thread ids set nothing.
diff --git a/python/frameworks/langchain/pyproject.toml b/python/frameworks/langchain/pyproject.toml
index 2adb61205..1289a1583 100644
--- a/python/frameworks/langchain/pyproject.toml
+++ b/python/frameworks/langchain/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "traceAI-langchain"
-version = "0.2.1"
+version = "0.2.2"
description = "OpenTelemetry instrumentation for LangChain"
authors = ["Future AGI "]
readme = "README.md"
diff --git a/python/frameworks/langchain/tests/test_protect_lifecycle.py b/python/frameworks/langchain/tests/test_protect_lifecycle.py
new file mode 100644
index 000000000..33151cab0
--- /dev/null
+++ b/python/frameworks/langchain/tests/test_protect_lifecycle.py
@@ -0,0 +1,292 @@
+"""The optional Protect hook follows the public instrumentor's lifecycle.
+
+Use the real LangChain callback path, guardrail wrapper and OTLP/HTTP exporter.
+Only the optional evaluation service is synthetic; no credentials or model calls
+are required. These contracts also run when ai-evaluation is not installed.
+"""
+
+import sys
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from threading import Thread
+from types import ModuleType
+
+import pytest
+from fi_instrumentation import TraceConfig
+from langchain_core.callbacks import BaseCallbackManager
+from langchain_core.runnables import RunnableLambda
+from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
+from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+from traceai_langchain import LangChainInstrumentor
+
+
+@pytest.fixture
+def protect_module(monkeypatch):
+ module = ModuleType("fi.evals")
+
+ class Protect:
+ def __init__(self):
+ self.calls = []
+ self.result = {"status": "passed", "messages": "private-output"}
+ self.error = None
+
+ def protect(self, inputs, protect_rules):
+ self.calls.append((inputs, protect_rules))
+ if self.error is not None:
+ raise self.error
+ return self.result
+
+ module.Protect = Protect
+ package = ModuleType("fi")
+ package.__path__ = []
+ package.evals = module
+ monkeypatch.setitem(sys.modules, "fi", package)
+ monkeypatch.setitem(sys.modules, "fi.evals", module)
+ return module
+
+
+@pytest.fixture
+def instrumentor():
+ instance = LangChainInstrumentor()
+ original_init = BaseCallbackManager.__init__
+ try:
+ yield instance
+ finally:
+ if instance.is_instrumented_by_opentelemetry:
+ instance.uninstrument()
+ # Keep baseline failures from contaminating other tests.
+ BaseCallbackManager.__init__ = original_init
+
+
+@pytest.fixture
+def otlp():
+ payloads = []
+
+ class Receiver(BaseHTTPRequestHandler):
+ def do_POST(self):
+ payloads.append(self.rfile.read(int(self.headers["Content-Length"])))
+ self.send_response(200)
+ self.send_header("Content-Type", "application/x-protobuf")
+ self.send_header("Content-Length", "0")
+ self.end_headers()
+
+ def log_message(self, *_args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Receiver)
+ thread = Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ provider = TracerProvider()
+ provider.add_span_processor(
+ SimpleSpanProcessor(
+ OTLPSpanExporter(
+ endpoint=f"http://127.0.0.1:{server.server_port}/v1/traces",
+ headers={},
+ timeout=2,
+ )
+ )
+ )
+
+ def spans():
+ return [
+ span
+ for payload in payloads
+ for resource in ExportTraceServiceRequest.FromString(payload).resource_spans
+ for scope in resource.scope_spans
+ for span in scope.spans
+ ]
+
+ try:
+ yield provider, spans
+ finally:
+ provider.shutdown()
+ server.shutdown()
+ thread.join(timeout=5)
+ server.server_close()
+
+
+def test_uninstrument_restores_both_methods(protect_module, instrumentor, otlp):
+ provider, _ = otlp
+ original_init = BaseCallbackManager.__init__
+ original_protect = protect_module.Protect.protect
+ instrumentor.instrument(tracer_provider=provider)
+ assert BaseCallbackManager.__init__ is not original_init
+ assert protect_module.Protect.protect is not original_protect
+
+ instrumentor.uninstrument()
+
+ assert BaseCallbackManager.__init__ is original_init
+ assert protect_module.Protect.protect is original_protect
+ assert instrumentor._original_protect is None
+
+
+def test_disable_stops_guardrail_exports(protect_module, instrumentor, otlp):
+ provider, spans = otlp
+ client = protect_module.Protect()
+ rules = [{"metric": "synthetic"}]
+ instrumentor.instrument(tracer_provider=provider)
+ assert client.protect("enabled", rules) is client.result
+ assert [span.name for span in spans()] == ["Guardrail.protect"]
+
+ instrumentor.uninstrument()
+
+ assert client.protect("disabled", rules) is client.result
+ assert client.calls == [("enabled", rules), ("disabled", rules)]
+ assert [span.name for span in spans()] == ["Guardrail.protect"]
+
+
+def test_repeated_cycles_keep_one_guardrail_span(protect_module, instrumentor, otlp):
+ provider, spans = otlp
+ client = protect_module.Protect()
+ rules = [{"metric": "synthetic"}]
+ chain = RunnableLambda(lambda value: client.protect(value, rules))
+
+ for cycle in range(3):
+ instrumentor.instrument(tracer_provider=provider)
+ with provider.get_tracer(__name__).start_as_current_span("outer"):
+ assert chain.invoke("enabled") is client.result
+ exported = spans()
+ assert len(exported) == (cycle + 1) * 3
+ guardrail, chain_span, parent = exported[-3:]
+ assert guardrail.name == "Guardrail.protect"
+ assert parent.name == "outer"
+ assert guardrail.parent_span_id == chain_span.parent_span_id == parent.span_id
+ assert guardrail.trace_id == chain_span.trace_id == parent.trace_id
+ assert guardrail.end_time_unix_nano >= guardrail.start_time_unix_nano > 0
+ assert guardrail.status.code == 1 # OTLP STATUS_CODE_OK
+ instrumentor.uninstrument()
+ assert chain.invoke("disabled") is client.result
+ assert len(spans()) == (cycle + 1) * 3
+
+ assert len(client.calls) == 6
+
+
+def test_reenable_drops_old_provider_and_config(protect_module, instrumentor, otlp):
+ provider, spans = otlp
+ client = protect_module.Protect()
+ rules = [{"metric": "synthetic"}]
+ instrumentor.instrument(tracer_provider=provider)
+ assert client.protect("first-input", rules) is client.result
+ instrumentor.uninstrument()
+
+ # A different provider must not keep exporting to the previous one.
+ new_provider = TracerProvider()
+ try:
+ instrumentor.instrument(tracer_provider=new_provider)
+ assert client.protect("second-input", rules) is client.result
+ instrumentor.uninstrument()
+ assert len(spans()) == 1
+ finally:
+ new_provider.shutdown()
+
+ instrumentor.instrument(
+ tracer_provider=provider,
+ config=TraceConfig(hide_inputs=True, hide_outputs=True),
+ )
+ assert client.protect("private-input", rules) is client.result
+ assert len(spans()) == 2
+ hidden = str(spans()[-1])
+ assert "private-input" not in hidden
+ assert "private-output" not in hidden
+ instrumentor.uninstrument()
+
+
+def test_missing_optional_dependency_keeps_callback_lifecycle(monkeypatch, instrumentor, otlp):
+ monkeypatch.setitem(sys.modules, "fi.evals", None)
+ provider, spans = otlp
+ original_init = BaseCallbackManager.__init__
+ instrumentor.instrument(tracer_provider=provider)
+ assert RunnableLambda(lambda value: value + 1).invoke(1) == 2
+ instrumentor.uninstrument()
+ assert BaseCallbackManager.__init__ is original_init
+ assert len(spans()) == 1
+ assert RunnableLambda(lambda value: value + 1).invoke(2) == 3
+ assert len(spans()) == 1
+
+
+def test_optional_dependency_changes_do_not_leave_stale_hooks(
+ monkeypatch, protect_module, instrumentor, otlp
+):
+ provider, _ = otlp
+ original_protect = protect_module.Protect.protect
+ instrumentor.instrument(tracer_provider=provider)
+ # Cleanup must restore the captured class, not require another import.
+ monkeypatch.setitem(sys.modules, "fi.evals", None)
+ instrumentor.uninstrument()
+ assert protect_module.Protect.protect is original_protect
+
+ instrumentor.instrument(tracer_provider=provider)
+ instrumentor.uninstrument()
+ assert protect_module.Protect.protect is original_protect
+
+ monkeypatch.setitem(sys.modules, "fi.evals", protect_module)
+ instrumentor.instrument(tracer_provider=provider)
+ assert protect_module.Protect.protect is not original_protect
+ instrumentor.uninstrument()
+ assert protect_module.Protect.protect is original_protect
+
+
+def test_cleanup_only_restores_the_class_it_patched(
+ monkeypatch, protect_module, instrumentor, otlp
+):
+ provider, _ = otlp
+ patched_class = protect_module.Protect
+ original_protect = patched_class.protect
+ instrumentor.instrument(tracer_provider=provider)
+
+ class ReplacementProtect:
+ def protect(self, inputs, protect_rules):
+ return inputs
+
+ replacement_method = ReplacementProtect.protect
+ monkeypatch.setattr(protect_module, "Protect", ReplacementProtect)
+ instrumentor.uninstrument()
+
+ assert patched_class.protect is original_protect
+ assert ReplacementProtect.protect is replacement_method
+ assert instrumentor._protect_class is None
+ assert instrumentor._original_protect is None
+
+
+def test_dependency_added_while_disabled_is_not_modified(
+ monkeypatch, protect_module, instrumentor, otlp
+):
+ provider, _ = otlp
+ original_protect = protect_module.Protect.protect
+ monkeypatch.setitem(sys.modules, "fi.evals", None)
+ instrumentor.instrument(tracer_provider=provider)
+ monkeypatch.setitem(sys.modules, "fi.evals", protect_module)
+ instrumentor.uninstrument()
+
+ assert protect_module.Protect.protect is original_protect
+ assert instrumentor._protect_class is None
+ assert instrumentor._original_protect is None
+
+
+def test_public_lifecycle_is_idempotent(protect_module, instrumentor, otlp):
+ provider, spans = otlp
+ client = protect_module.Protect()
+ original_protect = protect_module.Protect.protect
+ instrumentor.instrument(tracer_provider=provider)
+ instrumentor.instrument(tracer_provider=provider)
+ assert client.protect("input", [{"metric": "synthetic"}]) is client.result
+ assert len(spans()) == 1
+ instrumentor.uninstrument()
+ instrumentor.uninstrument()
+ assert protect_module.Protect.protect is original_protect
+
+
+def test_exceptions_are_unchanged_after_disable(protect_module, instrumentor, otlp):
+ provider, spans = otlp
+ client = protect_module.Protect()
+ client.error = ValueError("synthetic guardrail failure")
+ instrumentor.instrument(tracer_provider=provider)
+ for enabled in (True, False):
+ if not enabled:
+ instrumentor.uninstrument()
+ with pytest.raises(ValueError) as caught:
+ client.protect("input", [{"metric": "synthetic"}])
+ assert caught.value is client.error
+ assert len(spans()) == 1
+ assert spans()[0].status.code == 2 # OTLP STATUS_CODE_ERROR
diff --git a/python/frameworks/langchain/traceai_langchain/__init__.py b/python/frameworks/langchain/traceai_langchain/__init__.py
index df8203bf6..df30b52be 100644
--- a/python/frameworks/langchain/traceai_langchain/__init__.py
+++ b/python/frameworks/langchain/traceai_langchain/__init__.py
@@ -70,6 +70,7 @@ def _instrument(self, **kwargs: Any) -> None:
name="BaseCallbackManager.__init__",
wrapper=_BaseCallbackManagerInit(self._tracer),
)
+ self._protect_class = Protect
if Protect is not None:
self._original_protect = Protect.protect
wrap_function_wrapper(
@@ -83,6 +84,10 @@ def _instrument(self, **kwargs: Any) -> None:
def _uninstrument(self, **kwargs: Any) -> None:
langchain_core.callbacks.BaseCallbackManager.__init__ = self._original_callback_manager_init # type: ignore
self._original_callback_manager_init = None # type: ignore
+ if self._protect_class is not None:
+ self._protect_class.protect = self._original_protect
+ self._original_protect = None
+ self._protect_class = None
self._tracer = None
self.fi_tracer = None
diff --git a/python/frameworks/langchain/traceai_langchain/version.py b/python/frameworks/langchain/traceai_langchain/version.py
index 130276d81..210c13fdd 100644
--- a/python/frameworks/langchain/traceai_langchain/version.py
+++ b/python/frameworks/langchain/traceai_langchain/version.py
@@ -1 +1 @@
-__version__ = "0.2.1" # x-release-please-version
+__version__ = "0.2.2" # x-release-please-version
diff --git a/python/frameworks/openai/CHANGELOG.md b/python/frameworks/openai/CHANGELOG.md
index 7561cdc19..094eba4c8 100644
--- a/python/frameworks/openai/CHANGELOG.md
+++ b/python/frameworks/openai/CHANGELOG.md
@@ -1,6 +1,15 @@
-## [Unreleased]
-### Fixed
+## [0.1.14] - 2026-11-10
+### Added
- Add Azure client deployment, API version and endpoint host/explicit port span metadata through the existing OpenAI instrumentor, without recording full URLs or credentials (#154).
+
+### Fixed
+- Attribute OpenAI-compatible requests to `api.cometapi.com` to `cometapi` (#348), including streamed and failed requests.
+- Attribute OpenAI-compatible requests to `api.novita.ai` to `novita` (#397), including streamed and failed requests.
+- Attribute dedicated and regional Baseten endpoints (`model-*.api.baseten.co`) to `baseten` (#541).
+- Attribute Azure Government resources (`*.openai.azure.us`) to `azure` (#502).
+- Attribute the OpenAI-compatible `openrouter.ai` host to `openrouter` (#547).
+- `input.value` keeps every message of a conversational input instead of only the first (#245), and
+ `input.mime_type` is derived from that full value.
- Normally exhausted Chat Completions streams now export ERROR when at least one
choice reports a non-null `finish_reason` but a requested choice index never does.
This honors the effective on-wire `n`, including `extra_body` overrides, for sync
diff --git a/python/frameworks/openai/pyproject.toml b/python/frameworks/openai/pyproject.toml
index c4cc30a1a..26e0b31fa 100644
--- a/python/frameworks/openai/pyproject.toml
+++ b/python/frameworks/openai/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "traceAI-openai"
-version = "0.1.13"
+version = "0.1.14"
description = "OpenTelemetry instrumentation for OpenAI"
authors = ["Future AGI "]
readme = "README.md"
diff --git a/python/frameworks/openai/tests/test_cometapi_provider.py b/python/frameworks/openai/tests/test_cometapi_provider.py
new file mode 100644
index 000000000..53e267f65
--- /dev/null
+++ b/python/frameworks/openai/tests/test_cometapi_provider.py
@@ -0,0 +1,224 @@
+"""CometAPI attribution through the real SDK and a loopback OTLP/HTTP collector."""
+
+import asyncio
+import json
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from importlib import import_module
+from threading import Thread
+
+import openai
+import pytest
+from fi_instrumentation import TraceConfig
+from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
+from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import (
+ ExportTraceServiceRequest,
+)
+from opentelemetry.proto.trace.v1.trace_pb2 import Status
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+from traceai_openai import OpenAIInstrumentor
+from traceai_openai._providers import provider_from_host
+
+# OpenAI 3.x uses httpx2; the supported 1.x and 2.x SDKs use httpx.
+httpx = import_module("httpx2" if int(openai.__version__.split(".")[0]) >= 3 else "httpx")
+BASE_URL = "https://api.cometapi.com/v1"
+REQUEST_MODEL = "requested-model"
+RESPONSE_MODEL = "served-model"
+
+
+@pytest.mark.parametrize(
+ "host,expected",
+ [
+ ("api.cometapi.com", "cometapi"),
+ ("API.CometAPI.com.", "cometapi"),
+ ("api.cometapi.com.customer.example", "openai"),
+ ("proxy.api.cometapi.com", "openai"),
+ ("notapi.cometapi.com", "openai"),
+ ("cometapi.com", "openai"),
+ ("api.openai.com", "openai"),
+ ("localhost", "openai"),
+ (None, "openai"),
+ ],
+)
+def test_cometapi_requires_the_exact_api_host(host, expected):
+ assert provider_from_host(host) == expected
+
+
+@pytest.fixture
+def wire_spans():
+ spans = []
+ payloads = []
+
+ class Collector(BaseHTTPRequestHandler):
+ def do_POST(self):
+ assert self.path == "/v1/traces"
+ assert self.headers["Content-Type"] == "application/x-protobuf"
+ payload = self.rfile.read(int(self.headers["Content-Length"]))
+ payloads.append(payload)
+ message = ExportTraceServiceRequest.FromString(payload)
+ for resource in message.resource_spans:
+ for scope in resource.scope_spans:
+ spans.extend(scope.spans)
+ self.send_response(200)
+ self.send_header("Content-Length", "0")
+ self.end_headers()
+
+ def log_message(self, *_args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Collector)
+ thread = Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True)
+ thread.start()
+ provider = TracerProvider()
+ provider.add_span_processor(
+ SimpleSpanProcessor(
+ OTLPSpanExporter(
+ endpoint=f"http://127.0.0.1:{server.server_port}/v1/traces",
+ headers={},
+ timeout=2,
+ )
+ )
+ )
+ instrumentor = OpenAIInstrumentor()
+ instrumentor.instrument(tracer_provider=provider, config=TraceConfig())
+ try:
+ yield spans
+ finally:
+ instrumentor.uninstrument()
+ provider.shutdown()
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=2)
+ assert b"synthetic-cometapi-key" not in b"".join(payloads)
+
+
+def response_for(request, outcome):
+ assert request.url.host == "api.cometapi.com"
+ assert request.url.path == "/v1/chat/completions"
+ assert request.headers["authorization"] == "Bearer synthetic-cometapi-key"
+ body = json.loads(request.content)
+ assert body["model"] == REQUEST_MODEL
+ assert body["stream"] is (outcome == "stream")
+ if outcome == "error":
+ return httpx.Response(401, json={"error": {"message": "synthetic failure"}})
+ if outcome == "stream":
+ chunks = [
+ {
+ "id": "c",
+ "object": "chat.completion.chunk",
+ "created": 1,
+ "model": RESPONSE_MODEL,
+ "choices": [
+ {
+ "index": 0,
+ "finish_reason": "stop",
+ "delta": {"role": "assistant", "content": "hello"},
+ }
+ ],
+ },
+ {
+ "id": "c",
+ "object": "chat.completion.chunk",
+ "created": 1,
+ "model": RESPONSE_MODEL,
+ "choices": [],
+ "usage": {"prompt_tokens": 5, "completion_tokens": 2, "total_tokens": 7},
+ },
+ ]
+ body = "".join(f"data: {json.dumps(chunk)}\n\n" for chunk in chunks)
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ content=(body + "data: [DONE]\n\n").encode(),
+ )
+ return httpx.Response(
+ 200,
+ json={
+ "id": "c",
+ "object": "chat.completion",
+ "created": 1,
+ "model": RESPONSE_MODEL,
+ "choices": [
+ {
+ "index": 0,
+ "finish_reason": "stop",
+ "message": {"role": "assistant", "content": "hello"},
+ }
+ ],
+ "usage": {"prompt_tokens": 5, "completion_tokens": 2, "total_tokens": 7},
+ },
+ )
+
+
+@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"])
+@pytest.mark.parametrize("outcome", ["success", "stream", "error"])
+def test_cometapi_chat_attribution_on_otlp_wire(wire_spans, use_async, outcome):
+ kwargs = {
+ "model": REQUEST_MODEL,
+ "messages": [{"role": "user", "content": "hi"}],
+ "stream": outcome == "stream",
+ }
+ if outcome == "stream":
+ kwargs["stream_options"] = {"include_usage": True}
+ client_kwargs = {
+ "base_url": BASE_URL,
+ "api_key": "synthetic-cometapi-key",
+ "max_retries": 0,
+ }
+ transport = httpx.MockTransport(lambda request: response_for(request, outcome))
+
+ async def run_async():
+ async with openai.AsyncOpenAI(
+ **client_kwargs,
+ http_client=httpx.AsyncClient(transport=transport, trust_env=False),
+ ) as client:
+ result = await client.chat.completions.create(**kwargs)
+ if outcome == "stream":
+ assert wire_spans == [] # Streaming spans end after consumption.
+ text = ""
+ async for chunk in result:
+ if chunk.choices:
+ text += chunk.choices[0].delta.content or ""
+ assert text == "hello"
+ else:
+ assert result.choices[0].message.content == "hello"
+
+ def run_sync():
+ with openai.OpenAI(
+ **client_kwargs,
+ http_client=httpx.Client(transport=transport, trust_env=False),
+ ) as client:
+ result = client.chat.completions.create(**kwargs)
+ if outcome == "stream":
+ assert wire_spans == []
+ assert "".join(
+ chunk.choices[0].delta.content or ""
+ for chunk in result if chunk.choices
+ ) == "hello"
+ else:
+ assert result.choices[0].message.content == "hello"
+
+ def run():
+ if use_async:
+ asyncio.run(run_async())
+ else:
+ run_sync()
+
+ if outcome == "error":
+ with pytest.raises(openai.AuthenticationError):
+ run()
+ else:
+ run()
+
+ assert len(wire_spans) == 1 # No duplicate provider or SDK spans.
+ span = wire_spans[0]
+ attrs = {attribute.key: attribute.value for attribute in span.attributes}
+ assert attrs["gen_ai.provider.name"].string_value == "cometapi"
+ assert attrs["gen_ai.request.model"].string_value == (
+ RESPONSE_MODEL if outcome == "success" else REQUEST_MODEL
+ )
+ assert span.status.code == (Status.STATUS_CODE_ERROR if outcome == "error" else Status.STATUS_CODE_OK)
+ if outcome != "error":
+ assert attrs["output.value"].string_value == "hello"
+ assert attrs["gen_ai.usage.input_tokens"].int_value == 5
+ assert attrs["gen_ai.usage.output_tokens"].int_value == 2
diff --git a/python/frameworks/openai/tests/test_novita_provider.py b/python/frameworks/openai/tests/test_novita_provider.py
new file mode 100644
index 000000000..e1339b4f6
--- /dev/null
+++ b/python/frameworks/openai/tests/test_novita_provider.py
@@ -0,0 +1,243 @@
+"""Novita uses the shared OpenAI instrumentor, not a separate SDK wrapper.
+
+Vendor traffic is synthetic. Traces cross a localhost OTLP/HTTP protobuf wire
+before assertions, covering sync/async success, streams, errors and look-alikes.
+"""
+
+import asyncio
+import json
+import os
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from queue import Queue
+from threading import Thread
+
+import httpx
+import openai
+import pytest
+import requests
+from fi_instrumentation import TraceConfig
+from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
+from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest
+from opentelemetry.proto.trace.v1.trace_pb2 import Status
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+
+from traceai_openai import OpenAIInstrumentor
+from traceai_openai._providers import provider_from_host
+
+from .test_openai_compatible_spans import (
+ ANSWER,
+ REQUEST_MODEL,
+ RESPONSE_MODEL,
+ async_client,
+ chat_completion,
+ chat_stream,
+ client,
+ unauthorized,
+)
+
+
+PROMPT = "synthetic-novita-private-prompt"
+
+
+@pytest.mark.parametrize("host,expected", [
+ ("api.novita.ai", "novita"),
+ ("API.NOVITA.AI.", "novita"),
+ ("novita.ai", "openai"),
+ ("proxy.api.novita.ai", "openai"),
+ ("api.novita.ai.evil.example", "openai"),
+ ("notapi.novita.ai", "openai"),
+ ("api.novita-ai.example", "openai"),
+ # The resolver accepts a hostname, not a URL or authority. The SDK extracts
+ # the host first; schemes and ports on a genuine Novita URL do not change it.
+ ("https://api.novita.ai", "openai"),
+ ("http://api.novita.ai", "openai"),
+ ("api.novita.ai:443", "openai"),
+ ("api.novita.ai:8443", "openai"),
+ ("api.novita.ai@evil.example", "openai"),
+ (None, "openai"),
+ ("", "openai"),
+ (443, "openai"),
+])
+def test_novita_host_boundaries(host, expected):
+ assert provider_from_host(host) == expected
+
+
+@pytest.fixture(scope="module")
+def otlp_receiver():
+ received = Queue()
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_POST(self):
+ body = self.rfile.read(int(self.headers["Content-Length"]))
+ received.put((self.path, self.headers["Content-Type"], body))
+ self.send_response(200)
+ self.send_header("Content-Type", "application/x-protobuf")
+ self.send_header("Content-Length", "0")
+ self.end_headers()
+
+ def log_message(self, *_args):
+ pass
+
+ server = HTTPServer(("127.0.0.1", 0), Handler)
+ worker = Thread(target=server.serve_forever, daemon=True)
+ worker.start()
+ try:
+ yield f"http://127.0.0.1:{server.server_port}/v1/traces", received
+ finally:
+ server.shutdown()
+ worker.join(timeout=5)
+ server.server_close()
+
+
+@pytest.fixture
+def wire_trace(otlp_receiver, monkeypatch, hidden):
+ # Keep credentials, telemetry destinations and privacy flags synthetic.
+ for name in tuple(os.environ):
+ if name.startswith(("FI_", "OTEL_", "OPENAI_")):
+ monkeypatch.delenv(name)
+ endpoint, received = otlp_receiver
+ assert received.empty()
+ session = requests.Session()
+ session.trust_env = False
+ exporter = OTLPSpanExporter(endpoint=endpoint, session=session, timeout=5)
+ provider = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+ instrumentor = OpenAIInstrumentor()
+ config = TraceConfig(
+ hide_inputs=True, hide_outputs=True, hide_llm_invocation_parameters=True,
+ ) if hidden else TraceConfig()
+ instrumentor.instrument(tracer_provider=provider, config=config)
+ try:
+ yield received
+ finally:
+ instrumentor.uninstrument()
+ provider.shutdown()
+
+
+@pytest.mark.parametrize("base_url,expected_provider", [
+ ("https://api.novita.ai/openai/v1", "novita"),
+ ("https://API.NOVITA.AI./openai/v1", "novita"),
+ ("https://api.novita.ai:443/openai/v1", "novita"),
+ # Match existing host-only mappings: a port or HTTP scheme is not a new host.
+ ("https://api.novita.ai:8443/openai/v1", "novita"),
+ ("http://api.novita.ai:8080/openai/v1", "novita"),
+ ("https://api.novita.ai.evil.example:8443/openai/v1", "openai"),
+ ("http://proxy.api.novita.ai:8080/openai/v1", "openai"),
+ ("https://api.novita.ai@evil.example/openai/v1", "openai"),
+ ("https://api.novita.ai.customer.example/openai/v1", "openai"),
+ ("https://notapi.novita.ai/openai/v1", "openai"),
+ ("https://proxy.api.novita.ai/openai/v1", "openai"),
+ ("https://api.novita-ai.example/openai/v1", "openai"),
+ ("https://llm-proxy.customer.example/openai/v1", "openai"),
+ ("https://api.openai.com/openai/v1", "openai"),
+])
+@pytest.mark.parametrize("outcome", ["success", "stream", "stream-usage", "error"])
+@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"])
+@pytest.mark.parametrize("hidden", [False, True], ids=["default", "hidden"])
+def test_novita_provider_over_otlp(wire_trace, base_url, expected_provider, outcome, use_async, hidden):
+ calls = []
+ streaming = outcome.startswith("stream")
+
+ def handler(request):
+ assert request.url.path == "/openai/v1/chat/completions"
+ body = json.loads(request.content)
+ assert body["model"] == REQUEST_MODEL
+ assert body.get("stream", False) == streaming
+ calls.append(request.url.host)
+ if outcome == "error":
+ return unauthorized(request)
+ if streaming:
+ response = chat_stream()
+ if outcome == "stream-usage":
+ assert body["stream_options"] == {"include_usage": True}
+ usage = {
+ "id": "c", "object": "chat.completion.chunk", "created": 1,
+ "model": RESPONSE_MODEL, "choices": [],
+ "usage": {"prompt_tokens": 5, "completion_tokens": 2, "total_tokens": 7},
+ }
+ content = response.content.replace(
+ b"data: [DONE]", f"data: {json.dumps(usage)}\n\ndata: [DONE]".encode(),
+ )
+ return httpx.Response(200, headers=response.headers, content=content)
+ return response
+ return httpx.Response(200, json=chat_completion())
+
+ kwargs = {
+ "model": REQUEST_MODEL,
+ "messages": [{"role": "user", "content": PROMPT}],
+ "max_tokens": 128,
+ "stream": streaming,
+ }
+ if outcome == "stream-usage":
+ kwargs["stream_options"] = {"include_usage": True}
+
+ async def run_async():
+ async with async_client(handler, base_url=base_url) as sdk:
+ response = await sdk.chat.completions.create(**kwargs)
+ if streaming:
+ text = []
+ async for chunk in response:
+ text.extend(choice.delta.content or "" for choice in chunk.choices)
+ assert "".join(text) == ANSWER
+ else:
+ assert response.choices[0].message.content == ANSWER
+
+ def run_sync():
+ with client(handler, base_url=base_url) as sdk:
+ response = sdk.chat.completions.create(**kwargs)
+ if streaming:
+ text = "".join(
+ choice.delta.content or "" for chunk in response for choice in chunk.choices
+ )
+ assert text == ANSWER
+ else:
+ assert response.choices[0].message.content == ANSWER
+
+ def run():
+ if use_async:
+ asyncio.run(run_async())
+ else:
+ run_sync()
+
+ if outcome == "error":
+ with pytest.raises(openai.AuthenticationError):
+ run()
+ else:
+ run()
+
+ assert calls == [httpx.URL(base_url).host]
+ path, content_type, payload = wire_trace.get(timeout=5)
+ assert path == "/v1/traces"
+ assert content_type == "application/x-protobuf"
+ message = ExportTraceServiceRequest.FromString(payload)
+ spans = [span for resource in message.resource_spans
+ for scope in resource.scope_spans for span in scope.spans]
+ assert len(spans) == 1
+ assert wire_trace.empty(), "The shared instrumentor must not duplicate spans"
+ span = spans[0]
+ attrs = {item.key: getattr(item.value, item.value.WhichOneof("value"))
+ for item in span.attributes}
+ assert attrs["gen_ai.provider.name"] == expected_provider
+ # This instrumentor emits the modern provider field, not the legacy system.
+ assert "gen_ai.system" not in attrs
+ assert attrs["gen_ai.request.model"] == (
+ RESPONSE_MODEL if outcome == "success" else REQUEST_MODEL
+ )
+ assert attrs["gen_ai.span.kind"] == "LLM"
+ assert span.status.code == (
+ Status.STATUS_CODE_ERROR if outcome == "error" else Status.STATUS_CODE_OK
+ )
+ if outcome in ("success", "stream-usage"):
+ assert attrs["gen_ai.usage.input_tokens"] == 5
+ assert attrs["gen_ai.usage.output_tokens"] == 2
+ assert attrs["gen_ai.usage.total_tokens"] == 7
+ else:
+ assert not any(key.startswith("gen_ai.usage.") for key in attrs)
+ if hidden:
+ assert PROMPT.encode() not in payload
+ assert ANSWER.encode() not in payload
+ assert "gen_ai.request.parameters" not in attrs
+ elif streaming:
+ assert attrs["output.value"] == ANSWER
+ assert b"test-vendor-key" not in payload
diff --git a/python/frameworks/openai/traceai_openai/_providers.py b/python/frameworks/openai/traceai_openai/_providers.py
index fbe79a946..9acdb2210 100644
--- a/python/frameworks/openai/traceai_openai/_providers.py
+++ b/python/frameworks/openai/traceai_openai/_providers.py
@@ -20,7 +20,9 @@
"ollama.com": "ollama",
"generativelanguage.googleapis.com": FiLLMProviderValues.GOOGLE.value,
"api.anthropic.com": FiLLMProviderValues.ANTHROPIC.value,
+ "api.cometapi.com": "cometapi",
"api.mistral.ai": FiLLMProviderValues.MISTRALAI.value,
+ "api.novita.ai": "novita",
"api.deepseek.com": FiLLMProviderValues.DEEPSEEK.value,
"api.x.ai": FiLLMProviderValues.XAI.value,
"api.z.ai": "zai",
diff --git a/python/frameworks/openai/traceai_openai/version.py b/python/frameworks/openai/traceai_openai/version.py
index 2ae9a1c63..af77e1197 100644
--- a/python/frameworks/openai/traceai_openai/version.py
+++ b/python/frameworks/openai/traceai_openai/version.py
@@ -1 +1 @@
-__version__ = "0.1.13" # x-release-please-version
+__version__ = "0.1.14" # x-release-please-version
diff --git a/python/pyproject.toml b/python/pyproject.toml
index 8e4bfbc7f..29b68e589 100644
--- a/python/pyproject.toml
+++ b/python/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "fi-instrumentation-otel"
-version = "1.3.0"
+version = "1.3.1"
description = "OpenTelemetry tracing for AI applications: tracer setup, span helpers, exporters, and semantic conventions for Future AGI."
authors = ["Future AGI "]
readme = "README.md"
diff --git a/python/tests/test_export_credentials_wire.py b/python/tests/test_export_credentials_wire.py
new file mode 100644
index 000000000..a4fbe3186
--- /dev/null
+++ b/python/tests/test_export_credentials_wire.py
@@ -0,0 +1,93 @@
+"""Issue #155: credentials as they reach a local collector on the wire (synthetic values only)."""
+import http.server
+import threading
+
+import pytest
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+
+from fi_instrumentation import otel
+
+
+class _Collector(http.server.BaseHTTPRequestHandler):
+ requests = []
+
+ def do_POST(self): # noqa: N802 - http.server API
+ length = int(self.headers.get("Content-Length") or 0)
+ self.rfile.read(length)
+ type(self).requests.append((self.path, [(k.lower(), v) for k, v in self.headers.items()]))
+ self.send_response(200)
+ self.send_header("Content-Length", "0")
+ self.end_headers()
+
+ def log_message(self, *args):
+ pass
+
+
+@pytest.fixture
+def collector(monkeypatch):
+ _Collector.requests = []
+ server = http.server.HTTPServer(("127.0.0.1", 0), _Collector)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ monkeypatch.setenv("FI_BASE_URL", f"http://127.0.0.1:{server.server_port}")
+ monkeypatch.setenv("FI_API_KEY", "synthetic-env-key")
+ monkeypatch.setenv("FI_SECRET_KEY", "synthetic-env-secret")
+ try:
+ yield _Collector.requests
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
+def _export_one_span(exporter):
+ provider = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+ with provider.get_tracer("issue-155").start_as_current_span("export-check"):
+ pass
+ provider.shutdown()
+
+
+def _credential_headers(headers):
+ return [(k, v) for k, v in headers if k in ("authorization", "x-api-key", "x-secret-key")]
+
+
+@pytest.mark.parametrize("explicit", [None, {"Authorization": ""}, {"Authorization": " "}])
+def test_env_credentials_reach_the_collector_once(collector, explicit):
+ _export_one_span(otel.HTTPSpanExporter(headers=explicit))
+ assert len(collector) == 1
+ path, headers = collector[0]
+ assert path == "/tracer/v1/traces"
+ assert sorted(_credential_headers(headers)) == [
+ ("x-api-key", "synthetic-env-key"),
+ ("x-secret-key", "synthetic-env-secret"),
+ ]
+
+
+def test_explicit_keys_are_sent_once_without_env_copies(collector):
+ _export_one_span(otel.HTTPSpanExporter(headers={
+ "x-api-key": "synthetic-explicit-key",
+ "X-Secret-Key": "synthetic-explicit-secret",
+ }))
+ assert len(collector) == 1
+ _, headers = collector[0]
+ assert sorted(_credential_headers(headers)) == [
+ ("x-api-key", "synthetic-explicit-key"),
+ ("x-secret-key", "synthetic-explicit-secret"),
+ ]
+
+
+def test_register_exports_with_env_credentials(collector):
+ provider = otel.register(project_name="issue-155-wire", batch=False)
+ try:
+ with provider.get_tracer("issue-155").start_as_current_span("register-check"):
+ pass
+ finally:
+ provider.shutdown()
+ exports = [r for r in collector if r[0] == "/tracer/v1/traces"]
+ assert exports, collector
+ for _, headers in exports:
+ assert sorted(_credential_headers(headers)) == [
+ ("x-api-key", "synthetic-env-key"),
+ ("x-secret-key", "synthetic-env-secret"),
+ ]
diff --git a/python/tests/test_exporter_endpoint_r3.py b/python/tests/test_exporter_endpoint_r3.py
index 23ed57a6e..cf92403c8 100644
--- a/python/tests/test_exporter_endpoint_r3.py
+++ b/python/tests/test_exporter_endpoint_r3.py
@@ -90,3 +90,67 @@ def test_binding_errors_are_preserved():
otel.GRPCSpanExporter("localhost:1", endpoint="localhost:2")
with pytest.raises(TypeError):
otel.HTTPSpanExporter("http://localhost:1", endpoint="http://localhost:2")
+
+
+def _captured_headers(transport, monkeypatch, env, headers):
+ monkeypatch.setattr(otel, "get_env_fi_auth_header", lambda: env)
+ cls, base = (otel.GRPCSpanExporter, otel._GRPCSpanExporter) if transport == "grpc" else (otel.HTTPSpanExporter, otel._HTTPSpanExporter)
+ captured = {}
+ signature = inspect.signature(base)
+ init_signature = inspect.signature(base.__init__)
+ def capture(self, *args, **kwargs):
+ captured.update(signature.bind_partial(*args, **kwargs).arguments)
+ capture.__signature__ = init_signature
+ with patch.object(base, "__init__", capture):
+ cls(endpoint="http://local.invalid:4317", headers=headers)
+ return captured["headers"]
+
+
+ENV_PAIR = {"X-Api-Key": "synthetic-env-key", "X-Secret-Key": "synthetic-env-secret"}
+
+
+@pytest.mark.parametrize("transport", ["grpc", "http"])
+@pytest.mark.parametrize("empty", ["", " ", None])
+def test_empty_authorization_does_not_hide_env_credentials(transport, empty, monkeypatch):
+ """Issue #155: an empty Authorization header is not a credential."""
+ headers = _captured_headers(transport, monkeypatch, ENV_PAIR, {"Authorization": empty, "X-Custom": "value"})
+ assert headers == {"x-api-key": "synthetic-env-key", "x-secret-key": "synthetic-env-secret", "x-custom": "value"}
+
+
+@pytest.mark.parametrize("transport", ["grpc", "http"])
+def test_explicit_fi_keys_win_without_case_variant_duplicates(transport, monkeypatch):
+ """Issue #155: explicit X-Api-Key/X-Secret-Key are sent once and never mixed with the env pair."""
+ headers = _captured_headers(transport, monkeypatch, ENV_PAIR, {"x-api-key": "synthetic-explicit-key", "X-Secret-Key": "synthetic-explicit-secret"})
+ assert headers == {"x-api-key": "synthetic-explicit-key", "x-secret-key": "synthetic-explicit-secret"}
+ assert len({k.lower() for k in headers}) == len(headers)
+
+
+@pytest.mark.parametrize("transport", ["grpc", "http"])
+def test_env_pair_is_lower_cased_and_added_once(transport, monkeypatch):
+ headers = _captured_headers(transport, monkeypatch, ENV_PAIR, None)
+ assert headers == {"x-api-key": "synthetic-env-key", "x-secret-key": "synthetic-env-secret"}
+
+
+@pytest.mark.parametrize("transport", ["grpc", "http"])
+def test_no_credentials_anywhere_sends_no_headers(transport, monkeypatch):
+ assert _captured_headers(transport, monkeypatch, None, {"Authorization": ""}) is None
+
+
+@pytest.mark.parametrize("transport", ["grpc", "http"])
+def test_empty_case_variant_does_not_erase_an_explicit_credential(transport, monkeypatch):
+ """A later empty duplicate must not drop an earlier non-empty Authorization and pull in env keys."""
+ headers = _captured_headers(transport, monkeypatch, ENV_PAIR, {"Authorization": "Bearer synthetic", "authorization": ""})
+ assert headers == {"authorization": "Bearer synthetic"}
+
+
+@pytest.mark.parametrize("transport", ["grpc", "http"])
+@pytest.mark.parametrize("empty", [b"", b" "])
+def test_empty_bytes_credential_does_not_hide_env_credentials(transport, empty, monkeypatch):
+ headers = _captured_headers(transport, monkeypatch, ENV_PAIR, {"Authorization": empty})
+ assert headers == {"x-api-key": "synthetic-env-key", "x-secret-key": "synthetic-env-secret"}
+
+
+@pytest.mark.parametrize("transport", ["grpc", "http"])
+def test_non_empty_bytes_credential_is_kept(transport, monkeypatch):
+ headers = _captured_headers(transport, monkeypatch, ENV_PAIR, {"Authorization": b"Bearer synthetic"})
+ assert headers == {"authorization": b"Bearer synthetic"}