From d9bbcc7dc3eb154870fce8994300c7f89809ed12 Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Fri, 27 Nov 2026 00:32:51 +0000 Subject: [PATCH 1/3] Fix the formatting of `openai_client_test.cpp` The format check of CI (clang-format 18) has been failing on main since https://github.com/ClickHouse/ai-sdk-cpp/pull/62. Co-Authored-By: Claude Opus 5.5 --- src/providers/openai/openai_stream.cpp | 9 +++++---- tests/unit/openai_client_test.cpp | 15 +++++++-------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/providers/openai/openai_stream.cpp b/src/providers/openai/openai_stream.cpp index bf3ce39..105e9c8 100644 --- a/src/providers/openai/openai_stream.cpp +++ b/src/providers/openai/openai_stream.cpp @@ -45,13 +45,14 @@ void OpenAIStreamImpl::process_sse_line(std::string_view line) { if (delta.contains("reasoning_content") && !delta["reasoning_content"].is_null()) { - std::string content = delta["reasoning_content"].get(); ai::logger::log_debug("Received reasoning_content chunk - length: {}", content.length()); - //TODO: currently not passing content, needs revamping of StreamEvent constructor - push_event(StreamEvent(StreamEventType::kStreamEventTypeReasoningDelta)); - } + // TODO: currently not passing content, needs revamping of StreamEvent + // constructor + push_event( + StreamEvent(StreamEventType::kStreamEventTypeReasoningDelta)); + } if (delta.contains("tool_calls") && delta["tool_calls"].is_array()) { for (const auto& fragment : delta["tool_calls"]) { diff --git a/tests/unit/openai_client_test.cpp b/tests/unit/openai_client_test.cpp index 3cac86b..73525cb 100644 --- a/tests/unit/openai_client_test.cpp +++ b/tests/unit/openai_client_test.cpp @@ -154,20 +154,19 @@ TEST_F(OpenAIClientTest, Gpt5FamilyUsesChatCompletionsCompatibleReasoning) { openai::OpenAIRequestBuilder builder; // GPT-5.1 and later accept "none" and reject "minimal". - for (const auto* model : - {openai::models::kGpt56, openai::models::kGpt56Luna, - openai::models::kGpt55, openai::models::kGpt54, - openai::models::kGpt54Mini, openai::models::kGpt54Nano, "gpt-5.2", - "gpt-5.1"}) { + for (const auto* model : {openai::models::kGpt56, openai::models::kGpt56Luna, + openai::models::kGpt55, openai::models::kGpt54, + openai::models::kGpt54Mini, + openai::models::kGpt54Nano, "gpt-5.2", "gpt-5.1"}) { GenerateOptions options(model, "Use a tool"); EXPECT_EQ(builder.build_request_json(options)["reasoning_effort"], "none") << model; } // The original GPT-5 models reject "none"; they get the "minimal" floor. - for (const auto* model : {"gpt-5", "gpt-5-2025-08-07", - openai::models::kGpt5Mini, - openai::models::kGpt5Nano}) { + for (const auto* model : + {"gpt-5", "gpt-5-2025-08-07", openai::models::kGpt5Mini, + openai::models::kGpt5Nano}) { GenerateOptions options(model, "Use a tool"); EXPECT_EQ(builder.build_request_json(options)["reasoning_effort"], "minimal") From 2ffc50a05f1f138fb988d0bbcd37d040d126f784 Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Fri, 27 Nov 2026 01:17:22 +0000 Subject: [PATCH 2/3] Export Langfuse traces with OTLP for Langfuse v4 Langfuse Cloud is v4-only since 2026-11-16, and v4 rejects every event type except `score-create` on the legacy `POST /api/public/ingestion` endpoint that the tracer used. Traces and observations must go to the OpenTelemetry endpoint `POST /api/public/otel/v1/traces`. The tracer now sends an OTLP/HTTP JSON `ExportTraceServiceRequest` (no protobuf dependency) with Basic auth and `x-langfuse-ingestion-version: 4`. A trace is a root span that carries the trace input/output; generations are its children and tool calls are children of the generation, as before. The trace-level attributes (`langfuse.trace.name`, `langfuse.user.id`, `langfuse.session.id`, `langfuse.trace.tags`, `langfuse.trace.metadata`, `langfuse.release`, `langfuse.environment`) are set on every span, as Langfuse v4 requires. Generations carry the model, model parameters, usage (`langfuse.observation.usage_details` plus `gen_ai.usage.*`) and metadata; failures set `langfuse.observation.level` = `ERROR`, the status message and the OTLP span status. Rejected spans reported in `partialSuccess` count as a failed export. Self-hosted Langfuse supports the OTLP endpoint since v3.22.0, so the legacy path is removed without a fallback. API changes: `Tracer::send_batch` (legacy events) is replaced by `Tracer::export_spans` (OTLP spans); `Trace::id` is now a 32-hex OpenTelemetry trace id; new `Trace::new_trace_id`, `Trace::new_span_id`, `Trace::to_unix_nanos`. A generation without `finish_generation` and unfinished tool spans are now closed at `Trace::end` instead of being dropped or left open. Closes: https://github.com/ClickHouse/ai-sdk-cpp/issues/59 Co-Authored-By: Claude Opus 5.5 --- .env.local.example | 2 +- examples/langfuse_tracing.cpp | 4 +- include/ai/langfuse.h | 81 +++-- src/langfuse/tracer.cpp | 457 ++++++++++++++++++---------- tests/CMakeLists.txt | 1 + tests/unit/langfuse_tracer_test.cpp | 393 ++++++++++++++++++++++++ 6 files changed, 762 insertions(+), 176 deletions(-) create mode 100644 tests/unit/langfuse_tracer_test.cpp diff --git a/.env.local.example b/.env.local.example index a4bc539..6edf1ad 100644 --- a/.env.local.example +++ b/.env.local.example @@ -15,6 +15,6 @@ LANGFUSE_SECRET_KEY= # --- Langfuse host (optional) --- # EU cloud (default): https://cloud.langfuse.com # US cloud: https://us.cloud.langfuse.com -# Self-hosted (langfuse/ docker-compose): http://localhost:3000 +# Self-hosted (langfuse/ docker-compose, v3.22.0 or later): http://localhost:3000 # The example also accepts LANGFUSE_BASE_URL as a synonym. LANGFUSE_HOST=https://cloud.langfuse.com diff --git a/examples/langfuse_tracing.cpp b/examples/langfuse_tracing.cpp index 844b2e7..e05e553 100644 --- a/examples/langfuse_tracing.cpp +++ b/examples/langfuse_tracing.cpp @@ -3,7 +3,9 @@ * * Demonstrates how to wrap an `ai::Client::generate_text` call (with tools and * multi-step) so the LLM call and each tool execution show up as a trace in - * Langfuse. + * Langfuse. Spans are exported with OTLP/HTTP to Langfuse's + * `/api/public/otel/v1/traces` endpoint (Langfuse Cloud, or self-hosted + * Langfuse v3.22.0 or later). * * Required env: * OPENAI_API_KEY (or use ai::anthropic instead) diff --git a/include/ai/langfuse.h b/include/ai/langfuse.h index f14765f..6043f9d 100644 --- a/include/ai/langfuse.h +++ b/include/ai/langfuse.h @@ -3,7 +3,15 @@ /// Langfuse tracing for ai-sdk-cpp. /// /// Records traces, generations, and tool spans for `ai::Client::generate_text` -/// calls and POSTs them to Langfuse's `/api/public/ingestion` endpoint. +/// calls and exports them as OpenTelemetry spans (OTLP/HTTP with JSON +/// encoding) to Langfuse's `/api/public/otel/v1/traces` endpoint. This is the +/// ingestion API of Langfuse v4 (Langfuse Cloud) and is also accepted by +/// self-hosted Langfuse v3.22.0 and later. +/// +/// Each trace is exported as a root span carrying the trace-level attributes +/// (name, user, session, tags, metadata, input, output); generations and tool +/// calls are its descendants. Trace-level attributes are propagated to every +/// span, as Langfuse v4 requires for filtering. /// /// Usage: /// ```cpp @@ -64,7 +72,7 @@ struct Config { /// Environment to attach to all traces (Langfuse default is "default"). std::string environment = "default"; - /// HTTP timeouts for the ingestion request. + /// HTTP timeouts for the OTLP export request. int connection_timeout_sec = 10; int read_timeout_sec = 30; @@ -107,14 +115,16 @@ class Tracer { std::shared_ptr start_trace(const std::string& name, TraceOptions opts = {}); - /// POST a batch of ingestion events to Langfuse. Returns true on 2xx. - /// Public so advanced callers can build their own event batches; most users - /// should rely on `Trace::end()`. - bool send_batch(const JsonValue& events); + /// POST a JSON array of OTLP spans (the JSON encoding of + /// `opentelemetry.proto.trace.v1.Span`) to Langfuse's OTLP endpoint, wrapped + /// in a single `resourceSpans` / `scopeSpans` entry. Returns true on 2xx + /// without rejected spans. Public so advanced callers can export their own + /// spans; most users should rely on `Trace::end()`. + bool export_spans(const JsonValue& spans); private: // Lazily constructed httplib client + base path + Basic-auth header. Cached - // to avoid TLS handshake per send_batch call. Guarded by mu_. + // to avoid TLS handshake per export_spans call. Guarded by mu_. struct HttpState; HttpState& http_state(); @@ -123,14 +133,16 @@ class Tracer { std::unique_ptr http_; }; -/// A Trace owns a list of pending ingestion events and writes them all to -/// Langfuse on `end()`. Use one Trace per logical request (per call to a +/// A Trace owns a list of pending spans and exports them all to Langfuse on +/// `end()`. Use one Trace per logical request (per call to a /// user-facing API like `generateSQL`). /// /// Methods are thread-safe: callbacks fired from generate_text's worker /// threads can record into the same Trace concurrently. class Trace : public std::enable_shared_from_this { public: + /// `id` is the OpenTelemetry trace id: 32 lowercase hex characters. It is + /// also the trace id shown by Langfuse. Trace(Tracer& tracer, std::string id, std::string name); const std::string& id() const { return id_; } @@ -140,11 +152,13 @@ class Trace : public std::enable_shared_from_this { void set_output(JsonValue output); void set_user_id(std::string user_id); void set_session_id(std::string session_id); + /// Trace metadata; should be a JSON object (Langfuse ignores other values). void set_metadata(JsonValue metadata); void add_tag(std::string tag); /// Attach Langfuse callbacks to `options`. Records: - /// - a parent generation observation (model, modelParameters, input) + /// - a generation observation (model, model parameters, input) as a child + /// of the trace's root span /// - one tool span per tool call (input=args, output=result) /// /// Existing callbacks on `options` are preserved (chained, called after the @@ -157,24 +171,37 @@ class Trace : public std::enable_shared_from_this { /// `instrument()`-ed generation. Safe to call once per `instrument()`. void finish_generation(const GenerateResult& result); - /// Flush all accumulated events to Langfuse. Idempotent; subsequent calls + /// Export all accumulated spans to Langfuse. Idempotent; subsequent calls /// are no-ops. After end(), further set_* / instrument / finish_generation - /// calls become no-ops to prevent silently dropping events. Returns true on + /// calls become no-ops to prevent silently dropping spans. A generation + /// without `finish_generation()` and tool spans without a finish callback + /// are closed at the time of `end()`. Returns true on /// success (or when Config::error_policy is kBestEffort and the request /// failed). bool end(); - /// Generate a new UUID v4. Exposed so callers (and `Tracer::start_trace`) - /// can mint trace ids without re-implementing UUID generation. + /// Generate a new UUID v4. Trace and span ids are OpenTelemetry ids; mint + /// them with `new_trace_id` and `new_span_id`. static std::string new_uuid(); + /// Generate a random OpenTelemetry trace id (32 lowercase hex characters). + /// `Tracer::start_trace` uses it for `Trace::id`. + static std::string new_trace_id(); + + /// Generate a random OpenTelemetry span id (16 lowercase hex characters). + static std::string new_span_id(); + + /// Format a system_clock time_point as unix nanoseconds in a decimal string, + /// the OTLP/JSON encoding of `startTimeUnixNano` / `endTimeUnixNano`. + static std::string to_unix_nanos(std::chrono::system_clock::time_point t); + /// Format a system_clock time_point as RFC 3339 / ISO 8601 with millisecond /// precision and trailing 'Z'. Public so callers can stamp custom events. static std::string to_iso8601(std::chrono::system_clock::time_point t); private: struct PendingGeneration { - std::string id; + std::string id; // OpenTelemetry span id std::string name; std::chrono::system_clock::time_point start_time; JsonValue input; @@ -188,9 +215,19 @@ class Trace : public std::enable_shared_from_this { // Closes a tool-call span. Called from on_tool_call_finish. void record_tool_call_finish(const ToolResult& result); - // Builds and pushes the trace-create event with the current - // input/output/metadata/tags. - JsonValue build_trace_event() const; + // Builds the span of `active_generation_` ending at `end_nanos` and marks + // the generation finalized. `result` (output, usage, status) may be null + // for a generation that was never finished. Caller must hold mu_. + JsonValue build_generation_span(const std::string& end_nanos, + const GenerateResult* result); + + // Builds the root span that represents the trace itself, with the current + // input/output. Caller must hold mu_. + JsonValue build_root_span(const std::string& end_nanos) const; + + // Adds the attributes shared by all spans of the trace (name, user, + // session, tags, metadata, release, environment). Caller must hold mu_. + void add_trace_level_attributes(JsonValue& span) const; Tracer& tracer_; std::string id_; @@ -198,6 +235,8 @@ class Trace : public std::enable_shared_from_this { mutable std::mutex mu_; std::chrono::system_clock::time_point trace_start_; + // Span id of the root span that represents the trace itself. + std::string root_span_id_; std::optional input_; std::optional output_; std::optional user_id_; @@ -205,14 +244,14 @@ class Trace : public std::enable_shared_from_this { std::optional metadata_; std::vector tags_; - // Pending observation events accumulated until `end()` flushes them. + // Pending OTLP spans accumulated until `end()` exports them. std::vector events_; // Active generation, set by instrument() and closed by finish_generation(). std::optional active_generation_; - // Map tool_call_id -> open span event index in events_, used to update - // span end_time / output when the tool finishes. + // Map tool_call_id -> open span index in events_, used to set the span's + // end time / output when the tool finishes. std::unordered_map open_tool_spans_; std::atomic ended_{false}; diff --git a/src/langfuse/tracer.cpp b/src/langfuse/tracer.cpp index 503802f..83ba051 100644 --- a/src/langfuse/tracer.cpp +++ b/src/langfuse/tracer.cpp @@ -1,6 +1,7 @@ #include "ai/langfuse.h" #include "ai/logger.h" +#include #include #include #include @@ -12,18 +13,55 @@ namespace langfuse { namespace { -constexpr const char* kIngestionPath = "/api/public/ingestion"; - -// Langfuse ingestion event type discriminators -// (packages/shared/src/server/ingestion/types.ts::eventTypes). -constexpr const char* kEventTraceCreate = "trace-create"; -constexpr const char* kEventSpanCreate = "span-create"; -constexpr const char* kEventSpanUpdate = "span-update"; -constexpr const char* kEventGenerationCreate = "generation-create"; - -constexpr const char* kLevelDefault = "DEFAULT"; +// OTLP/HTTP traces endpoint of Langfuse: the only ingestion API of Langfuse v4 +// (Langfuse Cloud) for traces and observations; also available in self-hosted +// Langfuse since v3.22.0. +constexpr const char* kOtlpTracesPath = "/api/public/otel/v1/traces"; + +// Tells Langfuse v4 that every span carries the trace-level attributes +// (propagated client side), so spans are visible without the delay of the +// v3-to-v4 transition pipeline. +constexpr const char* kIngestionVersionHeader = "x-langfuse-ingestion-version"; +constexpr const char* kIngestionVersion = "4"; + +constexpr const char* kInstrumentationScope = "ai-sdk-cpp"; + +// Langfuse OpenTelemetry attribute names +// (packages/shared/src/server/otel/attributes.ts). +constexpr const char* kAttrTraceName = "langfuse.trace.name"; +constexpr const char* kAttrTraceInput = "langfuse.trace.input"; +constexpr const char* kAttrTraceOutput = "langfuse.trace.output"; +constexpr const char* kAttrTraceTags = "langfuse.trace.tags"; +constexpr const char* kAttrTraceMetadata = "langfuse.trace.metadata"; +constexpr const char* kAttrUserId = "langfuse.user.id"; +constexpr const char* kAttrSessionId = "langfuse.session.id"; +constexpr const char* kAttrRelease = "langfuse.release"; +constexpr const char* kAttrEnvironment = "langfuse.environment"; +constexpr const char* kAttrObservationType = "langfuse.observation.type"; +constexpr const char* kAttrObservationInput = "langfuse.observation.input"; +constexpr const char* kAttrObservationOutput = "langfuse.observation.output"; +constexpr const char* kAttrObservationMetadata = + "langfuse.observation.metadata"; +constexpr const char* kAttrObservationLevel = "langfuse.observation.level"; +constexpr const char* kAttrObservationStatusMessage = + "langfuse.observation.status_message"; +constexpr const char* kAttrModelName = "langfuse.observation.model.name"; +constexpr const char* kAttrModelParameters = + "langfuse.observation.model.parameters"; +constexpr const char* kAttrUsageDetails = "langfuse.observation.usage_details"; +// OpenTelemetry GenAI semantic conventions, for other OTLP consumers. +constexpr const char* kAttrGenAiRequestModel = "gen_ai.request.model"; +constexpr const char* kAttrGenAiInputTokens = "gen_ai.usage.input_tokens"; +constexpr const char* kAttrGenAiOutputTokens = "gen_ai.usage.output_tokens"; + +constexpr const char* kObservationTypeSpan = "span"; +constexpr const char* kObservationTypeGeneration = "generation"; constexpr const char* kLevelError = "ERROR"; -constexpr const char* kUsageUnitTokens = "TOKENS"; + +// opentelemetry.proto.trace.v1.Span.SpanKind / Status.StatusCode. +constexpr int kSpanKindInternal = 1; +constexpr int kSpanKindClient = 3; +constexpr int kStatusCodeError = 2; // Strip the scheme prefix off a Langfuse host URL and return the leading // sub-path (everything after the host[:port], e.g. "/langfuse" if hosted under @@ -125,8 +163,90 @@ JsonValue messages_input_from(const GenerateOptions& options) { JsonValue usage_to_langfuse(const Usage& u) { return {{"input", u.prompt_tokens}, {"output", u.completion_tokens}, - {"total", u.total_tokens}, - {"unit", kUsageUnitTokens}}; + {"total", u.total_tokens}}; +} + +// Langfuse expects input/output/metadata attributes as strings holding JSON; +// plain strings are sent as is. +std::string to_attribute_string(const JsonValue& value) { + if (value.is_string()) + return value.get(); + return value.dump(); +} + +void add_attribute(JsonValue& span, const char* key, std::string value) { + span["attributes"].push_back( + {{"key", key}, {"value", {{"stringValue", std::move(value)}}}}); +} + +void add_attribute(JsonValue& span, const char* key, const JsonValue& value) { + add_attribute(span, key, to_attribute_string(value)); +} + +void add_attribute(JsonValue& span, const char* key, int64_t value) { + // OTLP/JSON encodes 64-bit integers as decimal strings. + span["attributes"].push_back( + {{"key", key}, {"value", {{"intValue", std::to_string(value)}}}}); +} + +void add_attribute(JsonValue& span, + const char* key, + const std::vector& values) { + JsonValue array = JsonValue::array(); + for (const auto& v : values) + array.push_back({{"stringValue", v}}); + span["attributes"].push_back( + {{"key", key}, {"value", {{"arrayValue", {{"values", array}}}}}}); +} + +JsonValue make_span(const std::string& trace_id, + const std::string& span_id, + const std::string& parent_span_id, + const std::string& name, + int kind, + const char* observation_type, + const std::string& start_nanos) { + JsonValue span; + span["traceId"] = trace_id; + span["spanId"] = span_id; + if (!parent_span_id.empty()) + span["parentSpanId"] = parent_span_id; + span["name"] = name; + span["kind"] = kind; + span["startTimeUnixNano"] = start_nanos; + span["attributes"] = JsonValue::array(); + add_attribute(span, kAttrObservationType, std::string(observation_type)); + return span; +} + +void mark_error(JsonValue& span, const std::string& message) { + add_attribute(span, kAttrObservationLevel, std::string(kLevelError)); + add_attribute(span, kAttrObservationStatusMessage, message); + span["status"] = {{"code", kStatusCodeError}, {"message", message}}; +} + +std::string random_hex_id(size_t bytes) { + static thread_local std::mt19937_64 engine{[] { + std::random_device rd; + return (static_cast(rd()) << 32) ^ rd(); + }()}; + static const char* kHex = "0123456789abcdef"; + std::string out(bytes * 2, '0'); + bool all_zero = true; + do { + for (size_t i = 0; i < bytes; i += 8) { + uint64_t r = engine(); + for (size_t j = 0; j < 8 && i + j < bytes; ++j) { + unsigned char b = static_cast(r >> (j * 8)); + out[(i + j) * 2] = kHex[b >> 4]; + out[(i + j) * 2 + 1] = kHex[b & 0xF]; + if (b != 0) + all_zero = false; + } + } + // An all-zero id is invalid in OpenTelemetry. + } while (all_zero); + return out; } } // namespace @@ -156,6 +276,7 @@ struct Tracer::HttpState { {"User-Agent", "ai-sdk-cpp-langfuse/0.1"}, {"X-Langfuse-Sdk-Name", "ai-sdk-cpp"}, {"X-Langfuse-Sdk-Variant", "ai-sdk-cpp"}, + {kIngestionVersionHeader, kIngestionVersion}, }; } }; @@ -181,7 +302,7 @@ Tracer::HttpState& Tracer::http_state() { std::shared_ptr Tracer::start_trace(const std::string& name, TraceOptions opts) { - auto trace = std::make_shared(*this, Trace::new_uuid(), name); + auto trace = std::make_shared(*this, Trace::new_trace_id(), name); if (opts.input) trace->set_input(std::move(*opts.input)); if (opts.output) @@ -197,38 +318,63 @@ std::shared_ptr Tracer::start_trace(const std::string& name, return trace; } -bool Tracer::send_batch(const JsonValue& events) { +bool Tracer::export_spans(const JsonValue& spans) { if (!is_valid()) { ai::logger::log_warn( "Langfuse tracer not configured (missing host/public_key/secret_key); " - "dropping {} events", - events.is_array() ? events.size() : 0); + "dropping {} spans", + spans.is_array() ? spans.size() : 0); return false; } + // ExportTraceServiceRequest + // (opentelemetry/proto/collector/trace/v1/trace_service.proto). + JsonValue resource_attributes = JsonValue::array(); + resource_attributes.push_back( + {{"key", "service.name"}, + {"value", {{"stringValue", kInstrumentationScope}}}}); JsonValue body; - body["batch"] = events; + body["resourceSpans"] = JsonValue::array(); + body["resourceSpans"].push_back( + {{"resource", {{"attributes", std::move(resource_attributes)}}}, + {"scopeSpans", + JsonValue::array({{{"scope", {{"name", kInstrumentationScope}}}, + {"spans", spans}}})}}); std::string serialized = body.dump(); std::lock_guard lock(mu_); auto& s = http_state(); - std::string path = s.base_path + kIngestionPath; + std::string path = s.base_path + kOtlpTracesPath; auto res = s.client.Post(path.c_str(), s.headers, serialized, "application/json"); if (!res) { - ai::logger::log_error("Langfuse ingestion failed: {}", + ai::logger::log_error("Langfuse OTLP export failed: {}", httplib::to_string(res.error())); return false; } - if (res->status >= 200 && res->status < 300) { - ai::logger::log_debug("Langfuse ingestion accepted ({}): {}", res->status, + if (res->status < 200 || res->status >= 300) { + ai::logger::log_error("Langfuse OTLP export non-2xx ({}): {}", res->status, res->body); - return true; + return false; + } + + // ExportTraceServiceResponse may report spans the server rejected. + auto response = JsonValue::parse(res->body, nullptr, false); + if (response.is_object() && response.contains("partialSuccess")) { + const auto& partial = response["partialSuccess"]; + // int64 rejectedSpans may be encoded as a number or a decimal string. + const auto rejected = partial.value("rejectedSpans", JsonValue(0)); + if ((rejected.is_number() && rejected.get() != 0) || + (rejected.is_string() && rejected.get() != "0")) { + ai::logger::log_error("Langfuse OTLP export rejected spans ({}): {}", + res->status, res->body); + return false; + } } - ai::logger::log_error("Langfuse ingestion non-2xx ({}): {}", res->status, + ai::logger::log_debug("Langfuse OTLP export accepted ({}): {}", res->status, res->body); - return false; + return true; } // --------------------------------------------------------------------------- @@ -239,7 +385,8 @@ Trace::Trace(Tracer& tracer, std::string id, std::string name) : tracer_(tracer), id_(std::move(id)), name_(std::move(name)), - trace_start_(std::chrono::system_clock::now()) {} + trace_start_(std::chrono::system_clock::now()), + root_span_id_(new_span_id()) {} void Trace::set_input(JsonValue input) { if (ended_.load()) @@ -289,7 +436,7 @@ void Trace::instrument(GenerateOptions& options, return; PendingGeneration gen; - gen.id = new_uuid(); + gen.id = new_span_id(); gen.name = generation_name; gen.start_time = std::chrono::system_clock::now(); gen.input = messages_input_from(options); @@ -298,6 +445,11 @@ void Trace::instrument(GenerateOptions& options, { std::lock_guard lock(mu_); + // A previous generation that was never finished is closed now, so that + // its tool spans keep their parent. + if (active_generation_ && !active_generation_->finalized) + events_.push_back(build_generation_span( + to_unix_nanos(std::chrono::system_clock::now()), nullptr)); active_generation_ = std::move(gen); } @@ -323,58 +475,21 @@ void Trace::instrument(GenerateOptions& options, }; } -namespace { - -// Build a span-create event body. Used for both tool-call starts (open span) -// and the synthetic span emitted in record_tool_call_finish's fallback path. -JsonValue make_span_create(const std::string& span_id, - const std::string& trace_id, - const std::string& parent_id, - const std::string& name, - const std::string& start_iso, - const JsonValue& input, - const std::string& environment) { - JsonValue body; - body["id"] = span_id; - body["traceId"] = trace_id; - body["name"] = name; - body["startTime"] = start_iso; - body["input"] = input; - body["environment"] = environment; - if (!parent_id.empty()) - body["parentObservationId"] = parent_id; - return body; -} - -JsonValue wrap_event(const char* type, - const std::string& timestamp, - JsonValue body) { - JsonValue event; - event["id"] = Trace::new_uuid(); - event["timestamp"] = timestamp; - event["type"] = type; - event["body"] = std::move(body); - return event; -} - -} // namespace - void Trace::record_tool_call_start(const ToolCall& call) { if (ended_.load()) return; - // One clock read per event: startTime and the envelope timestamp share it. - std::string ts = to_iso8601(std::chrono::system_clock::now()); + std::string now = to_unix_nanos(std::chrono::system_clock::now()); std::lock_guard lock(mu_); std::string parent_id = - active_generation_ ? active_generation_->id : std::string(); - JsonValue body = - make_span_create(new_uuid(), id_, parent_id, call.tool_name, ts, - call.arguments, tracer_.config().environment); + active_generation_ ? active_generation_->id : root_span_id_; + JsonValue span = make_span(id_, new_span_id(), parent_id, call.tool_name, + kSpanKindInternal, kObservationTypeSpan, now); + add_attribute(span, kAttrObservationInput, call.arguments); size_t idx = events_.size(); - events_.push_back(wrap_event(kEventSpanCreate, ts, std::move(body))); + events_.push_back(std::move(span)); open_tool_spans_[call.id] = idx; } @@ -382,43 +497,33 @@ void Trace::record_tool_call_finish(const ToolResult& result) { if (ended_.load()) return; - std::string ts = to_iso8601(std::chrono::system_clock::now()); + std::string now = to_unix_nanos(std::chrono::system_clock::now()); std::lock_guard lock(mu_); auto it = open_tool_spans_.find(result.tool_call_id); - JsonValue output = - result.is_success() ? result.result : JsonValue(result.error_message()); - + JsonValue* span = nullptr; if (it == open_tool_spans_.end()) { // No matching start (defensive). Emit a closed span with start==end. std::string parent_id = - active_generation_ ? active_generation_->id : std::string(); - JsonValue body = - make_span_create(new_uuid(), id_, parent_id, result.tool_name, ts, - result.arguments, tracer_.config().environment); - body["endTime"] = ts; - body["output"] = output; - body["level"] = result.is_success() ? kLevelDefault : kLevelError; - if (!result.is_success()) - body["statusMessage"] = result.error_message(); - events_.push_back(wrap_event(kEventSpanCreate, ts, std::move(body))); - return; + active_generation_ ? active_generation_->id : root_span_id_; + JsonValue created = + make_span(id_, new_span_id(), parent_id, result.tool_name, + kSpanKindInternal, kObservationTypeSpan, now); + add_attribute(created, kAttrObservationInput, result.arguments); + events_.push_back(std::move(created)); + span = &events_.back(); + } else { + span = &events_[it->second]; + open_tool_spans_.erase(it); } - // Close the open span by emitting span-update referencing the same id. - const std::string span_id = - events_[it->second]["body"]["id"].get(); - JsonValue body; - body["id"] = span_id; - body["traceId"] = id_; - body["endTime"] = ts; - body["output"] = output; - if (!result.is_success()) { - body["level"] = kLevelError; - body["statusMessage"] = result.error_message(); + (*span)["endTimeUnixNano"] = now; + if (result.is_success()) { + add_attribute(*span, kAttrObservationOutput, result.result); + } else { + add_attribute(*span, kAttrObservationOutput, result.error_message()); + mark_error(*span, result.error_message()); } - events_.push_back(wrap_event(kEventSpanUpdate, ts, std::move(body))); - open_tool_spans_.erase(it); } void Trace::finish_generation(const GenerateResult& result) { @@ -428,94 +533,126 @@ void Trace::finish_generation(const GenerateResult& result) { std::lock_guard lock(mu_); if (!active_generation_ || active_generation_->finalized) return; + + events_.push_back(build_generation_span( + to_unix_nanos(std::chrono::system_clock::now()), &result)); +} + +JsonValue Trace::build_generation_span(const std::string& end_nanos, + const GenerateResult* result) { + // Caller must hold mu_. auto& gen = *active_generation_; gen.finalized = true; + JsonValue span = + make_span(id_, gen.id, root_span_id_, gen.name, kSpanKindClient, + kObservationTypeGeneration, to_unix_nanos(gen.start_time)); + span["endTimeUnixNano"] = end_nanos; + add_attribute(span, kAttrModelName, gen.model); + add_attribute(span, kAttrGenAiRequestModel, gen.model); + if (!gen.model_parameters.empty()) + add_attribute(span, kAttrModelParameters, gen.model_parameters); + add_attribute(span, kAttrObservationInput, gen.input); + + if (!result) + return span; + // Aggregate per-step usage when the multi-step coordinator didn't roll it up. - Usage total = result.usage; - if (!result.steps.empty() && total.total_tokens == 0) { + Usage total = result->usage; + if (!result->steps.empty() && total.total_tokens == 0) { int p = 0, c = 0; - for (const auto& s : result.steps) { + for (const auto& s : result->steps) { p += s.usage.prompt_tokens; c += s.usage.completion_tokens; } total = Usage(p, c); } - std::string end_iso = to_iso8601(std::chrono::system_clock::now()); - - JsonValue body; - body["id"] = gen.id; - body["traceId"] = id_; - body["name"] = gen.name; - body["startTime"] = to_iso8601(gen.start_time); - body["endTime"] = end_iso; - body["model"] = gen.model; - if (!gen.model_parameters.empty()) - body["modelParameters"] = gen.model_parameters; - body["input"] = gen.input; - body["output"] = result.text; - body["usage"] = usage_to_langfuse(total); - body["environment"] = tracer_.config().environment; + add_attribute(span, kAttrObservationOutput, result->text); + add_attribute(span, kAttrUsageDetails, usage_to_langfuse(total)); + add_attribute(span, kAttrGenAiInputTokens, + static_cast(total.prompt_tokens)); + add_attribute(span, kAttrGenAiOutputTokens, + static_cast(total.completion_tokens)); JsonValue meta = JsonValue::object(); - meta["finish_reason"] = result.finishReasonToString(); - if (!result.steps.empty()) - meta["steps"] = result.steps.size(); - if (!result.warnings.empty()) - meta["warnings"] = result.warnings; - body["metadata"] = std::move(meta); - - if (!result.is_success() && result.error) { - body["level"] = kLevelError; - body["statusMessage"] = *result.error; - } + meta["finish_reason"] = result->finishReasonToString(); + if (!result->steps.empty()) + meta["steps"] = result->steps.size(); + if (!result->warnings.empty()) + meta["warnings"] = result->warnings; + add_attribute(span, kAttrObservationMetadata, meta); + + if (!result->is_success() && result->error) + mark_error(span, *result->error); - events_.push_back( - wrap_event(kEventGenerationCreate, end_iso, std::move(body))); + return span; } -JsonValue Trace::build_trace_event() const { +JsonValue Trace::build_root_span(const std::string& end_nanos) const { // Caller must hold mu_. - std::string start_iso = to_iso8601(trace_start_); + JsonValue span = + make_span(id_, root_span_id_, std::string(), name_, kSpanKindInternal, + kObservationTypeSpan, to_unix_nanos(trace_start_)); + span["endTimeUnixNano"] = end_nanos; + // Langfuse v4 takes the trace input/output from the root observation; + // the langfuse.trace.* attributes set them for Langfuse v3. + if (input_) { + add_attribute(span, kAttrObservationInput, *input_); + add_attribute(span, kAttrTraceInput, *input_); + } + if (output_) { + add_attribute(span, kAttrObservationOutput, *output_); + add_attribute(span, kAttrTraceOutput, *output_); + } + return span; +} - JsonValue body; - body["id"] = id_; - body["name"] = name_; - body["timestamp"] = start_iso; - body["environment"] = tracer_.config().environment; - if (!tracer_.config().release.empty()) - body["release"] = tracer_.config().release; - if (input_) - body["input"] = *input_; - if (output_) - body["output"] = *output_; +void Trace::add_trace_level_attributes(JsonValue& span) const { + // Caller must hold mu_. + const auto& config = tracer_.config(); + add_attribute(span, kAttrTraceName, name_); + add_attribute(span, kAttrEnvironment, config.environment); + if (!config.release.empty()) + add_attribute(span, kAttrRelease, config.release); if (user_id_) - body["userId"] = *user_id_; + add_attribute(span, kAttrUserId, *user_id_); if (session_id_) - body["sessionId"] = *session_id_; + add_attribute(span, kAttrSessionId, *session_id_); if (metadata_) - body["metadata"] = *metadata_; + add_attribute(span, kAttrTraceMetadata, *metadata_); if (!tags_.empty()) - body["tags"] = tags_; - - return wrap_event(kEventTraceCreate, start_iso, std::move(body)); + add_attribute(span, kAttrTraceTags, tags_); } bool Trace::end() { if (ended_.exchange(true)) return true; - JsonValue batch = JsonValue::array(); + JsonValue spans = JsonValue::array(); { std::lock_guard lock(mu_); - batch.push_back(build_trace_event()); - for (auto& ev : events_) - batch.push_back(std::move(ev)); + std::string now = to_unix_nanos(std::chrono::system_clock::now()); + + if (active_generation_ && !active_generation_->finalized) + events_.push_back(build_generation_span(now, nullptr)); + + spans.push_back(build_root_span(now)); + for (auto& span : events_) { + // Tool calls that never finished are closed at the end of the trace. + if (!span.contains("endTimeUnixNano")) + span["endTimeUnixNano"] = now; + spans.push_back(std::move(span)); + } events_.clear(); + open_tool_spans_.clear(); + + // Langfuse v4 requires trace-level attributes on every span. + for (auto& span : spans) + add_trace_level_attributes(span); } - bool ok = tracer_.send_batch(batch); + bool ok = tracer_.export_spans(spans); return ok || tracer_.config().error_policy == Config::ErrorPolicy::kBestEffort; } @@ -539,6 +676,20 @@ std::string Trace::to_iso8601(std::chrono::system_clock::time_point t) { return std::string(buf); } +std::string Trace::to_unix_nanos(std::chrono::system_clock::time_point t) { + return std::to_string( + std::chrono::duration_cast(t.time_since_epoch()) + .count()); +} + +std::string Trace::new_trace_id() { + return random_hex_id(16); +} + +std::string Trace::new_span_id() { + return random_hex_id(8); +} + std::string Trace::new_uuid() { // RFC 4122 v4 UUID via stduuid. The generator is thread-local to avoid // contention; each thread seeds its own mt19937 from std::random_device. diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 7ece7c7..df5babc 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -8,6 +8,7 @@ add_executable(ai_tests unit/anthropic_stream_test.cpp unit/openai_embeddings_test.cpp unit/multi_step_coordinator_test.cpp + unit/langfuse_tracer_test.cpp # Integration tests integration/openai_integration_test.cpp diff --git a/tests/unit/langfuse_tracer_test.cpp b/tests/unit/langfuse_tracer_test.cpp new file mode 100644 index 0000000..380d049 --- /dev/null +++ b/tests/unit/langfuse_tracer_test.cpp @@ -0,0 +1,393 @@ +#include "ai/langfuse.h" + +#include +#include +#include +#include +#include +#include + +#include + +namespace ai { +namespace test { + +namespace { + +struct CapturedRequest { + std::string path; + httplib::Headers headers; + std::string body; +}; + +// Local HTTP server standing in for Langfuse's OTLP endpoint. +class FakeLangfuseServer { + public: + FakeLangfuseServer() { + server_.Post(".*", + [this](const httplib::Request& req, httplib::Response& res) { + std::lock_guard lock(mu_); + requests_.push_back({req.path, req.headers, req.body}); + res.status = status_; + res.set_content(response_body_, "application/json"); + }); + port_ = server_.bind_to_any_port("127.0.0.1"); + thread_ = std::thread([this] { server_.listen_after_bind(); }); + server_.wait_until_ready(); + } + + ~FakeLangfuseServer() { + server_.stop(); + thread_.join(); + } + + std::string url() const { + return "http://127.0.0.1:" + std::to_string(port_); + } + + void respond_with(int status, std::string body) { + std::lock_guard lock(mu_); + status_ = status; + response_body_ = std::move(body); + } + + std::vector requests() { + std::lock_guard lock(mu_); + return requests_; + } + + private: + httplib::Server server_; + int port_ = 0; + std::thread thread_; + std::mutex mu_; + int status_ = 200; + std::string response_body_ = "{}"; + std::vector requests_; +}; + +std::string header_value(const httplib::Headers& headers, + const std::string& name) { + auto it = headers.find(name); // httplib compares header names + // case-insensitively + return it == headers.end() ? std::string() : it->second; +} + +// Flattens the OTLP attribute list of a span into key -> value object. +std::map attributes_of(const JsonValue& span) { + std::map out; + for (const auto& attr : span.at("attributes")) + out[attr.at("key").get()] = attr.at("value"); + return out; +} + +std::string string_attribute(const JsonValue& span, const std::string& key) { + auto attrs = attributes_of(span); + auto it = attrs.find(key); + if (it == attrs.end()) + return ""; + return it->second.at("stringValue").get(); +} + +bool is_lower_hex(const std::string& s, size_t length) { + if (s.size() != length) + return false; + for (char c : s) { + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) + return false; + } + return true; +} + +const JsonValue& find_span(const JsonValue& spans, const std::string& name) { + for (const auto& span : spans) { + if (span.at("name") == name) + return span; + } + throw std::runtime_error("span not found: " + name); +} + +langfuse::Config config_for(const FakeLangfuseServer& server, + const std::string& sub_path = "") { + langfuse::Config config; + config.host = server.url() + sub_path; + config.public_key = "pk-lf-test"; + config.secret_key = "sk-lf-test"; + config.release = "v1.2.3"; + config.environment = "test-env"; + return config; +} + +} // namespace + +TEST(LangfuseTracerTest, ExportsOtlpRequestToSubPathHost) { + FakeLangfuseServer server; + langfuse::Tracer tracer(config_for(server, "/langfuse/")); + + auto trace = tracer.start_trace("request"); + ASSERT_TRUE(trace->end()); + + auto requests = server.requests(); + ASSERT_EQ(requests.size(), 1u); + const auto& req = requests[0]; + EXPECT_EQ(req.path, "/langfuse/api/public/otel/v1/traces"); + // base64("pk-lf-test:sk-lf-test") + EXPECT_EQ(header_value(req.headers, "Authorization"), + "Basic cGstbGYtdGVzdDpzay1sZi10ZXN0"); + EXPECT_EQ(header_value(req.headers, "x-langfuse-ingestion-version"), "4"); + EXPECT_EQ(header_value(req.headers, "Content-Type"), "application/json"); + + auto body = JsonValue::parse(req.body); + ASSERT_EQ(body.at("resourceSpans").size(), 1u); + const auto& resource_spans = body["resourceSpans"][0]; + ASSERT_EQ(resource_spans.at("scopeSpans").size(), 1u); + const auto& scope_spans = resource_spans["scopeSpans"][0]; + EXPECT_EQ(scope_spans.at("scope").at("name"), "ai-sdk-cpp"); + ASSERT_EQ(scope_spans.at("spans").size(), 1u); + + const auto& root = scope_spans["spans"][0]; + EXPECT_EQ(root.at("traceId"), trace->id()); + EXPECT_TRUE(is_lower_hex(trace->id(), 32)); + EXPECT_TRUE(is_lower_hex(root.at("spanId").get(), 16)); + EXPECT_FALSE(root.contains("parentSpanId")); + EXPECT_EQ(root.at("name"), "request"); + EXPECT_EQ(string_attribute(root, "langfuse.observation.type"), "span"); + EXPECT_EQ(string_attribute(root, "langfuse.trace.name"), "request"); + EXPECT_EQ(string_attribute(root, "langfuse.environment"), "test-env"); + EXPECT_EQ(string_attribute(root, "langfuse.release"), "v1.2.3"); + + // Times are unix nanoseconds encoded as decimal strings. + auto start = std::stoll(root.at("startTimeUnixNano").get()); + auto end = std::stoll(root.at("endTimeUnixNano").get()); + EXPECT_GT(start, 1'700'000'000'000'000'000LL); + EXPECT_GE(end, start); +} + +TEST(LangfuseTracerTest, ExportsTraceGenerationAndToolHierarchy) { + FakeLangfuseServer server; + langfuse::Tracer tracer(config_for(server)); + + langfuse::TraceOptions trace_options; + trace_options.user_id = "user-1"; + trace_options.session_id = "session-1"; + trace_options.metadata = JsonValue{{"tenant", "acme"}, {"n", 3}}; + trace_options.tags = {"a", "b"}; + auto trace = tracer.start_trace("sql-generation", trace_options); + trace->set_input("show tables"); + + GenerateOptions options; + options.model = "test-model"; + options.system = "be brief"; + options.prompt = "show tables"; + options.temperature = 0.5; + options.max_steps = 3; + + bool user_callback_called = false; + options.on_tool_call_start = [&](const ToolCall&) { + user_callback_called = true; + }; + trace->instrument(options, "llm"); + + (*options.on_tool_call_start)( + ToolCall("call-1", "run_query", JsonValue{{"sql", "SHOW TABLES"}})); + (*options.on_tool_call_finish)(ToolResult("call-1", "run_query", + JsonValue{{"sql", "SHOW TABLES"}}, + JsonValue{{"rows", 2}})); + (*options.on_tool_call_start)( + ToolCall("call-2", "broken", JsonValue::object())); + (*options.on_tool_call_finish)(ToolResult( + "call-2", "broken", JsonValue::object(), std::string("tool failed"))); + EXPECT_TRUE(user_callback_called); + + GenerateResult result("t1, t2", kFinishReasonStop, Usage(10, 5)); + trace->finish_generation(result); + trace->set_output("t1, t2"); + ASSERT_TRUE(trace->end()); + + auto requests = server.requests(); + ASSERT_EQ(requests.size(), 1u); + auto body = JsonValue::parse(requests[0].body); + const auto& spans = body["resourceSpans"][0]["scopeSpans"][0]["spans"]; + ASSERT_EQ(spans.size(), 4u); + + const JsonValue root = find_span(spans, "sql-generation"); + const JsonValue generation = find_span(spans, "llm"); + const JsonValue tool = find_span(spans, "run_query"); + const JsonValue broken = find_span(spans, "broken"); + + // Hierarchy: root span -> generation -> tool spans, all in one trace. + for (const auto& span : spans) { + EXPECT_EQ(span.at("traceId"), trace->id()); + EXPECT_TRUE(is_lower_hex(span.at("spanId").get(), 16)); + EXPECT_TRUE(span.contains("endTimeUnixNano")); + } + EXPECT_FALSE(root.contains("parentSpanId")); + EXPECT_EQ(generation.at("parentSpanId"), root.at("spanId")); + EXPECT_EQ(tool.at("parentSpanId"), generation.at("spanId")); + EXPECT_EQ(broken.at("parentSpanId"), generation.at("spanId")); + + // Trace-level attributes are propagated to every span. + for (const auto& span : spans) { + EXPECT_EQ(string_attribute(span, "langfuse.trace.name"), "sql-generation"); + EXPECT_EQ(string_attribute(span, "langfuse.user.id"), "user-1"); + EXPECT_EQ(string_attribute(span, "langfuse.session.id"), "session-1"); + EXPECT_EQ( + JsonValue::parse(string_attribute(span, "langfuse.trace.metadata")), + (JsonValue{{"tenant", "acme"}, {"n", 3}})); + auto tags = attributes_of(span).at("langfuse.trace.tags"); + EXPECT_EQ( + tags, + (JsonValue{ + {"arrayValue", + {{"values", {{{"stringValue", "a"}}, {{"stringValue", "b"}}}}}}})); + } + + // Root span carries the trace input/output. + EXPECT_EQ(string_attribute(root, "langfuse.observation.input"), + "show tables"); + EXPECT_EQ(string_attribute(root, "langfuse.trace.input"), "show tables"); + EXPECT_EQ(string_attribute(root, "langfuse.observation.output"), "t1, t2"); + EXPECT_EQ(string_attribute(root, "langfuse.trace.output"), "t1, t2"); + + // Generation. + EXPECT_EQ(string_attribute(generation, "langfuse.observation.type"), + "generation"); + EXPECT_EQ(string_attribute(generation, "langfuse.observation.model.name"), + "test-model"); + EXPECT_EQ(string_attribute(generation, "gen_ai.request.model"), "test-model"); + EXPECT_EQ(JsonValue::parse(string_attribute( + generation, "langfuse.observation.model.parameters")), + (JsonValue{{"temperature", 0.5}, {"max_steps", 3}})); + EXPECT_EQ( + JsonValue::parse( + string_attribute(generation, "langfuse.observation.input")), + (JsonValue::array({{{"role", "system"}, {"content", "be brief"}}, + {{"role", "user"}, {"content", "show tables"}}}))); + EXPECT_EQ(string_attribute(generation, "langfuse.observation.output"), + "t1, t2"); + EXPECT_EQ(JsonValue::parse(string_attribute( + generation, "langfuse.observation.usage_details")), + (JsonValue{{"input", 10}, {"output", 5}, {"total", 15}})); + auto gen_attrs = attributes_of(generation); + EXPECT_EQ(gen_attrs.at("gen_ai.usage.input_tokens"), + (JsonValue{{"intValue", "10"}})); + EXPECT_EQ(gen_attrs.at("gen_ai.usage.output_tokens"), + (JsonValue{{"intValue", "5"}})); + EXPECT_EQ(JsonValue::parse(string_attribute( + generation, "langfuse.observation.metadata"))["finish_reason"], + "stop"); + EXPECT_FALSE(generation.contains("status")); + + // Tool spans. + EXPECT_EQ(string_attribute(tool, "langfuse.observation.type"), "span"); + EXPECT_EQ( + JsonValue::parse(string_attribute(tool, "langfuse.observation.input")), + (JsonValue{{"sql", "SHOW TABLES"}})); + EXPECT_EQ( + JsonValue::parse(string_attribute(tool, "langfuse.observation.output")), + (JsonValue{{"rows", 2}})); + EXPECT_EQ(attributes_of(tool).count("langfuse.observation.level"), 0u); + + EXPECT_EQ(string_attribute(broken, "langfuse.observation.level"), "ERROR"); + EXPECT_EQ(string_attribute(broken, "langfuse.observation.status_message"), + "tool failed"); + EXPECT_EQ(broken.at("status"), + (JsonValue{{"code", 2}, {"message", "tool failed"}})); +} + +TEST(LangfuseTracerTest, FailedGenerationIsMarkedAsError) { + FakeLangfuseServer server; + langfuse::Tracer tracer(config_for(server)); + + auto trace = tracer.start_trace("failing"); + GenerateOptions options; + options.model = "test-model"; + options.prompt = "hi"; + trace->instrument(options); + trace->finish_generation(GenerateResult(std::string("rate limited"))); + ASSERT_TRUE(trace->end()); + + auto body = JsonValue::parse(server.requests().at(0).body); + const auto& spans = body["resourceSpans"][0]["scopeSpans"][0]["spans"]; + const JsonValue generation = find_span(spans, "generate_text"); + EXPECT_EQ(string_attribute(generation, "langfuse.observation.level"), + "ERROR"); + EXPECT_EQ(string_attribute(generation, "langfuse.observation.status_message"), + "rate limited"); + EXPECT_EQ(generation.at("status").at("code"), 2); +} + +TEST(LangfuseTracerTest, UnfinishedSpansAreClosedAtEnd) { + FakeLangfuseServer server; + langfuse::Tracer tracer(config_for(server)); + + auto trace = tracer.start_trace("unfinished"); + GenerateOptions options; + options.model = "test-model"; + options.prompt = "hi"; + trace->instrument(options, "llm"); + (*options.on_tool_call_start)(ToolCall("call-1", "slow", JsonValue{})); + ASSERT_TRUE(trace->end()); + + auto body = JsonValue::parse(server.requests().at(0).body); + const auto& spans = body["resourceSpans"][0]["scopeSpans"][0]["spans"]; + ASSERT_EQ(spans.size(), 3u); + const JsonValue generation = find_span(spans, "llm"); + const JsonValue tool = find_span(spans, "slow"); + EXPECT_EQ(tool.at("parentSpanId"), generation.at("spanId")); + EXPECT_TRUE(generation.contains("endTimeUnixNano")); + EXPECT_TRUE(tool.contains("endTimeUnixNano")); +} + +TEST(LangfuseTracerTest, EndIsIdempotent) { + FakeLangfuseServer server; + langfuse::Tracer tracer(config_for(server)); + + auto trace = tracer.start_trace("once"); + ASSERT_TRUE(trace->end()); + ASSERT_TRUE(trace->end()); + EXPECT_EQ(server.requests().size(), 1u); +} + +TEST(LangfuseTracerTest, ErrorPolicy) { + FakeLangfuseServer server; + server.respond_with(400, R"({"error":"bad request"})"); + + langfuse::Tracer strict(config_for(server)); + EXPECT_FALSE(strict.start_trace("strict")->end()); + + auto config = config_for(server); + config.error_policy = langfuse::Config::ErrorPolicy::kBestEffort; + langfuse::Tracer best_effort(config); + EXPECT_TRUE(best_effort.start_trace("best-effort")->end()); +} + +TEST(LangfuseTracerTest, RejectedSpansAreAnError) { + FakeLangfuseServer server; + server.respond_with( + 200, + R"({"partialSuccess":{"rejectedSpans":"1","errorMessage":"invalid"}})"); + + langfuse::Tracer tracer(config_for(server)); + EXPECT_FALSE(tracer.start_trace("rejected")->end()); +} + +TEST(LangfuseTracerTest, InvalidConfigDoesNotSend) { + langfuse::Config config; + config.host = "http://127.0.0.1:1"; + langfuse::Tracer tracer(config); + EXPECT_FALSE(tracer.is_valid()); + EXPECT_FALSE(tracer.start_trace("unconfigured")->end()); +} + +TEST(LangfuseTracerTest, GeneratesOpenTelemetryIds) { + auto trace_id = langfuse::Trace::new_trace_id(); + auto span_id = langfuse::Trace::new_span_id(); + EXPECT_TRUE(is_lower_hex(trace_id, 32)); + EXPECT_TRUE(is_lower_hex(span_id, 16)); + EXPECT_NE(trace_id, langfuse::Trace::new_trace_id()); + EXPECT_NE(span_id, langfuse::Trace::new_span_id()); +} + +} // namespace test +} // namespace ai From 3ebdfb91631d74a4bb62ee68412bcd30bf3089f6 Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Fri, 27 Nov 2026 02:19:44 +0000 Subject: [PATCH 3/3] Ignore a non-object `partialSuccess` in the OTLP export response Co-Authored-By: Claude Opus 5.5 --- src/langfuse/tracer.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/langfuse/tracer.cpp b/src/langfuse/tracer.cpp index 83ba051..673322c 100644 --- a/src/langfuse/tracer.cpp +++ b/src/langfuse/tracer.cpp @@ -361,7 +361,8 @@ bool Tracer::export_spans(const JsonValue& spans) { // ExportTraceServiceResponse may report spans the server rejected. auto response = JsonValue::parse(res->body, nullptr, false); - if (response.is_object() && response.contains("partialSuccess")) { + if (response.is_object() && response.contains("partialSuccess") && + response["partialSuccess"].is_object()) { const auto& partial = response["partialSuccess"]; // int64 rejectedSpans may be encoded as a number or a decimal string. const auto rejected = partial.value("rejectedSpans", JsonValue(0));