The personal finance app for everyone (by everyone)
Ruby
chore(langfuse): migrate tracing and experiments to v4 (#3625)
Alessandro Pogliaghi5695e56a5b67
diff --git a/Gemfile b/Gemfileindex f744f62a9d..ac97a8e009 100644--- a/Gemfile+++ b/Gemfile@@ -106,7 +106,8 @@ gem "after_commit_everywhere", "~> 1.0"# AIgem "ruby-openai"gem "anthropic", "~> 1.0"-gem "langfuse-ruby", "~> 0.1.4", require: "langfuse"+gem "opentelemetry-sdk", "~> 1.13"+gem "opentelemetry-exporter-otlp", "~> 0.36"group :development, :test dogem "debug", platforms: %i[mri mswin mswin64 mingw x64_mingw]diff --git a/Gemfile.lock b/Gemfile.lockindex e77e88a165..51f975f78e 100644--- a/Gemfile.lock+++ b/Gemfile.lock@@ -279,6 +279,29 @@ GEMgoogleauth (~> 1.9)mini_mime (~> 1.0)google-logging-utils (0.2.0)+ google-protobuf (4.36.1)+ bigdecimal+ rake (~> 13.3)+ google-protobuf (4.36.1-aarch64-linux-gnu)+ bigdecimal+ rake (~> 13.3)+ google-protobuf (4.36.1-aarch64-linux-musl)+ bigdecimal+ rake (~> 13.3)+ google-protobuf (4.36.1-arm64-darwin)+ bigdecimal+ rake (~> 13.3)+ google-protobuf (4.36.1-x86_64-darwin)+ bigdecimal+ rake (~> 13.3)+ google-protobuf (4.36.1-x86_64-linux-gnu)+ bigdecimal+ rake (~> 13.3)+ google-protobuf (4.36.1-x86_64-linux-musl)+ bigdecimal+ rake (~> 13.3)+ googleapis-common-protos-types (1.23.0)+ google-protobuf (~> 4.26)googleauth (1.16.2)faraday (>= 1.0, < 3.a)google-cloud-env (~> 2.2)@@ -357,11 +380,6 @@ GEMbigdecimal (~> 3.1)jwt (2.10.3)base64- langfuse-ruby (0.1.4)- concurrent-ruby (~> 1.0)- faraday (>= 1.8, < 3.0)- faraday-net_http (>= 1.0, < 4.0)- json (~> 2.0)language_server-protocol (3.17.0.5)launchy (3.1.1)addressable (~> 2.8)@@ -507,6 +525,32 @@ GEMopenssl (4.0.1)openssl-signature_algorithm (1.3.0)openssl (> 2.0)+ opentelemetry-api (1.11.1)+ logger+ opentelemetry-common (0.25.1)+ opentelemetry-api (~> 1.0)+ opentelemetry-exporter-otlp (0.36.0)+ google-protobuf (>= 3.18)+ googleapis-common-protos-types (~> 1.3)+ opentelemetry-api (~> 1.1)+ opentelemetry-common (~> 0.20)+ opentelemetry-exporter-otlp-common+ opentelemetry-sdk (~> 1.10)+ opentelemetry-semantic_conventions+ opentelemetry-exporter-otlp-common (0.2.0)+ google-protobuf (>= 3.18)+ googleapis-common-protos-types (~> 1.3)+ opentelemetry-api (~> 1.1)+ opentelemetry-registry (0.6.3)+ opentelemetry-api (~> 1.1)+ opentelemetry-sdk (1.13.1)+ logger+ opentelemetry-api (~> 1.1)+ opentelemetry-common (~> 0.20)+ opentelemetry-registry (~> 0.2)+ opentelemetry-semantic_conventions+ opentelemetry-semantic_conventions (1.44.0)+ opentelemetry-api (~> 1.0)os (1.1.4)ostruct (0.6.2)pagy (9.3.5)@@ -907,7 +951,6 @@ DEPENDENCIESinline_svgjbuilderjwt- langfuse-ruby (~> 0.1.4)letter_openerlogtail-railslookbook (= 2.3.11)@@ -920,6 +963,8 @@ DEPENDENCIESomniauth-rails_csrf_protection (>= 2.0)omniauth-saml (~> 2.1)omniauth_openid_connect+ opentelemetry-exporter-otlp (~> 0.36)+ opentelemetry-sdk (~> 1.13)ostructpagypdf-reader (~> 2.12)diff --git a/app/models/assistant/function/search_family_files.rb b/app/models/assistant/function/search_family_files.rbindex 3f5f914ff1..42a4cbf049 100644--- a/app/models/assistant/function/search_family_files.rb+++ b/app/models/assistant/function/search_family_files.rb@@ -1,4 +1,6 @@class Assistant::Function::SearchFamilyFiles < Assistant::Function+ include LangfuseTraceable+class << selfdef name"search_family_files"@@ -83,7 +85,8 @@ class Assistant::Function::SearchFamilyFiles < Assistant::Functiontrace = create_langfuse_trace(name: "search_family_files",- input: { query: query, max_results: max_results, store_id: store_id }+ input: { query: query, max_results: max_results, store_id: store_id },+ user_identifier: user.id&.to_s)response = adapter.search(@@ -96,7 +99,7 @@ class Assistant::Function::SearchFamilyFiles < Assistant::Functionerror_msg = response.error&.messageRails.logger.debug("[SearchFamilyFiles] search failed: #{error_msg}")begin- langfuse_client&.trace(id: trace.id, output: { error: error_msg }, level: "ERROR") if trace+ finish_langfuse_trace(trace: trace, output: { error: error_msg }, level: "ERROR")rescue => eRails.logger.debug("[SearchFamilyFiles] Langfuse trace update failed: #{e.class}: #{e.message}\n#{e.backtrace&.first(5)&.join("\n")}")end@@ -130,7 +133,7 @@ class Assistant::Function::SearchFamilyFiles < Assistant::Functionbeginif trace- langfuse_client&.trace(id: trace.id, output: {+ finish_langfuse_trace(trace: trace, output: {result_count: mapped.size,chunks: mapped.map { |r| { filename: r[:filename], score: r[:score], content_length: r[:content]&.length } }})@@ -141,6 +144,7 @@ class Assistant::Function::SearchFamilyFiles < Assistant::Functionoutputrescue => e+ finish_langfuse_trace(trace: trace, output: { error: e.message }, level: "ERROR")Rails.logger.error("[SearchFamilyFiles] error: #{e.class.name} - #{e.message}"){success: false,@@ -148,25 +152,4 @@ class Assistant::Function::SearchFamilyFiles < Assistant::Functionmessage: "An error occurred while searching documents: #{e.message.truncate(200)}"}end-- private- def langfuse_client- return unless ENV["LANGFUSE_PUBLIC_KEY"].present? && ENV["LANGFUSE_SECRET_KEY"].present?-- @langfuse_client ||= Langfuse.new- end-- def create_langfuse_trace(name:, input:)- return unless langfuse_client-- langfuse_client.trace(- name: name,- input: input,- user_id: user.id&.to_s,- environment: Rails.env- )- rescue => e- Rails.logger.debug("[SearchFamilyFiles] Langfuse trace creation failed: #{e.class}: #{e.message}\n#{e.backtrace&.first(5)&.join("\n")}")- nil- endenddiff --git a/app/models/concerns/langfuse_traceable.rb b/app/models/concerns/langfuse_traceable.rbnew file mode 100644index 0000000000..a71d5542f5--- /dev/null+++ b/app/models/concerns/langfuse_traceable.rb@@ -0,0 +1,30 @@+module LangfuseTraceable+ private++ def langfuse_client+ return unless ENV["LANGFUSE_PUBLIC_KEY"].present? && ENV["LANGFUSE_SECRET_KEY"].present?++ Rails.configuration.x.langfuse+ end++ def create_langfuse_trace(name:, input:, session_id: nil, user_identifier: nil, start_time: nil)+ langfuse_client&.trace(+ name: name,+ input: input,+ session_id: session_id,+ user_id: user_identifier,+ environment: Rails.env,+ start_time: start_time+ )+ rescue => e+ Rails.logger.warn("Langfuse trace creation failed: #{e.class}: #{e.message}")+ nil+ end++ def finish_langfuse_trace(trace:, output:, level: nil)+ trace&.end(output: output, level: level)+ rescue => e+ Rails.logger.warn("Langfuse trace finalization failed: #{e.class}: #{e.message}")+ nil+ end+enddiff --git a/app/models/eval/langfuse/client.rb b/app/models/eval/langfuse/client.rbindex 75701e1cb9..120871d401 100644--- a/app/models/eval/langfuse/client.rb+++ b/app/models/eval/langfuse/client.rb@@ -77,64 +77,51 @@ class Eval::Langfuse::Clientget("/dataset-items", datasetName: dataset_name, page: page, limit: limit)end- # Dataset run operations (for experiments)- def create_dataset_run_item(run_name:, dataset_item_id:, trace_id: nil, observation_id: nil, metadata: {})- post("/dataset-run-items", {- runName: run_name,- datasetItemId: dataset_item_id,- traceId: trace_id,- observationId: observation_id,- metadata: metadata- }.compact)+ def create_experiment_item(name:, input:, output:, expected_output:, experiment_id:, experiment_name:, dataset_id:, item_id:, metadata: {}, start_time: nil)+ @tracing ||= LangfuseTracing.new(public_key: @public_key, secret_key: @secret_key, host: @base_url.delete_suffix("/api/public"), auto_flush: false)+ observation = @tracing.trace(+ name: name,+ input: input,+ environment: "experiment",+ start_time: start_time,+ attributes: {+ "langfuse.experiment.id" => experiment_id,+ "langfuse.experiment.name" => experiment_name,+ "langfuse.experiment.dataset.id" => dataset_id,+ "langfuse.experiment.item.id" => item_id,+ "langfuse.experiment.item.expected_output" => expected_output.to_json+ }+ )+ attributes = { "langfuse.experiment.item.root_observation_id" => observation.span_id }+ metadata.each { |key, value| attributes["langfuse.experiment.item.metadata.#{key}"] = value.is_a?(String) ? value : value.to_json }+ observation.set_attributes(attributes)+ observation.end(output: output)+ observationend- # Trace operations- def create_trace(name:, input: nil, output: nil, metadata: {}, session_id: nil, user_id: nil)- # Generate trace ID upfront so we can return it- trace_id = SecureRandom.uuid-- post("/ingestion", {- batch: [- {- id: SecureRandom.uuid,- type: "trace-create",- timestamp: Time.current.iso8601,- body: {- id: trace_id,- name: name,- input: input,- output: output,- metadata: metadata,- sessionId: session_id,- userId: user_id- }.compact- }- ]- })+ def flush_experiment_items+ return unless @tracing- # Return the trace ID we generated- trace_id+ unless @tracing.flush == OpenTelemetry::SDK::Trace::Export::SUCCESS+ raise ApiError, "Failed to export Langfuse experiment items"+ endend- # Score operations- def create_score(trace_id:, name:, value:, comment: nil, data_type: "NUMERIC")- post("/ingestion", {- batch: [- {- id: SecureRandom.uuid,- type: "score-create",- timestamp: Time.current.iso8601,- body: {- id: SecureRandom.uuid,- traceId: trace_id,- name: name,- value: value,- comment: comment,- dataType: data_type- }.compact- }- ]- })+ def create_score(trace_id:, observation_id:, name:, value:, comment: nil, data_type: "NUMERIC")+ post("/scores", {+ traceId: trace_id,+ observationId: observation_id,+ name: name,+ value: value,+ comment: comment,+ dataType: data_type,+ environment: "experiment"+ }.compact)+ end++ def shutdown+ @tracing&.shutdown+ @tracing = nilenddef configured?diff --git a/app/models/eval/langfuse/experiment_runner.rb b/app/models/eval/langfuse/experiment_runner.rbindex 4c9c326a3e..636dede4be 100644--- a/app/models/eval/langfuse/experiment_runner.rb+++ b/app/models/eval/langfuse/experiment_runner.rb@@ -16,6 +16,7 @@ class Eval::Langfuse::ExperimentRunnerdef run(run_name: nil)@run_name = run_name || generate_run_name+ @experiment_id = SecureRandom.uuidRails.logger.info("[Langfuse Experiment] Starting experiment '#{@run_name}'")Rails.logger.info("[Langfuse Experiment] Dataset: #{dataset.name} (#{dataset.sample_count} samples)")@@ -23,6 +24,7 @@ class Eval::Langfuse::ExperimentRunner# Ensure dataset exists in Langfuseensure_dataset_exported+ @dataset_id = client.get_dataset(name: langfuse_dataset_name).fetch("id")# Get dataset items from Langfuseitems = fetch_langfuse_items@@ -43,6 +45,8 @@ class Eval::Langfuse::ExperimentRunnersamples_processed: results.size,metrics: metrics}+ ensure+ client.shutdownendprivate@@ -93,7 +97,8 @@ class Eval::Langfuse::ExperimentRunnerenddef process_batch(items)- case dataset.eval_type+ @pending_scores = []+ results = case dataset.eval_typewhen "categorization"process_categorization_batch(items)when "merchant_detection"@@ -103,6 +108,13 @@ class Eval::Langfuse::ExperimentRunnerelseraise "Unsupported eval type: #{dataset.eval_type}"end+ client.flush_experiment_items+ @pending_scores.each { |args| score_result(*args) }+ results+ rescue => e+ handle_batch_error(items, e)+ ensure+ @pending_scores = nilenddef process_categorization_batch(items)@@ -140,8 +152,8 @@ class Eval::Langfuse::ExperimentRunnerscore_value = correct ? 1.0 : 0.0# Create trace and score in Langfuse- trace_id = create_trace_for_item(item, actual_category, latency_ms)- score_result(trace_id, item["id"], score_value, correct, actual_category, expected_category)+ observation = create_trace_for_item(item, actual_category, latency_ms)+ queue_score_result(observation, item["id"], score_value, correct, actual_category, expected_category){item_id: item["id"],@@ -193,8 +205,8 @@ class Eval::Langfuse::ExperimentRunner# Create trace and score in Langfuseactual_output = { business_name: actual_name, business_url: actual_url }- trace_id = create_trace_for_item(item, actual_output, latency_ms)- score_result(trace_id, item["id"], score_value, correct, actual_output, item["expectedOutput"])+ observation = create_trace_for_item(item, actual_output, latency_ms)+ queue_score_result(observation, item["id"], score_value, correct, actual_output, item["expectedOutput"]){item_id: item["id"],@@ -238,8 +250,8 @@ class Eval::Langfuse::ExperimentRunnerscore_value = correct ? 1.0 : 0.0# Create trace and score in Langfuse- trace_id = create_trace_for_item(item, { functions: actual_functions }, latency_ms)- score_result(trace_id, item["id"], score_value, correct, actual_functions, expected_functions)+ observation = create_trace_for_item(item, { functions: actual_functions }, latency_ms)+ queue_score_result(observation, item["id"], score_value, correct, actual_functions, expected_functions){item_id: item["id"],@@ -253,49 +265,40 @@ class Eval::Langfuse::ExperimentRunnerenddef create_trace_for_item(item, output, latency_ms)- trace_id = client.create_trace(+ client.create_experiment_item(name: "#{dataset.eval_type}_eval",input: item["input"],output: output,- metadata: {- run_name: @run_name,- model: model,- latency_ms: latency_ms,- dataset_item_id: item["id"]- }+ expected_output: item["expectedOutput"],+ experiment_id: @experiment_id,+ experiment_name: @run_name,+ dataset_id: @dataset_id,+ item_id: item.fetch("id"),+ start_time: Time.current - latency_ms / 1000.0,+ metadata: (item["metadata"] || {}).merge(model: model, latency_ms: latency_ms))+ end- Rails.logger.debug("[Langfuse Experiment] Created trace #{trace_id} for item #{item['id']}")- trace_id+ def queue_score_result(observation, item_id, score_value, correct, actual, expected)+ @pending_scores << [ observation, item_id, score_value, correct, actual, expected ]end- def score_result(trace_id, item_id, score_value, correct, actual, expected)- return unless trace_id+ def score_result(observation, item_id, score_value, correct, actual, expected)+ return unless observation- # Score the accuracyclient.create_score(- trace_id: trace_id,+ trace_id: observation.id,+ observation_id: observation.span_id,name: "accuracy",value: score_value,comment: correct ? "Correct" : "Expected: #{expected.inspect}, Got: #{actual.inspect}")-- # Link to dataset run- client.create_dataset_run_item(- run_name: @run_name,- dataset_item_id: item_id,- trace_id: trace_id,- metadata: {- correct: correct,- actual: actual,- expected: expected- }- )rescue => eRails.logger.warn("[Langfuse Experiment] Failed to score item #{item_id}: #{e.message}")enddef handle_batch_error(items, error)+ @pending_scores&.clearerror_message = error.is_a?(Exception) ? error.message : error.to_sRails.logger.error("[Langfuse Experiment] Batch error: #{error_message}")diff --git a/app/models/provider/anthropic.rb b/app/models/provider/anthropic.rbindex b52073cac7..ce9becfbda 100644--- a/app/models/provider/anthropic.rb+++ b/app/models/provider/anthropic.rb@@ -1,5 +1,6 @@class Provider::Anthropic < Providerinclude LlmConcept+ include LangfuseTraceable# Subclass so errors caught in this provider are raised as Provider::Anthropic::ErrorError = Class.new(Provider::Error)@@ -120,9 +121,12 @@ class Provider::Anthropic < Providerfamily: family).auto_categorize- upsert_langfuse_trace(trace: trace, output: result.map(&:to_h))+ finish_langfuse_trace(trace: trace, output: result.map(&:to_h))result+ rescue => error+ finish_langfuse_trace(trace: trace, output: { error: error.message }, level: "ERROR")+ raiseendend@@ -145,9 +149,12 @@ class Provider::Anthropic < Providerfamily: family).suggest- upsert_langfuse_trace(trace: trace, output: result.to_h)+ finish_langfuse_trace(trace: trace, output: result.to_h)result+ rescue => error+ finish_langfuse_trace(trace: trace, output: { error: error.message }, level: "ERROR")+ raiseendend@@ -169,9 +176,12 @@ class Provider::Anthropic < Providerfamily: family).auto_detect_merchants- upsert_langfuse_trace(trace: trace, output: result.map(&:to_h))+ finish_langfuse_trace(trace: trace, output: result.map(&:to_h))result+ rescue => error+ finish_langfuse_trace(trace: trace, output: { error: error.message }, level: "ERROR")+ raiseendend@@ -192,9 +202,12 @@ class Provider::Anthropic < Providerfamily: family).enhance_merchants- upsert_langfuse_trace(trace: trace, output: result.map(&:to_h))+ finish_langfuse_trace(trace: trace, output: result.map(&:to_h))result+ rescue => error+ finish_langfuse_trace(trace: trace, output: { error: error.message }, level: "ERROR")+ raiseendend@@ -222,9 +235,12 @@ class Provider::Anthropic < Providerfamily: family).process- upsert_langfuse_trace(trace: trace, output: result.to_h)+ finish_langfuse_trace(trace: trace, output: result.to_h)result+ rescue => error+ finish_langfuse_trace(trace: trace, output: { error: error.message }, level: "ERROR")+ raiseendend@@ -245,9 +261,12 @@ class Provider::Anthropic < Providerfamily: family).extract- upsert_langfuse_trace(trace: trace, output: { transaction_count: result[:transactions].size })+ finish_langfuse_trace(trace: trace, output: { transaction_count: result[:transactions].size })result+ rescue => error+ finish_langfuse_trace(trace: trace, output: { error: error.message }, level: "ERROR")+ raiseendend@@ -409,37 +428,14 @@ class Provider::Anthropic < Providerhashend- def langfuse_client- return unless ENV["LANGFUSE_PUBLIC_KEY"].present? && ENV["LANGFUSE_SECRET_KEY"].present?-- @langfuse_client ||= Langfuse.new- end-- def create_langfuse_trace(name:, input:, session_id: nil, user_identifier: nil)- return unless langfuse_client-- langfuse_client.trace(- name: name,- input: input,- session_id: session_id,- user_id: user_identifier,- environment: Rails.env- )- rescue => e- # Sanitized log (class + message only) — `e.full_message` bundles the- # backtrace + cause chain, which on some SDK error types includes the- # serialized request/response payload (model output, user prompt).- Rails.logger.warn("Langfuse trace creation failed: #{e.class}: #{e.message}")- nil- end-def log_langfuse_generation(name:, model:, input:, trace:, output: nil, usage: nil, error: nil)return unless langfuse_clientgeneration = trace&.generation(name: name,model: model,- input: input+ input: input,+ start_time: trace.start_time)if error@@ -447,27 +443,15 @@ class Provider::Anthropic < Provideroutput: { error: error.message, details: error.respond_to?(:details) ? error.details : nil },level: "ERROR")- upsert_langfuse_trace(trace: trace, output: { error: error.message }, level: "ERROR")+ finish_langfuse_trace(trace: trace, output: { error: error.message }, level: "ERROR")elsegeneration&.end(output: output, usage: usage)- upsert_langfuse_trace(trace: trace, output: output)+ finish_langfuse_trace(trace: trace, output: output)endrescue => eRails.logger.warn("Langfuse logging failed: #{e.class}: #{e.message}")end- def upsert_langfuse_trace(trace:, output:, level: nil)- return unless langfuse_client && trace&.id-- payload = { id: trace.id, output: output }- payload[:level] = level if level.present?-- langfuse_client.trace(**payload)- rescue => e- Rails.logger.warn("Langfuse trace upsert failed for trace_id=#{trace&.id}: #{e.class}: #{e.message}")- nil- end-def record_llm_usage(family:, model:, operation:, usage: nil, error: nil)return unless familydiff --git a/app/models/provider/anthropic/auto_categorizer.rb b/app/models/provider/anthropic/auto_categorizer.rbindex ccf9a1aa81..c81e0936b8 100644--- a/app/models/provider/anthropic/auto_categorizer.rb+++ b/app/models/provider/anthropic/auto_categorizer.rb@@ -15,7 +15,7 @@ class Provider::Anthropic::AutoCategorizerenddef auto_categorize- span = langfuse_trace&.span(name: "auto_categorize_api_call", input: {+ span = langfuse_trace&.generation(name: "auto_categorize_api_call", model: model, input: {model: model,transactions: transactions,user_categories: user_categories@@ -173,13 +173,4 @@ class Provider::Anthropic::AutoCategorizerdef block_input(block)block.respond_to?(:input) ? block.input : (block[:input] || block["input"])end-- def usage_hash(raw_usage)- return {} unless raw_usage- {- "input_tokens" => raw_usage.input_tokens.to_i,- "output_tokens" => raw_usage.output_tokens.to_i,- "total_tokens" => raw_usage.input_tokens.to_i + raw_usage.output_tokens.to_i- }- endenddiff --git a/app/models/provider/anthropic/auto_merchant_detector.rb b/app/models/provider/anthropic/auto_merchant_detector.rbindex c958a3ef32..ce774145b0 100644--- a/app/models/provider/anthropic/auto_merchant_detector.rb+++ b/app/models/provider/anthropic/auto_merchant_detector.rb@@ -15,7 +15,7 @@ class Provider::Anthropic::AutoMerchantDetectorenddef auto_detect_merchants- span = langfuse_trace&.span(name: "auto_detect_merchants_api_call", input: {+ span = langfuse_trace&.generation(name: "auto_detect_merchants_api_call", model: model, input: {model: model,transactions: transactions,user_merchants: user_merchants@@ -182,13 +182,4 @@ class Provider::Anthropic::AutoMerchantDetectordef block_input(block)block.respond_to?(:input) ? block.input : (block[:input] || block["input"])end-- def usage_hash(raw_usage)- return {} unless raw_usage- {- "input_tokens" => raw_usage.input_tokens.to_i,- "output_tokens" => raw_usage.output_tokens.to_i,- "total_tokens" => raw_usage.input_tokens.to_i + raw_usage.output_tokens.to_i- }- endenddiff --git a/app/models/provider/anthropic/bank_statement_extractor.rb b/app/models/provider/anthropic/bank_statement_extractor.rbindex acc62a92d4..470a9e07d2 100644--- a/app/models/provider/anthropic/bank_statement_extractor.rb+++ b/app/models/provider/anthropic/bank_statement_extractor.rb@@ -23,7 +23,7 @@ class Provider::Anthropic::BankStatementExtractor"PDF exceeds Anthropic's 32 MB limit (#{pdf_content.bytesize} bytes)"end- span = langfuse_trace&.span(name: "extract_bank_statement_api_call", input: {+ span = langfuse_trace&.generation(name: "extract_bank_statement_api_call", model: model, input: {model: model,pdf_size: pdf_content.bytesize})@@ -217,13 +217,4 @@ class Provider::Anthropic::BankStatementExtractordef block_input(block)block.respond_to?(:input) ? block.input : (block[:input] || block["input"])end-- def usage_hash(raw_usage)- return {} unless raw_usage- {- "input_tokens" => raw_usage.input_tokens.to_i,- "output_tokens" => raw_usage.output_tokens.to_i,- "total_tokens" => raw_usage.input_tokens.to_i + raw_usage.output_tokens.to_i- }- endenddiff --git a/app/models/provider/anthropic/bill_setup_suggester.rb b/app/models/provider/anthropic/bill_setup_suggester.rbindex b5ce43f38d..27c9d5596a 100644--- a/app/models/provider/anthropic/bill_setup_suggester.rb+++ b/app/models/provider/anthropic/bill_setup_suggester.rb@@ -16,7 +16,7 @@ class Provider::Anthropic::BillSetupSuggesterenddef suggest- span = langfuse_trace&.span(name: "suggest_bill_setup_api_call", input: {+ span = langfuse_trace&.generation(name: "suggest_bill_setup_api_call", model: model, input: {model: model,charges: charges,configure_mode: current_config.present?@@ -166,13 +166,4 @@ class Provider::Anthropic::BillSetupSuggesterdef block_input(block)block.respond_to?(:input) ? block.input : (block[:input] || block["input"])end-- def usage_hash(raw_usage)- return {} unless raw_usage- {- "input_tokens" => raw_usage.input_tokens.to_i,- "output_tokens" => raw_usage.output_tokens.to_i,- "total_tokens" => raw_usage.input_tokens.to_i + raw_usage.output_tokens.to_i- }- endenddiff --git a/app/models/provider/anthropic/concerns/usage_recorder.rb b/app/models/provider/anthropic/concerns/usage_recorder.rbindex 546440b640..fb31481de0 100644--- a/app/models/provider/anthropic/concerns/usage_recorder.rb+++ b/app/models/provider/anthropic/concerns/usage_recorder.rb@@ -3,6 +3,18 @@ module Provider::Anthropic::Concerns::UsageRecorderprivate+ def usage_hash(raw_usage)+ return {} unless raw_usage++ {+ "input_tokens" => raw_usage.input_tokens.to_i,+ "output_tokens" => raw_usage.output_tokens.to_i,+ "total_tokens" => raw_usage.input_tokens.to_i + raw_usage.output_tokens.to_i,+ "cache_creation_input_tokens" => raw_usage.respond_to?(:cache_creation_input_tokens) ? raw_usage.cache_creation_input_tokens.to_i : 0,+ "cache_read_input_tokens" => raw_usage.respond_to?(:cache_read_input_tokens) ? raw_usage.cache_read_input_tokens.to_i : 0+ }+ end+# Persists an LlmUsage row from an Anthropic Message#usage object.# Returns nil if no family is attached (e.g., system-initiated calls).def record_usage(model_name, raw_usage, operation:, metadata: {})diff --git a/app/models/provider/anthropic/pdf_processor.rb b/app/models/provider/anthropic/pdf_processor.rbindex aaceb71891..865d4355c4 100644--- a/app/models/provider/anthropic/pdf_processor.rb+++ b/app/models/provider/anthropic/pdf_processor.rb@@ -31,7 +31,7 @@ class Provider::Anthropic::PdfProcessor"PDF is too large (#{pdf_content.bytesize} bytes); base64-encoded it would exceed Anthropic's 32 MB request limit"end- span = langfuse_trace&.span(name: "process_pdf_api_call", input: {+ span = langfuse_trace&.generation(name: "process_pdf_api_call", model: model, input: {model: model,pdf_size: pdf_content&.bytesize})@@ -175,13 +175,4 @@ class Provider::Anthropic::PdfProcessordef block_input(block)block.respond_to?(:input) ? block.input : (block[:input] || block["input"])end-- def usage_hash(raw_usage)- return {} unless raw_usage- {- "input_tokens" => raw_usage.input_tokens.to_i,- "output_tokens" => raw_usage.output_tokens.to_i,- "total_tokens" => raw_usage.input_tokens.to_i + raw_usage.output_tokens.to_i- }- endenddiff --git a/app/models/provider/anthropic/provider_merchant_enhancer.rb b/app/models/provider/anthropic/provider_merchant_enhancer.rbindex 4ee94740a1..dec43f5762 100644--- a/app/models/provider/anthropic/provider_merchant_enhancer.rb+++ b/app/models/provider/anthropic/provider_merchant_enhancer.rb@@ -14,7 +14,7 @@ class Provider::Anthropic::ProviderMerchantEnhancerenddef enhance_merchants- span = langfuse_trace&.span(name: "enhance_provider_merchants_api_call", input: {+ span = langfuse_trace&.generation(name: "enhance_provider_merchants_api_call", model: model, input: {model: model,merchants: merchants})@@ -142,13 +142,4 @@ class Provider::Anthropic::ProviderMerchantEnhancerdef block_input(block)block.respond_to?(:input) ? block.input : (block[:input] || block["input"])end-- def usage_hash(raw_usage)- return {} unless raw_usage- {- "input_tokens" => raw_usage.input_tokens.to_i,- "output_tokens" => raw_usage.output_tokens.to_i,- "total_tokens" => raw_usage.input_tokens.to_i + raw_usage.output_tokens.to_i- }- endenddiff --git a/app/models/provider/openai.rb b/app/models/provider/openai.rbindex 08a3b7f144..71e759304f 100644--- a/app/models/provider/openai.rb+++ b/app/models/provider/openai.rb@@ -1,5 +1,6 @@class Provider::Openai < Providerinclude LlmConcept+ include LangfuseTraceable# Subclass so errors caught in this provider are raised as Provider::Openai::ErrorError = Class.new(Provider::Error)@@ -213,9 +214,12 @@ class Provider::Openai < Provider).auto_categorizeend- upsert_langfuse_trace(trace: trace, output: result.map(&:to_h))+ finish_langfuse_trace(trace: trace, output: result.map(&:to_h))result+ rescue => error+ finish_langfuse_trace(trace: trace, output: { error: error.message }, level: "ERROR")+ raiseendend@@ -238,9 +242,12 @@ class Provider::Openai < Providerfamily: family).suggest- upsert_langfuse_trace(trace: trace, output: result.to_h)+ finish_langfuse_trace(trace: trace, output: result.to_h)result+ rescue => error+ finish_langfuse_trace(trace: trace, output: { error: error.message }, level: "ERROR")+ raiseendend@@ -268,9 +275,12 @@ class Provider::Openai < Provider).auto_detect_merchantsend- upsert_langfuse_trace(trace: trace, output: result.map(&:to_h))+ finish_langfuse_trace(trace: trace, output: result.map(&:to_h))result+ rescue => error+ finish_langfuse_trace(trace: trace, output: { error: error.message }, level: "ERROR")+ raiseendend@@ -297,9 +307,12 @@ class Provider::Openai < Provider).enhance_merchantsend- upsert_langfuse_trace(trace: trace, output: result.map(&:to_h))+ finish_langfuse_trace(trace: trace, output: result.map(&:to_h))result+ rescue => error+ finish_langfuse_trace(trace: trace, output: { error: error.message }, level: "ERROR")+ raiseendend@@ -349,9 +362,12 @@ class Provider::Openai < Providerjson_mode: json_mode).process- upsert_langfuse_trace(trace: trace, output: result.to_h)+ finish_langfuse_trace(trace: trace, output: result.to_h)result+ rescue => error+ finish_langfuse_trace(trace: trace, output: { error: error.message }, level: "ERROR")+ raiseendend@@ -371,9 +387,12 @@ class Provider::Openai < Providerjson_mode: json_mode).extract- upsert_langfuse_trace(trace: trace, output: { transaction_count: result[:transactions].size })+ finish_langfuse_trace(trace: trace, output: { transaction_count: result[:transactions].size })result+ rescue => error+ finish_langfuse_trace(trace: trace, output: { error: error.message }, level: "ERROR")+ raiseendend@@ -510,6 +529,8 @@ class Provider::Openai < Providerinput_payload = chat_config.build_input(prompt: prompt)+ start_time = Time.current+beginrequest_params = {model: model,@@ -547,7 +568,8 @@ class Provider::Openai < Provideroutput: response.messages.map(&:output_text).join("\n"),usage: usage,session_id: session_id,- user_identifier: user_identifier+ user_identifier: user_identifier,+ start_time: start_time)record_llm_usage(family: family, model: model, operation: "chat", usage: usage)response@@ -561,7 +583,8 @@ class Provider::Openai < Provideroutput: parsed.messages.map(&:output_text).join("\n"),usage: raw_response["usage"],session_id: session_id,- user_identifier: user_identifier+ user_identifier: user_identifier,+ start_time: start_time)record_llm_usage(family: family, model: model, operation: "chat", usage: raw_response["usage"])parsed@@ -573,7 +596,8 @@ class Provider::Openai < Providerinput: input_payload,error: e,session_id: session_id,- user_identifier: user_identifier+ user_identifier: user_identifier,+ start_time: start_time)record_llm_usage(family: family, model: model, operation: "chat", error: e)raise@@ -615,6 +639,8 @@ class Provider::Openai < Providerparams[:tool_choice] = "none" if tool_choice == :none && tools.present?params[:max_tokens] = explicit_max_response_tokens if explicit_max_response_tokens+ start_time = Time.current+beginraw_response = session_client.chat(parameters: params)@@ -627,7 +653,8 @@ class Provider::Openai < Provideroutput: parsed.messages.map(&:output_text).join("\n"),usage: raw_response["usage"],session_id: session_id,- user_identifier: user_identifier+ user_identifier: user_identifier,+ start_time: start_time)record_llm_usage(family: family, model: model, operation: "chat", usage: raw_response["usage"])@@ -654,7 +681,8 @@ class Provider::Openai < Providerinput: messages,error: e,session_id: session_id,- user_identifier: user_identifier+ user_identifier: user_identifier,+ start_time: start_time)record_llm_usage(family: family, model: model, operation: "chat", error: e)raise@@ -750,41 +778,22 @@ class Provider::Openai < Providerendend- def langfuse_client- return unless ENV["LANGFUSE_PUBLIC_KEY"].present? && ENV["LANGFUSE_SECRET_KEY"].present?-- @langfuse_client = Langfuse.new- end-- def create_langfuse_trace(name:, input:, session_id: nil, user_identifier: nil)- return unless langfuse_client-- langfuse_client.trace(- name: name,- input: input,- session_id: session_id,- user_id: user_identifier,- environment: Rails.env- )- rescue => e- Rails.logger.warn("Langfuse trace creation failed: #{e.message}\n#{e.full_message}")- nil- end-- def log_langfuse_generation(name:, model:, input:, output: nil, usage: nil, error: nil, session_id: nil, user_identifier: nil)+ def log_langfuse_generation(name:, model:, input:, output: nil, usage: nil, error: nil, session_id: nil, user_identifier: nil, start_time: nil)return unless langfuse_clienttrace = create_langfuse_trace(name: "openai.#{name}",input: input,session_id: session_id,- user_identifier: user_identifier+ user_identifier: user_identifier,+ start_time: start_time)generation = trace&.generation(name: name,model: model,- input: input+ input: input,+ start_time: start_time)if error@@ -792,34 +801,19 @@ class Provider::Openai < Provideroutput: { error: error.message, details: error.respond_to?(:details) ? error.details : nil },level: "ERROR")- upsert_langfuse_trace(+ finish_langfuse_trace(trace: trace,output: { error: error.message },level: "ERROR")elsegeneration&.end(output: output, usage: usage)- upsert_langfuse_trace(trace: trace, output: output)+ finish_langfuse_trace(trace: trace, output: output)endrescue => eRails.logger.warn("Langfuse logging failed: #{e.message}\n#{e.full_message}")end- def upsert_langfuse_trace(trace:, output:, level: nil)- return unless langfuse_client && trace&.id-- payload = {- id: trace.id,- output: output- }- payload[:level] = level if level.present?-- langfuse_client.trace(**payload)- rescue => e- Rails.logger.warn("Langfuse trace upsert failed for trace_id=#{trace&.id}: #{e.message}\n#{e.full_message}")- nil- end-def record_llm_usage(family:, model:, operation:, usage: nil, error: nil)return unless familydiff --git a/app/models/provider/openai/auto_categorizer.rb b/app/models/provider/openai/auto_categorizer.rbindex d2c7c4d604..6c181ddb8e 100644--- a/app/models/provider/openai/auto_categorizer.rb+++ b/app/models/provider/openai/auto_categorizer.rb@@ -85,7 +85,7 @@ class Provider::Openai::AutoCategorizerprivatedef auto_categorize_openai_native- span = langfuse_trace&.span(name: "auto_categorize_api_call", input: {+ span = langfuse_trace&.generation(name: "auto_categorize_api_call", model: model.presence || Provider::Openai::DEFAULT_MODEL, input: {model: model.presence || Provider::Openai::DEFAULT_MODEL,transactions: transactions,user_categories: user_categories@@ -169,7 +169,7 @@ class Provider::Openai::AutoCategorizerenddef auto_categorize_with_mode(mode)- span = langfuse_trace&.span(name: "auto_categorize_api_call", input: {+ span = langfuse_trace&.generation(name: "auto_categorize_api_call", model: model.presence || Provider::Openai::DEFAULT_MODEL, input: {model: model.presence || Provider::Openai::DEFAULT_MODEL,transactions: transactions,user_categories: user_categories,diff --git a/app/models/provider/openai/auto_merchant_detector.rb b/app/models/provider/openai/auto_merchant_detector.rbindex cb018ba58f..5e4b850953 100644--- a/app/models/provider/openai/auto_merchant_detector.rb+++ b/app/models/provider/openai/auto_merchant_detector.rb@@ -96,7 +96,7 @@ class Provider::Openai::AutoMerchantDetectorprivatedef auto_detect_merchants_openai_native- span = langfuse_trace&.span(name: "auto_detect_merchants_api_call", input: {+ span = langfuse_trace&.generation(name: "auto_detect_merchants_api_call", model: model.presence || Provider::Openai::DEFAULT_MODEL, input: {model: model.presence || Provider::Openai::DEFAULT_MODEL,transactions: transactions,user_merchants: user_merchants@@ -177,7 +177,7 @@ class Provider::Openai::AutoMerchantDetectorenddef auto_detect_merchants_with_mode(mode)- span = langfuse_trace&.span(name: "auto_detect_merchants_api_call", input: {+ span = langfuse_trace&.generation(name: "auto_detect_merchants_api_call", model: model.presence || Provider::Openai::DEFAULT_MODEL, input: {model: model.presence || Provider::Openai::DEFAULT_MODEL,transactions: transactions,user_merchants: user_merchants,diff --git a/app/models/provider/openai/bill_setup_suggester.rb b/app/models/provider/openai/bill_setup_suggester.rbindex 23d37dd38c..8d9ff5f9cc 100644--- a/app/models/provider/openai/bill_setup_suggester.rb+++ b/app/models/provider/openai/bill_setup_suggester.rb@@ -27,7 +27,7 @@ class Provider::Openai::BillSetupSuggesterSuggestion = Provider::LlmConcept::BillSetupSuggestiondef suggest_with_format(response_format)- span = langfuse_trace&.span(name: "suggest_bill_setup_api_call", input: {+ span = langfuse_trace&.generation(name: "suggest_bill_setup_api_call", model: model, input: {model: model,charges: charges,configure_mode: current_config.present?diff --git a/app/models/provider/openai/pdf_processor.rb b/app/models/provider/openai/pdf_processor.rbindex 4059f21e0e..03c9771161 100644--- a/app/models/provider/openai/pdf_processor.rb+++ b/app/models/provider/openai/pdf_processor.rb@@ -19,14 +19,14 @@ class Provider::Openai::PdfProcessorenddef process- span = langfuse_trace&.span(name: "process_pdf_api_call", input: {+ span = langfuse_trace&.generation(name: "process_pdf_api_call", model: model.presence || Provider::Openai::DEFAULT_MODEL, input: {model: model.presence || Provider::Openai::DEFAULT_MODEL,pdf_size: pdf_content&.bytesize})# Try text extraction first (works with all models)# Fall back to vision API with images if text extraction fails (for scanned PDFs)- response = case processing_mode+ response, usage = case processing_modewhen :textprocess_with_text_extractionwhen :vision@@ -42,7 +42,7 @@ class Provider::Openai::PdfProcessorraise ArgumentError, "Unknown PDF processing mode: #{processing_mode.inspect}"end- span&.end(output: response.to_h)+ span&.end(output: response.to_h, usage: usage)responserescue => espan&.end(output: { error: e.message, error_detail: safe_error_detail(e) }, level: "ERROR")@@ -256,7 +256,7 @@ class Provider::Openai::PdfProcessorraw = response.dig("choices", 0, "message", "content")parsed = parse_json_flexibly(raw)- build_result(parsed)+ [ build_result(parsed), response["usage"] ]enddef build_result(parsed)diff --git a/app/models/provider/openai/provider_merchant_enhancer.rb b/app/models/provider/openai/provider_merchant_enhancer.rbindex 0afdd08157..c1e89e03e9 100644--- a/app/models/provider/openai/provider_merchant_enhancer.rb+++ b/app/models/provider/openai/provider_merchant_enhancer.rb@@ -87,7 +87,7 @@ class Provider::Openai::ProviderMerchantEnhancerprivatedef enhance_merchants_native- span = langfuse_trace&.span(name: "enhance_provider_merchants_api_call", input: {+ span = langfuse_trace&.generation(name: "enhance_provider_merchants_api_call", model: model.presence || Provider::Openai::DEFAULT_MODEL, input: {model: model.presence || Provider::Openai::DEFAULT_MODEL,merchants: merchants})@@ -156,7 +156,7 @@ class Provider::Openai::ProviderMerchantEnhancerenddef enhance_merchants_with_mode(mode)- span = langfuse_trace&.span(name: "enhance_provider_merchants_api_call", input: {+ span = langfuse_trace&.generation(name: "enhance_provider_merchants_api_call", model: model.presence || Provider::Openai::DEFAULT_MODEL, input: {model: model.presence || Provider::Openai::DEFAULT_MODEL,merchants: merchants,json_mode: modediff --git a/config/initializers/langfuse.rb b/config/initializers/langfuse.rbindex 320fdd78ed..d8f885acf1 100644--- a/config/initializers/langfuse.rb+++ b/config/initializers/langfuse.rb@@ -1,9 +1,11 @@-require "langfuse"+require "langfuse_tracing"if ENV["LANGFUSE_PUBLIC_KEY"].present? && ENV["LANGFUSE_SECRET_KEY"].present?- Langfuse.configure do |config|- config.public_key = ENV["LANGFUSE_PUBLIC_KEY"]- config.secret_key = ENV["LANGFUSE_SECRET_KEY"]- config.host = ENV["LANGFUSE_HOST"] if ENV["LANGFUSE_HOST"].present?- end+ Rails.configuration.x.langfuse = LangfuseTracing.new(+ public_key: ENV.fetch("LANGFUSE_PUBLIC_KEY"),+ secret_key: ENV.fetch("LANGFUSE_SECRET_KEY"),+ host: ENV["LANGFUSE_HOST"].presence || "https://cloud.langfuse.com"+ )++ at_exit { Rails.configuration.x.langfuse.shutdown }enddiff --git a/docs/hosting/ai.md b/docs/hosting/ai.mdindex 3491f90e21..9d78ac3551 100644--- a/docs/hosting/ai.md+++ b/docs/hosting/ai.md@@ -1030,6 +1030,8 @@ Langfuse helps you:4. Restart Sure+Sure sends completed observations through Langfuse's v4 OpenTelemetry ingestion path. Existing keys and host settings still apply. See the [Langfuse migration and validation notes](langfuse.md#langfuse-v4) before upgrading an existing project.+All LLM operations will now be logged to Langfuse, including:- Chat messages and responses- Auto-categorization requestsdiff --git a/docs/hosting/langfuse.md b/docs/hosting/langfuse.mdindex 23ecfdd877..2b822f4f55 100644--- a/docs/hosting/langfuse.md+++ b/docs/hosting/langfuse.md@@ -6,7 +6,7 @@ Source statement](https://langfuse.com/open-source).## Prerequisites-1. Create a Langfuse project (self‑hosted or using their cloud offering).+1. Create a Langfuse Cloud project, or use a self-hosted instance compatible with [v4 ingestion](https://langfuse.com/docs/compatibility).2. Copy the **public key** and **secret key** from the project's settings.## Configuration@@ -26,12 +26,33 @@ The initializer reads these values on boot and automatically enables tracing. If## What Gets Tracked-* `chat_response`-* `auto_categorize`-* `auto_detect_merchants`+* Chat responses+* Categorization and merchant detection/enrichment+* Bill suggestions and PDF processing+* Family document searchesEach call records the prompt, model, response, and token usage when available.## Viewing Traces-After starting the app with the variables set, visit your Langfuse dashboard to see traces and generations grouped under the `openai.*` traces.+After starting the app with the variables set, visit your Langfuse dashboard to see observations grouped under `openai.*`, `anthropic.*`, and `search_family_files` traces. Chat roots and their generations carry the same session ID and hashed user ID.++## Langfuse v4++Sure uses the native Ruby OpenTelemetry SDK and OTLP exporter. The existing keys and `LANGFUSE_HOST` remain unchanged; Sure sends completed observations to `/api/public/otel/v1/traces` with `x-langfuse-ingestion-version: 4`. Request and response data live on the root observation, with operation-specific data on its children. No separate trace input/output is written.++Observations are buffered in memory and exported in batches. The exporter retries transient failures; failed batches and overflowing buffers can lose observations. Normal process exit flushes pending observations with a 30-second timeout. Forced termination can lose buffered data. Tracing failures are reported through OpenTelemetry logging and do not change LLM results. This is best-effort telemetry, not durable delivery.++`evals:langfuse:run_experiment` writes one root observation per dataset item, with experiment identity, input, expected output, actual output, and item metadata. Scores reference that observation through `/api/public/scores`. Dataset CRUD and pagination remain unchanged. Experiment observations are flushed once per batch of up to 25 items before their scores are submitted. Export failures mark the batch as failed and skip its scores. Provider calls made in evaluation batches retain their separate operational traces; their token costs are not assigned to individual experiment items.++## Production cutover++Follow the [project migration workflow](https://raw.githubusercontent.com/langfuse/skills/main/skills/langfuse/references/v4-project-migration.md) and inspect the [Cloud migration status](https://cloud.langfuse.com/v4-migration). Langfuse Cloud manages its own server upgrade; only Sure needs redeploying. Cloud removes legacy ingestion on November 16, 2026.++Before deploying to production, configure a separate non-production project and exercise chat, a batched provider operation, a failed request, document search, and a dataset experiment. Inspect hierarchy, root input/output, model/usage, session IDs on every cost-bearing generation, session costs, and experiment scores. Repository tests verify the exported format and HTTP contract; they do not verify Cloud ingestion or project configuration.++Inspect active Legacy rules in [Evaluators](https://cloud.langfuse.com/project/~/evals). Provider roots are candidate targets for observation evaluators; experiment-item roots are candidate targets for dataset evaluator successors. These are code-derived suggestions, not project-verified contracts. Check each rule's filters, sampling and variable mappings against actual observations. Create successors disabled, validate them, and obtain approval before enabling them; retain disabled legacy rules for rollback. Do not restore deprecated trace input/output to avoid migrating evaluators.++Inspect Project Settings > Integrations for blob-storage, Mixpanel, PostHog, or other exports. Confirm downstream consumers support enriched observations before changing export sources. Preserve existing credentials, schedules, and formats.++Keep the prior Sure image available during rollout. Reverting to it restores legacy ingestion only while Cloud still accepts that ingestion path. After the Cloud cutoff, fix forward or temporarily disable tracing by removing its keys; rolling back Sure cannot restore a removed Cloud API.diff --git a/lib/langfuse_tracing.rb b/lib/langfuse_tracing.rbnew file mode 100644index 0000000000..acfe54513d--- /dev/null+++ b/lib/langfuse_tracing.rb@@ -0,0 +1,108 @@+require "opentelemetry/sdk"+require "opentelemetry-exporter-otlp"+require "base64"+require "json"++class LangfuseTracing+ def initialize(public_key:, secret_key:, host:, processor: nil, auto_flush: true)+ @provider = OpenTelemetry::SDK::Trace::TracerProvider.new+ @provider.add_span_processor(processor || OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new(+ OpenTelemetry::Exporter::OTLP::Exporter.new(+ endpoint: "#{host.chomp('/')}/api/public/otel/v1/traces",+ headers: {+ "Authorization" => "Basic #{Base64.strict_encode64("#{public_key}:#{secret_key}")}",+ "x-langfuse-ingestion-version" => "4"+ }+ ), start_thread_on_boot: auto_flush+ ))+ @tracer = @provider.tracer("sure.langfuse")+ end++ def trace(name:, input:, session_id: nil, user_id: nil, environment: Rails.env, metadata: {}, attributes: {}, start_time: nil)+ context = {+ "langfuse.trace.name" => name,+ "langfuse.session.id" => session_id,+ "langfuse.user.id" => user_id,+ "langfuse.environment" => environment.to_s+ }.compact.merge(attributes)+ metadata.each { |key, value| context["langfuse.trace.metadata.#{key}"] = value.is_a?(String) ? value : JSON.generate(value) }+ Observation.new(@tracer, name: name, input: input, attributes: context, start_time: start_time)+ end++ def flush+ @provider.force_flush(timeout: 30)+ end++ def shutdown+ @provider.shutdown(timeout: 30)+ end++ class Observation+ attr_reader :span_id, :id, :start_time++ def initialize(tracer, name:, input:, attributes:, parent: nil, type: "span", model: nil, start_time: nil)+ @tracer = tracer+ @attributes = attributes+ @start_time = start_time || Time.now+ @span = tracer.start_span(name, with_parent: parent || OpenTelemetry::Context.empty, attributes: attributes.merge(+ "langfuse.observation.type" => type,+ "langfuse.observation.input" => JSON.generate(input),+ "langfuse.observation.model.name" => model,+ "langfuse.internal.as_root" => parent.nil?+ ).compact, start_timestamp: @start_time)+ @id = @span.context.hex_trace_id+ @span_id = @span.context.hex_span_id+ end++ def span(name:, input:)+ child(name: name, input: input)+ end++ def generation(name:, input:, model:, start_time: nil)+ child(name: name, input: input, type: "generation", model: model, start_time: start_time)+ end++ def end(output: nil, usage: nil, level: nil)+ return unless @span.recording?++ @span.set_attribute("langfuse.observation.output", JSON.generate(output))+ @span.set_attribute("langfuse.observation.level", level) if level+ @span.status = OpenTelemetry::Trace::Status.error if level == "ERROR"+ @span.set_attribute("langfuse.observation.usage_details", JSON.generate(usage_details(usage))) if usage+ @span.finish+ rescue => error+ Rails.logger.warn("Langfuse observation failed: #{error.class}")+ ensure+ @span.finish if @span.recording?+ end++ def set_attributes(attributes)+ @span.add_attributes(attributes)+ end++ private++ def child(name:, input:, type: "span", model: nil, start_time: nil)+ self.class.new(@tracer, name: name, input: input, model: model, type: type,+ attributes: @attributes, parent: OpenTelemetry::Trace.context_with_span(@span), start_time: start_time)+ rescue => error+ Rails.logger.warn("Langfuse observation creation failed: #{error.class}")+ nil+ end++ def usage_details(usage)+ usage = usage.to_h.transform_keys(&:to_s)+ cached = usage.dig("prompt_tokens_details", "cached_tokens") || usage.dig("input_tokens_details", "cached_tokens")+ input = usage["input_tokens"] || usage["prompt_tokens"]+ details = {+ input: cached && input ? input - cached : input,+ output: usage["output_tokens"] || usage["completion_tokens"],+ input_cached_tokens: cached,+ cache_read_input_tokens: usage["cache_read_input_tokens"],+ cache_creation_input_tokens: usage["cache_creation_input_tokens"]+ }.compact+ total = details.key?(:input) && details.key?(:output) ? details.values.sum : usage["total_tokens"]+ details.merge(total: total).compact+ end+ end+enddiff --git a/test/controllers/admin/system_health_controller_test.rb b/test/controllers/admin/system_health_controller_test.rbindex 22c612f50c..6bce308d74 100644--- a/test/controllers/admin/system_health_controller_test.rb+++ b/test/controllers/admin/system_health_controller_test.rb@@ -915,9 +915,8 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTesttest "optional service rendering exposes no configured values and creates no clients" dosign_in users(:sure_support_staff)stub_healthy_sidekiq- Langfuse.stubs(:configuration).returns(OpenStruct.new(public_key: "optional-public-secret", secret_key: "optional-langfuse-secret"))Sentry.stubs(:configuration).returns(OpenStruct.new(dsn: "optional-sentry-secret", enabled_in_current_env?: true))- Langfuse.expects(:new).never+ LangfuseTracing.expects(:new).neverStripe::StripeClient.expects(:new).neverPostHog::Client.expects(:new).neverSentry.expects(:capture_exception).neverdiff --git a/test/lib/langfuse_tracing_test.rb b/test/lib/langfuse_tracing_test.rbnew file mode 100644index 0000000000..374c4fc590--- /dev/null+++ b/test/lib/langfuse_tracing_test.rb@@ -0,0 +1,159 @@+require "test_helper"++class LangfuseTracingTest < ActiveSupport::TestCase+ setup do+ @exporter = OpenTelemetry::SDK::Trace::Export::InMemorySpanExporter.new+ @client = LangfuseTracing.new(public_key: "pk-test", secret_key: "sk-test", host: "https://langfuse.test",+ processor: OpenTelemetry::SDK::Trace::Export::SimpleSpanProcessor.new(@exporter))+ end++ teardown do+ @client.shutdown+ end++ test "exports complete observations once with root IO and context on every child" do+ root = @client.trace(name: "openai.chat_response", input: { prompt: "Hello" }, session_id: "chat-1",+ user_id: "hashed-user", environment: "test", metadata: { workflow: "chat" }, attributes: {+ "langfuse.trace.tags" => [ "canary" ], "langfuse.version" => "1", "langfuse.release" => "commit", "langfuse.trace.public" => false+ })+ generation = root.generation(name: "chat_response", model: "gpt-4.1", input: "Hello")+ tool = root.span(name: "tool", input: "query")+ assert_empty @exporter.finished_spans++ generation.end(output: "Hi", usage: { "input_tokens" => 10, "output_tokens" => 5, "total_tokens" => 15 })+ tool.end(output: "result")+ root.end(output: "Hi")+ root.end(output: "duplicate")++ spans = @exporter.finished_spans+ assert_equal 3, spans.size+ assert_equal 1, spans.map(&:trace_id).uniq.size+ root_span = spans.find { |span| span.name == "openai.chat_response" }+ assert_equal({ "prompt" => "Hello" }, JSON.parse(root_span.attributes["langfuse.observation.input"]))+ assert_equal "Hi", JSON.parse(root_span.attributes["langfuse.observation.output"])+ assert root_span.attributes["langfuse.internal.as_root"]++ spans.each do |span|+ assert_equal "chat-1", span.attributes["langfuse.session.id"]+ assert_equal "hashed-user", span.attributes["langfuse.user.id"]+ assert_equal "test", span.attributes["langfuse.environment"]+ assert_equal "openai.chat_response", span.attributes["langfuse.trace.name"]+ assert_equal "chat", span.attributes["langfuse.trace.metadata.workflow"]+ assert_equal [ "canary" ], span.attributes["langfuse.trace.tags"]+ assert_equal "1", span.attributes["langfuse.version"]+ assert_equal "commit", span.attributes["langfuse.release"]+ assert_equal false, span.attributes["langfuse.trace.public"]+ refute span.attributes.key?("langfuse.trace.input")+ refute span.attributes.key?("langfuse.trace.output")+ assert_equal root_span.span_id, span.parent_span_id unless span == root_span+ end++ llm_span = spans.find { |span| span.name == "chat_response" }+ assert_equal "generation", llm_span.attributes["langfuse.observation.type"]+ assert_equal "gpt-4.1", llm_span.attributes["langfuse.observation.model.name"]+ assert_equal({ "input" => 10, "output" => 5, "total" => 15 }, JSON.parse(llm_span.attributes["langfuse.observation.usage_details"]))+ end++ test "keeps separate sessions isolated and records errors" do+ first = @client.trace(name: "first", input: "one", session_id: "session-one")+ second = @client.trace(name: "second", input: "two", session_id: "session-two")+ first.end(output: { error: "failed" }, level: "ERROR")+ second.end(output: "ok")++ failed, succeeded = @exporter.finished_spans+ assert_equal "session-one", failed.attributes["langfuse.session.id"]+ assert_equal "session-two", succeeded.attributes["langfuse.session.id"]+ refute_equal failed.trace_id, succeeded.trace_id+ assert_equal OpenTelemetry::Trace::Status::ERROR, failed.status.code+ assert_equal "ERROR", failed.attributes["langfuse.observation.level"]+ end++ test "normalizes OpenAI cached tokens without counting them twice" do+ root = @client.trace(name: "chat", input: "prompt")+ root.generation(name: "chat", input: "prompt", model: "gpt-4.1").end(output: "answer", usage: {+ "prompt_tokens" => 100, "completion_tokens" => 20, "total_tokens" => 120,+ "prompt_tokens_details" => { "cached_tokens" => 60 }+ })+ usage = JSON.parse(@exporter.finished_spans.first.attributes["langfuse.observation.usage_details"])+ assert_equal 40, usage["input"]+ assert_equal 60, usage["input_cached_tokens"]+ assert_equal 120, usage["total"]+ root.end+ end++ test "preserves Anthropic cache usage and original request timing" do+ start_time = 2.seconds.ago+ root = @client.trace(name: "chat", input: "prompt", start_time: start_time)+ root.generation(name: "chat", input: "prompt", model: "claude-sonnet-4-6", start_time: root.start_time).end(output: "answer", usage: {+ "input_tokens" => 10, "output_tokens" => 20, "cache_read_input_tokens" => 50, "cache_creation_input_tokens" => 30+ })+ span = @exporter.finished_spans.first+ usage = JSON.parse(span.attributes["langfuse.observation.usage_details"])+ assert_equal 10, usage["input"]+ assert_equal 50, usage["cache_read_input_tokens"]+ assert_equal 30, usage["cache_creation_input_tokens"]+ assert_equal 110, usage["total"]+ assert_in_delta start_time.to_f, span.start_timestamp / 1_000_000_000.0, 0.001+ root.end+ end++ test "flush sends OTLP to the configured host with v4 authentication headers" do+ request = stub_request(:post, "https://langfuse.test/api/public/otel/v1/traces")+ .with(headers: { "Authorization" => "Basic #{Base64.strict_encode64('pk-test:sk-test')}", "x-langfuse-ingestion-version" => "4" })+ .to_return(status: 200, body: "")+ client = LangfuseTracing.new(public_key: "pk-test", secret_key: "sk-test", host: "https://langfuse.test/")+ client.trace(name: "request", input: "prompt").end(output: "response")+ assert_equal OpenTelemetry::SDK::Trace::Export::SUCCESS, client.flush+ assert_requested request, times: 1+ ensure+ client&.shutdown+ end++ test "provider failures finish their roots without changing the provider response" do+ Rails.configuration.x.stubs(:langfuse).returns(@client)+ with_env_overrides("LANGFUSE_PUBLIC_KEY" => "pk-test", "LANGFUSE_SECRET_KEY" => "sk-test") do+ [ Provider::Openai, Provider::Anthropic ].each do |provider_class|+ provider_class::AutoCategorizer.any_instance.stubs(:auto_categorize).raises(StandardError, "LLM unavailable")+ response = provider_class.new("test-token").auto_categorize(+ transactions: [ { id: "transaction", description: "Coffee" } ], user_categories: [ { id: "category", name: "Dining" } ])+ refute response.success?+ assert_equal "LLM unavailable", response.error.message+ end+ end+ assert_equal 2, @exporter.finished_spans.size+ @exporter.finished_spans.each do |span|+ assert_equal "ERROR", span.attributes["langfuse.observation.level"]+ assert_equal({ "error" => "LLM unavailable" }, JSON.parse(span.attributes["langfuse.observation.output"]))+ end+ end++ test "shutdown flushes pending observations and a failed flush reports failure" do+ request = stub_request(:post, "https://langfuse.test/api/public/otel/v1/traces").to_return(status: 401)+ client = LangfuseTracing.new(public_key: "pk-test", secret_key: "sk-test", host: "https://langfuse.test")+ client.trace(name: "request", input: "prompt").end(output: "response")+ assert_equal OpenTelemetry::SDK::Trace::Export::FAILURE, client.flush+ request.to_return(status: 200, body: "")+ client.trace(name: "second", input: "prompt").end(output: "response")+ client.shutdown+ assert_requested request, times: 2+ end++ test "tracing finalization failures preserve the original provider error" do+ [ Provider::Openai, Provider::Anthropic ].each do |provider_class|+ original_error = provider_class::Error.new("LLM unavailable", failure_code: :provider_unavailable)+ provider_class::AutoCategorizer.any_instance.stubs(:auto_categorize).raises(original_error)+ trace = mock+ trace.expects(:end).with(output: { error: "LLM unavailable" }, level: "ERROR").raises(StandardError, "Tracing unavailable")+ provider = provider_class.new("test-token")+ provider.stubs(:create_langfuse_trace).returns(trace)+ Rails.logger.expects(:warn).with("Langfuse trace finalization failed: StandardError: Tracing unavailable")++ response = provider.auto_categorize(transactions: [ { id: "transaction", description: "Coffee" } ],+ user_categories: [ { id: "category", name: "Dining" } ])++ refute response.success?+ assert_equal original_error.message, response.error.message+ assert_equal :provider_unavailable, response.error.failure_code+ end+ end+enddiff --git a/test/models/assistant/function/search_family_files_test.rb b/test/models/assistant/function/search_family_files_test.rbindex 2545968102..974a9ef04e 100644--- a/test/models/assistant/function/search_family_files_test.rb+++ b/test/models/assistant/function/search_family_files_test.rb@@ -126,4 +126,21 @@ class Assistant::Function::SearchFamilyFilesTest < ActiveSupport::TestCase@function.call("query" => "test", "max_results" => 50)end++ test "returns the search failure when tracing finalization also fails" do+ @user.family.update!(vector_store_id: "vs_test123")+ adapter = mock+ adapter.expects(:search).raises(StandardError, "Search unavailable")+ VectorStore::Registry.stubs(:adapter).returns(adapter)+ trace = mock+ trace.expects(:end).with(output: { error: "Search unavailable" }, level: "ERROR").raises(StandardError, "Tracing unavailable")+ @function.stubs(:create_langfuse_trace).returns(trace)+ Rails.logger.expects(:warn).with("Langfuse trace finalization failed: StandardError: Tracing unavailable")++ result = @function.call("query" => "tax return")++ assert_equal false, result[:success]+ assert_equal "search_failed", result[:error]+ assert_equal "An error occurred while searching documents: Search unavailable", result[:message]+ endenddiff --git a/test/models/configuration_health/optional_services_test.rb b/test/models/configuration_health/optional_services_test.rbindex d9ebc9c360..edd9fe2706 100644--- a/test/models/configuration_health/optional_services_test.rb+++ b/test/models/configuration_health/optional_services_test.rb@@ -10,13 +10,11 @@ class ConfigurationHealth::OptionalServicesTest < ActiveSupport::TestCasesetup do@health = ConfigurationHealth::OptionalServices.new- @langfuse = OpenStruct.new(public_key: nil, secret_key: nil)@posthog = Rails.configuration.x.posthog.clone@posthog.api_key = nil@posthog.host = "https://us.i.posthog.com"@posthog.development_enabled = false@posthog.feedback_enabled = true- Langfuse.stubs(:configuration).returns(@langfuse)Sentry.stubs(:configuration).returns(nil)Rails.configuration.x.stubs(:posthog).returns(@posthog)Rails.application.config.stubs(:app_mode).returns("managed".inquiry)@@ -24,7 +22,7 @@ class ConfigurationHealth::OptionalServicesTest < ActiveSupport::TestCaseendtest "absent optional services are informational and initialize no clients" do- Langfuse.expects(:new).never+ LangfuseTracing.expects(:new).neverSentry.expects(:init).neverSentry.expects(:capture_exception).neverSentry.expects(:capture_message).never@@ -57,7 +55,7 @@ class ConfigurationHealth::OptionalServicesTest < ActiveSupport::TestCaseendtest "Langfuse reports both environment keys without initializing a client" do- Langfuse.expects(:new).never+ LangfuseTracing.expects(:new).neverwith_environment("LANGFUSE_PUBLIC_KEY" => "private-public", "LANGFUSE_SECRET_KEY" => "private-secret") doassert_equal :configured, @health.langfuse.statusassert_no_match(/private-/, @health.langfuse.inspect)diff --git a/test/models/eval/langfuse_client_test.rb b/test/models/eval/langfuse_client_test.rbindex 023e2608c6..d3d0aa5122 100644--- a/test/models/eval/langfuse_client_test.rb+++ b/test/models/eval/langfuse_client_test.rb@@ -2,6 +2,82 @@ require "test_helper"require "ostruct"class Eval::LangfuseClientTest < ActiveSupport::TestCase+ test "writes experiment context and attaches scores to the root observation" do+ exporter = OpenTelemetry::SDK::Trace::Export::InMemorySpanExporter.new+ tracing = LangfuseTracing.new(public_key: "pk-test", secret_key: "sk-test", host: "https://langfuse.test",+ processor: OpenTelemetry::SDK::Trace::Export::SimpleSpanProcessor.new(exporter))+ LangfuseTracing.stubs(:new).returns(tracing)+ client = Eval::Langfuse::Client.new(public_key: "pk-test", secret_key: "sk-test", host: "https://langfuse.test")+ observation = client.create_experiment_item(name: "categorization_eval", input: { transaction: "Coffee" },+ output: "Dining", expected_output: "Dining", experiment_id: "experiment-id", experiment_name: "candidate",+ dataset_id: "dataset-id", item_id: "item-id", metadata: { difficulty: "easy" })+ span = exporter.finished_spans.sole+ assert_equal "experiment", span.attributes["langfuse.environment"]+ assert_equal "experiment-id", span.attributes["langfuse.experiment.id"]+ assert_equal "candidate", span.attributes["langfuse.experiment.name"]+ assert_equal "dataset-id", span.attributes["langfuse.experiment.dataset.id"]+ assert_equal "item-id", span.attributes["langfuse.experiment.item.id"]+ assert_equal observation.span_id, span.attributes["langfuse.experiment.item.root_observation_id"]+ assert_equal "Dining", JSON.parse(span.attributes["langfuse.experiment.item.expected_output"])+ assert_equal "Dining", JSON.parse(span.attributes["langfuse.observation.output"])+ assert_equal "easy", span.attributes["langfuse.experiment.item.metadata.difficulty"]++ score = stub_request(:post, "https://langfuse.test/api/public/scores")+ .with(basic_auth: [ "pk-test", "sk-test" ], body: {+ traceId: observation.id, observationId: observation.span_id, name: "accuracy", value: 1.0, dataType: "NUMERIC", environment: "experiment"+ }.to_json).to_return(status: 200, body: '{"id":"score-id"}')+ assert_equal "score-id", client.create_score(trace_id: observation.id, observation_id: observation.span_id, name: "accuracy", value: 1.0)["id"]+ assert_requested score+ ensure+ client&.shutdown+ end++ test "raises when experiment ingestion cannot be flushed" do+ tracing = mock+ observation = stub(span_id: "span-id")+ observation.expects(:set_attributes)+ observation.expects(:end).with(output: "result")+ tracing.expects(:trace).returns(observation)+ tracing.expects(:flush).returns(OpenTelemetry::SDK::Trace::Export::FAILURE)+ LangfuseTracing.stubs(:new).returns(tracing)+ client = Eval::Langfuse::Client.new(public_key: "pk-test", secret_key: "sk-test")+ client.create_experiment_item(name: "eval", input: "input", output: "result", expected_output: "expected",+ experiment_id: "experiment-id", experiment_name: "run", dataset_id: "dataset-id", item_id: "item-id")+ assert_raises(Eval::Langfuse::Client::ApiError) { client.flush_experiment_items }+ end++ test "buffers experiment items until the batch is explicitly flushed" do+ exporter = OpenTelemetry::SDK::Trace::Export::InMemorySpanExporter.new+ tracing = LangfuseTracing.new(public_key: "pk-test", secret_key: "sk-test", host: "https://langfuse.test",+ processor: OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new(exporter, start_thread_on_boot: false))+ LangfuseTracing.stubs(:new).returns(tracing)+ client = Eval::Langfuse::Client.new(public_key: "pk-test", secret_key: "sk-test")++ 25.times do |index|+ client.create_experiment_item(name: "eval", input: "input", output: "result", expected_output: "expected",+ experiment_id: "experiment-id", experiment_name: "run", dataset_id: "dataset-id", item_id: "item-#{index}")+ end+ assert_empty exporter.finished_spans++ client.flush_experiment_items++ assert_equal 25, exporter.finished_spans.size+ assert_equal 25, exporter.finished_spans.map(&:span_id).uniq.size+ ensure+ client&.shutdown+ end++ test "preserves dataset pagination and configured host" do+ request = stub_request(:get, "https://langfuse.test/api/public/dataset-items")+ .with(query: { datasetName: "eval_chat", page: 2, limit: 50 }, basic_auth: [ "pk-test", "sk-test" ])+ .to_return(status: 200, body: '{"data":[{"id":"item-51"}],"meta":{"page":2}}')+ client = Eval::Langfuse::Client.new(public_key: "pk-test", secret_key: "sk-test", host: "https://langfuse.test/")+ response = client.get_dataset_items(dataset_name: "eval_chat", page: 2)+ assert_equal "item-51", response.fetch("data").sole.fetch("id")+ assert_equal 2, response.dig("meta", "page")+ assert_requested request+ end+# -- CRL error list --test "crl_errors includes standard CRL error codes" dodiff --git a/test/models/eval/langfuse_experiment_runner_test.rb b/test/models/eval/langfuse_experiment_runner_test.rbnew file mode 100644index 0000000000..0710932fac--- /dev/null+++ b/test/models/eval/langfuse_experiment_runner_test.rb@@ -0,0 +1,121 @@+require "test_helper"++class Eval::LangfuseExperimentRunnerTest < ActiveSupport::TestCase+ test "runs an experiment with dataset identity and observation scores" do+ dataset = stub(name: "categories", eval_type: "categorization", sample_count: 1)+ exporter = mock+ exporter.expects(:export)+ Eval::Langfuse::DatasetExporter.expects(:new).with(dataset, client: anything).returns(exporter)+ client = mock+ client.expects(:get_dataset).with(name: "eval_categories").returns({ "id" => "dataset-id" })+ client.expects(:get_dataset_items).with(dataset_name: "eval_categories", page: 1, limit: 50).returns({ "data" => [ {+ "id" => "item-id", "input" => { "transaction" => { "description" => "Coffee" }, "categories" => [ { "name" => "Dining" } ] },+ "expectedOutput" => { "category_name" => "Dining" }, "metadata" => { "difficulty" => "easy" }+ } ] })+ observation = stub(id: "trace-id", span_id: "span-id")+ client.expects(:create_experiment_item).with do |args|+ args[:dataset_id] == "dataset-id" && args[:item_id] == "item-id" && args[:experiment_id].present? &&+ args[:experiment_name] == "candidate" && args[:output] == "Dining" &&+ args[:expected_output] == { "category_name" => "Dining" } && args[:metadata]["difficulty"] == "easy"+ end.returns(observation)+ scoring = sequence("flush before scoring")+ client.expects(:flush_experiment_items).in_sequence(scoring)+ client.expects(:create_score).with(trace_id: "trace-id", observation_id: "span-id", name: "accuracy", value: 1.0, comment: "Correct").in_sequence(scoring)+ client.expects(:shutdown)+ provider = mock+ provider.expects(:auto_categorize).returns(Provider::Response.new(success?: true, error: nil,+ data: [ Provider::LlmConcept::AutoCategorization.new(transaction_id: "item-id", category_name: "Dining") ]))+ runner = Eval::Langfuse::ExperimentRunner.new(dataset, model: "gpt-4.1", client: client)+ runner.stubs(:llm_provider).returns(provider)++ result = runner.run(run_name: "candidate")++ assert_equal "candidate", result[:run_name]+ assert_equal 1, result[:samples_processed]+ assert_equal 100.0, result[:metrics][:accuracy]+ end++ [ false, true ].each do |export_fails|+ test "flushes once per batch and #{export_fails ? 'skips scores for failed exports' : 'scores after export'}" do+ dataset = stub(name: "categories", eval_type: "categorization", sample_count: 26)+ exporter = mock+ exporter.expects(:export)+ client = mock+ Eval::Langfuse::DatasetExporter.expects(:new).with(dataset, client: client).returns(exporter)+ client.expects(:get_dataset).returns({ "id" => "dataset-id" })+ items = 26.times.map do |index|+ { "id" => "item-#{index}", "input" => { "description" => "Coffee" }, "expectedOutput" => { "category_name" => "Dining" } }+ end+ client.expects(:get_dataset_items).returns({ "data" => items })+ ordering = sequence("batched export and scores")+ items.each_slice(25).with_index do |batch, index|+ batch.each do |item|+ client.expects(:create_experiment_item).with { |args| args[:item_id] == item["id"] }+ .returns(stub(id: "trace-#{item['id']}", span_id: "span-#{item['id']}")).in_sequence(ordering)+ end+ flush = client.expects(:flush_experiment_items).in_sequence(ordering)+ if export_fails && index.zero?+ flush.raises(Eval::Langfuse::Client::ApiError, "Export failed")+ else+ batch.each do |item|+ client.expects(:create_score).with(trace_id: "trace-#{item['id']}", observation_id: "span-#{item['id']}",+ name: "accuracy", value: 1.0, comment: "Correct").in_sequence(ordering)+ end+ end+ end+ client.expects(:shutdown)+ provider = mock+ provider.expects(:auto_categorize).twice.returns(Provider::Response.new(success?: true, error: nil,+ data: items.map { |item| Provider::LlmConcept::AutoCategorization.new(transaction_id: item["id"], category_name: "Dining") }))+ runner = Eval::Langfuse::ExperimentRunner.new(dataset, model: "gpt-4.1", client: client)+ runner.stubs(:llm_provider).returns(provider)++ result = runner.run(run_name: "candidate")++ assert_equal 26, result[:samples_processed]+ assert_equal export_fails ? 1 : 26, result[:metrics][:correct]+ assert_equal export_fails ? 25 : 0, result[:metrics][:incorrect]+ end+ end++ [ "categorization", "merchant_detection" ].each do |eval_type|+ test "discards queued scores after a partial #{eval_type} batch fails" do+ dataset = stub(name: "transactions", eval_type: eval_type, sample_count: 26)+ exporter = mock+ exporter.expects(:export)+ client = mock+ Eval::Langfuse::DatasetExporter.expects(:new).with(dataset, client: client).returns(exporter)+ client.expects(:get_dataset).returns({ "id" => "dataset-id" })+ items = 26.times.map do |index|+ { "id" => "item-#{index}", "input" => { "description" => "Coffee" },+ "expectedOutput" => { "category_name" => "Dining", "business_name" => "Cafe", "business_url" => "https://cafe.test" } }+ end+ client.expects(:get_dataset_items).returns({ "data" => items })+ client.expects(:create_experiment_item).with { |args| args[:item_id] == "item-0" }+ .returns(stub(id: "trace-0", span_id: "span-0"))+ client.expects(:create_experiment_item).with { |args| args[:item_id] == "item-1" }+ .raises(Eval::Langfuse::Client::ApiError, "Observation creation failed")+ client.expects(:create_experiment_item).with { |args| args[:item_id] == "item-25" }+ .returns(stub(id: "trace-25", span_id: "span-25"))+ client.expects(:flush_experiment_items).twice+ client.expects(:create_score).with(trace_id: "trace-25", observation_id: "span-25", name: "accuracy", value: 1.0, comment: "Correct")+ client.expects(:shutdown)+ provider = mock+ if eval_type == "categorization"+ data = items.map { |item| Provider::LlmConcept::AutoCategorization.new(transaction_id: item["id"], category_name: "Dining") }+ provider.expects(:auto_categorize).twice.returns(Provider::Response.new(success?: true, error: nil, data: data))+ else+ data = items.map { |item| Provider::LlmConcept::AutoDetectedMerchant.new(transaction_id: item["id"], business_name: "Cafe", business_url: "https://cafe.test") }+ provider.expects(:auto_detect_merchants).twice.returns(Provider::Response.new(success?: true, error: nil, data: data))+ end+ runner = Eval::Langfuse::ExperimentRunner.new(dataset, model: "gpt-4.1", client: client)+ runner.stubs(:llm_provider).returns(provider)++ result = runner.run(run_name: "candidate")++ assert_equal 26, result[:samples_processed]+ assert_equal 1, result[:metrics][:correct]+ assert_equal 25, result[:metrics][:incorrect]+ end+ end+enddiff --git a/test/models/provider/anthropic/pdf_processor_test.rb b/test/models/provider/anthropic/pdf_processor_test.rbindex 2be3e32eee..5ac664eacd 100644--- a/test/models/provider/anthropic/pdf_processor_test.rb+++ b/test/models/provider/anthropic/pdf_processor_test.rb@@ -6,6 +6,24 @@ class Provider::Anthropic::PdfProcessorTest < ActiveSupport::TestCase@pdf_content = "%PDF-1.4 fake bytes".bend+ [ {}, { cache_creation_input_tokens: 30, cache_read_input_tokens: 50 } ].each do |cache_usage|+ test "exports token usage with #{cache_usage.empty? ? 'missing' : 'populated'} cache fields" do+ response = build_response(content: [ tool_use_block(id: "toolu_1", name: "report_document_analysis",+ input: { "summary" => "Statement", "document_type" => "bank_statement" }) ],+ usage: { input_tokens: 10, output_tokens: 20 }.merge(cache_usage))+ span = mock+ span.expects(:end).with do |args|+ args[:usage] == { "input_tokens" => 10, "output_tokens" => 20, "total_tokens" => 30,+ "cache_creation_input_tokens" => cache_usage.fetch(:cache_creation_input_tokens, 0),+ "cache_read_input_tokens" => cache_usage.fetch(:cache_read_input_tokens, 0) }+ end+ result = Provider::Anthropic::PdfProcessor.new(stub_client(response), model: "claude-sonnet-4-6",+ pdf_content: @pdf_content, langfuse_trace: stub(generation: span)).process++ assert_equal "Statement", result.summary+ end+ end+test "sends PDF as native document content block and parses tool response" dofake_response = build_response(content: [tool_use_block(@@ -201,7 +219,7 @@ class Provider::Anthropic::PdfProcessorTest < ActiveSupport::TestCasespan = mockspan.expects(:end).with { |args| yield(args[:output]); true }trace = mock- trace.stubs(:span).returns(span)+ trace.stubs(:generation).returns(span)traceend@@ -221,7 +239,7 @@ class Provider::Anthropic::PdfProcessorTest < ActiveSupport::TestCaseid: "msg_test",model: "claude-sonnet-4-6",content: content,- usage: OpenStruct.new(input_tokens: usage[:input_tokens], output_tokens: usage[:output_tokens])+ usage: OpenStruct.new(usage))enddiff --git a/test/models/provider/openai/pdf_processor_test.rb b/test/models/provider/openai/pdf_processor_test.rbindex 018e1f2f06..d804d9eba3 100644--- a/test/models/provider/openai/pdf_processor_test.rb+++ b/test/models/provider/openai/pdf_processor_test.rb@@ -5,6 +5,30 @@ class Provider::Openai::PdfProcessorTest < ActiveSupport::TestCase@pdf_content = "%PDF-1.4 fake bytes".bend+ [ :text, :vision ].each do |mode|+ test "exports response usage in #{mode} mode without changing the parsed result" do+ usage = { "prompt_tokens" => 100, "completion_tokens" => 20, "total_tokens" => 120,+ "prompt_tokens_details" => { "cached_tokens" => 60 } }+ client = mock+ client.expects(:chat).returns({ "usage" => usage, "choices" => [ { "message" => {+ "content" => { summary: "Statement", document_type: "bank_statement", extracted_data: {} }.to_json+ } } ] })+ span = mock+ span.expects(:end).with(output: { summary: "Statement", document_type: "bank_statement", extracted_data: {} }, usage: usage)+ trace = stub(generation: span)+ processor = Provider::Openai::PdfProcessor.new(client, model: "gpt-4.1", pdf_content: @pdf_content,+ max_response_tokens: 512, processing_mode: mode, langfuse_trace: trace)+ processor.stubs(:extract_text_from_pdf).returns("Statement text")+ processor.stubs(:convert_pdf_to_images).returns([ "base64-image" ])++ result = processor.process++ assert_instance_of Provider::LlmConcept::PdfProcessingResult, result+ assert_equal "Statement", result.summary+ assert_equal "bank_statement", result.document_type+ end+ end+test "extracts only allowlisted error fields into span output when the API call fails" doerror = StandardError.new("boom")def error.response_body@@ -72,7 +96,7 @@ class Provider::Openai::PdfProcessorTest < ActiveSupport::TestCasemax_response_tokens: 512,processing_mode: :text)- processor.expects(:process_with_text_extraction).returns(expected)+ processor.expects(:process_with_text_extraction).returns([ expected, nil ])processor.expects(:process_with_vision).neverassert_equal expected, processor.process@@ -92,7 +116,7 @@ class Provider::Openai::PdfProcessorTest < ActiveSupport::TestCaseprocessing_mode: :vision)processor.expects(:process_with_text_extraction).never- processor.expects(:process_with_vision).returns(expected)+ processor.expects(:process_with_vision).returns([ expected, nil ])assert_equal expected, processor.processend@@ -347,7 +371,7 @@ class Provider::Openai::PdfProcessorTest < ActiveSupport::TestCasespan = mockspan.expects(:end).with { |args| yield(args[:output]); true }trace = mock- trace.stubs(:span).returns(span)+ trace.stubs(:generation).returns(span)traceend# Builds a processor around a mocked client for the json_mode tests.diff --git a/test/models/provider/openai_test.rb b/test/models/provider/openai_test.rbindex fd4ec8cf23..a7461b6483 100644--- a/test/models/provider/openai_test.rb+++ b/test/models/provider/openai_test.rb@@ -598,17 +598,31 @@ class Provider::OpenaiTest < ActiveSupport::TestCaseassert_equal "configured model: custom-model", custom_provider.supported_models_descriptionend- test "upsert_langfuse_trace uses client trace upsert" do- trace = Struct.new(:id).new("trace_123")- fake_client = mock-- fake_client.expects(:trace).with(id: "trace_123", output: { ok: true }, level: "ERROR")- @subject.stubs(:langfuse_client).returns(fake_client)+ test "finishes the root observation with output and error level" do+ trace = mock+ trace.expects(:end).with(output: { ok: true }, level: "ERROR")+ @subject.send(:finish_langfuse_trace, trace: trace, output: { ok: true }, level: "ERROR")+ end- @subject.send(:upsert_langfuse_trace, trace: trace, output: { ok: true }, level: "ERROR")+ test "configured tracing emits chat observations through the shared OpenTelemetry client" do+ exporter = OpenTelemetry::SDK::Trace::Export::InMemorySpanExporter.new+ tracing = LangfuseTracing.new(public_key: "pk-test", secret_key: "sk-test", host: "https://langfuse.test",+ processor: OpenTelemetry::SDK::Trace::Export::SimpleSpanProcessor.new(exporter))+ Rails.configuration.x.stubs(:langfuse).returns(tracing)+ with_env_overrides("LANGFUSE_PUBLIC_KEY" => "pk-test", "LANGFUSE_SECRET_KEY" => "sk-test") do+ @subject.send(:log_langfuse_generation, name: "chat_response", model: "gpt-4.1", input: "Hi", output: "Hello",+ usage: { "prompt_tokens" => 4, "completion_tokens" => 2 }, session_id: "chat-id", user_identifier: "hashed-id")+ end+ assert_equal 2, exporter.finished_spans.size+ exporter.finished_spans.each do |span|+ assert_equal "chat-id", span.attributes["langfuse.session.id"]+ assert_equal "hashed-id", span.attributes["langfuse.user.id"]+ end+ ensure+ tracing&.shutdownend- test "log_langfuse_generation upserts trace through client" do+ test "log_langfuse_generation finishes generation and root observation" dotrace = Struct.new(:id).new("trace_456")generation = mockfake_client = mock@@ -616,7 +630,7 @@ class Provider::OpenaiTest < ActiveSupport::TestCase@subject.stubs(:langfuse_client).returns(fake_client)@subject.stubs(:create_langfuse_trace).returns(trace)- fake_client.expects(:trace).with(id: "trace_456", output: "hello")+ trace.expects(:end).with(output: "hello", level: nil)trace.expects(:generation).returns(generation)generation.expects(:end).with(output: "hello", usage: { "total_tokens" => 10 })@@ -630,14 +644,14 @@ class Provider::OpenaiTest < ActiveSupport::TestCase)end- test "create_langfuse_trace logs full error details" do+ test "create_langfuse_trace logs the error without its backtrace" dofake_client = mockerror = StandardError.new("boom")@subject.stubs(:langfuse_client).returns(fake_client)fake_client.expects(:trace).raises(error)- Rails.logger.expects(:warn).with(regexp_matches(/Langfuse trace creation failed: boom.*test\/models\/provider\/openai_test\.rb/m))+ Rails.logger.expects(:warn).with("Langfuse trace creation failed: StandardError: boom")@subject.send(:create_langfuse_trace, name: "openai.test", input: { foo: "bar" })end