The personal finance app for everyone (by everyone)
Ruby
Add Jev (TypeSafe) as a transaction-categorization provider (#3660)
Will Wilson8dd0394a0953
diff --git a/.env.example b/.env.exampleindex e72599c43d..53dcb8950b 100644--- a/.env.example+++ b/.env.example@@ -65,6 +65,20 @@ OPENAI_URI_BASE=# OPENAI_SUPPORTS_RESPONSES_ENDPOINT= # Override Responses-API vs chat.completions routing# LLM_JSON_MODE= # auto | strict | json_object | none+# Optional: Jev (TypeSafe) — a classification provider used for transaction+# categorization. It answers typed questions with calibrated probabilities+# rather than generating text, so it is never used for chat or PDF processing+# and is configured independently of LLM_PROVIDER.+# JEV_API_KEY= # Required to enable Jev; no fallback to other keys+# CATEGORIZATION_PROVIDER= # llm | jev — overrides each family's choice+# JEV_ENDPOINT= # Default: https://api.typesafe.ai/v1/systemone+# JEV_MODEL= # Default: jev-latest+# Defaults go straight to TypeSafe. To reach Jev through a gateway such as+# OpenRouter instead -- which means your transaction descriptions transit that+# provider too -- set both:+# JEV_ENDPOINT=https://openrouter.ai/api/alpha/decisions+# JEV_MODEL=~typesafe/jev-latest+# Optional: document-search vector store. Hosted OpenAI is selected by default# when OPENAI_ACCESS_TOKEN is configured. For a local OpenAI-compatible LLM,# use pgvector plus a separate OpenAI-compatible embeddings endpoint.diff --git a/app/components/DS/note.html.erb b/app/components/DS/note.html.erbnew file mode 100644index 0000000000..8adda7177c--- /dev/null+++ b/app/components/DS/note.html.erb@@ -0,0 +1,6 @@+<%= tag.div class: container_classes, **container_opts do %>+ <% if title.present? %>+ <p class="font-medium text-primary"><%= title %></p>+ <% end %>+ <%= content %>+<% end %>diff --git a/app/components/DS/note.rb b/app/components/DS/note.rbnew file mode 100644index 0000000000..0dcc1fff54--- /dev/null+++ b/app/components/DS/note.rb@@ -0,0 +1,23 @@+# Quiet inset panel for standing explanatory copy, such as a data-sharing notice+# or a retention policy. Use DS::Alert instead for something that just became+# true, since it announces through an ARIA live region. Use DS::Card for a+# raised surface rather than an inset one.+class DS::Note < DesignSystemComponent+ attr_reader :title, :opts++ def initialize(title: nil, **opts)+ @title = title+ @opts = opts+ end++ def container_classes+ class_names(+ "rounded-md border border-secondary p-3 bg-container-inset text-xs text-secondary space-y-1",+ opts[:class]+ )+ end++ def container_opts+ opts.except(:class)+ end+enddiff --git a/app/controllers/rules_controller.rb b/app/controllers/rules_controller.rbindex 377e081a41..cdadd21230 100644--- a/app/controllers/rules_controller.rb+++ b/app/controllers/rules_controller.rb@@ -66,17 +66,7 @@ class RulesController < ApplicationControllerdef confirm# Compute provider, model, and cost estimation for auto-categorize actionsif @rule.actions.any? { |a| a.action_type == "auto_categorize" }- # Use the same provider determination logic as Family::AutoCategorizer- llm_provider = Provider::Registry.get_provider(:openai)-- if llm_provider- @selected_model = Provider::Openai.effective_model- @estimated_cost = LlmUsage.estimate_auto_categorize_cost(- transaction_count: @rule.affected_resource_count,- category_count: @rule.family.categories.count,- model: @selected_model- )- end+ @selected_model, @estimated_cost = auto_categorize_estimate(@rule)endend@@ -110,16 +100,10 @@ class RulesController < ApplicationController# Compute AI cost estimation if any rule has auto_categorize actionif @rules.any? { |r| r.actions.any? { |a| a.action_type == "auto_categorize" } }- llm_provider = Provider::Registry.get_provider(:openai)-- if llm_provider- @selected_model = Provider::Openai.effective_model- @estimated_cost = LlmUsage.estimate_auto_categorize_cost(- transaction_count: @total_affected_count,- category_count: Current.family.categories.count,- model: @selected_model- )- end+ @selected_model, @estimated_cost = auto_categorize_estimate(+ Current.family,+ transaction_count: @total_affected_count+ )endend@@ -134,6 +118,27 @@ class RulesController < ApplicationControllerendprivate+ # Names the provider that will actually run, and prices against it.+ #+ # This previously hardcoded :openai, so an Anthropic install was quoted the+ # wrong model and a family on Jev was quoted a provider that would not run+ # at all. LlmUsage has no pricing for Jev, so the cost comes back nil and the+ # view says so rather than inventing a figure.+ def auto_categorize_estimate(scope, transaction_count: nil)+ family = scope.is_a?(Rule) ? scope.family : scope+ count = transaction_count || scope.affected_resource_count+ model = family.categorization_model_name+ return [ nil, nil ] if model.blank?++ cost = LlmUsage.estimate_auto_categorize_cost(+ transaction_count: count,+ category_count: family.categories.count,+ model: model+ )++ [ model, cost ]+ end+# The reset itself happens in a background job, so an enqueue that never# lands looks exactly like a job that ran and found nothing. Logging the# request separately from the job's own "started" entry tells those apart.diff --git a/app/controllers/settings/hostings_controller.rb b/app/controllers/settings/hostings_controller.rbindex fe73027168..37abed4f6d 100644--- a/app/controllers/settings/hostings_controller.rb+++ b/app/controllers/settings/hostings_controller.rb@@ -212,6 +212,27 @@ class Settings::HostingsController < ApplicationControllerendend+ update_encrypted_setting(:jev_api_key)++ if hosting_params.key?(:jev_endpoint)+ raw_endpoint = hosting_params[:jev_endpoint].to_s.strip+ if raw_endpoint.blank?+ Setting.jev_endpoint = nil+ else+ # Provider::Jev owns the rule so settings, JEV_ENDPOINT and eval-time+ # construction cannot drift apart; the controller's job is only to turn+ # a rejection into a message instead of a 500.+ unless Provider::Jev.endpoint_allowed?(raw_endpoint)+ raise Setting::ValidationError, t(".invalid_jev_endpoint")+ end+ Setting.jev_endpoint = raw_endpoint+ end+ end++ if hosting_params.key?(:jev_model)+ Setting.jev_model = hosting_params[:jev_model].presence+ end+LLM_NUMERIC_MINIMUMS.each do |key, minimum|next unless hosting_params.key?(key)raw = hosting_params[key].to_s.strip@@ -238,6 +259,8 @@ class Settings::HostingsController < ApplicationControllerendupdate_assistant_type+ update_categorization_provider+ update_categorization_tuningredirect_to settings_hosting_path, notice: t(".success")rescue Setting::ValidationError => error@@ -249,6 +272,8 @@ class Settings::HostingsController < ApplicationController@openai_model_input = hosting_params[:openai_model] if hosting_params.key?(:openai_model)@anthropic_base_url_input = hosting_params[:anthropic_base_url] if hosting_params.key?(:anthropic_base_url)@anthropic_model_input = hosting_params[:anthropic_model] if hosting_params.key?(:anthropic_model)+ @jev_endpoint_input = hosting_params[:jev_endpoint] if hosting_params.key?(:jev_endpoint)+ @jev_model_input = hosting_params[:jev_model] if hosting_params.key?(:jev_model)flash.now[:alert] = error.messagerender :show, status: :unprocessable_entityend@@ -273,7 +298,58 @@ class Settings::HostingsController < ApplicationController# Strong parameters for the self-hosting settings form.def hosting_paramsreturn ActionController::Parameters.new unless params.key?(:setting)- params.require(:setting).permit(:onboarding_state, :require_email_confirmation, :invite_only_default_family_id, :brand_fetch_client_id, :brand_fetch_high_res_logos, :twelve_data_api_key, :tiingo_api_key, :eodhd_api_key, :alpha_vantage_api_key, :tinkoff_invest_api_key, :mansa_api_key, :rentcast_api_key, :realie_api_key, :openai_access_token, :openai_uri_base, :openai_model, :openai_json_mode, :anthropic_access_token, :anthropic_base_url, :anthropic_model, :llm_provider, :llm_context_window, :llm_max_response_tokens, :llm_max_items_per_call, :openai_request_timeout, :ai_response_timeout, :exchange_rate_provider, :securities_provider, :syncs_include_pending, :auto_sync_enabled, :auto_sync_time, :external_assistant_url, :external_assistant_token, :external_assistant_agent_id, securities_providers: [])+ params.require(:setting).permit(:onboarding_state, :require_email_confirmation, :invite_only_default_family_id, :brand_fetch_client_id, :brand_fetch_high_res_logos, :twelve_data_api_key, :tiingo_api_key, :eodhd_api_key, :alpha_vantage_api_key, :tinkoff_invest_api_key, :mansa_api_key, :rentcast_api_key, :realie_api_key, :openai_access_token, :openai_uri_base, :openai_model, :openai_json_mode, :anthropic_access_token, :anthropic_base_url, :anthropic_model, :jev_api_key, :jev_endpoint, :jev_model, :llm_provider, :llm_context_window, :llm_max_response_tokens, :llm_max_items_per_call, :openai_request_timeout, :ai_response_timeout, :exchange_rate_provider, :securities_provider, :syncs_include_pending, :auto_sync_enabled, :auto_sync_time, :external_assistant_url, :external_assistant_token, :external_assistant_agent_id, securities_providers: [])+ end++ # Family-scoped, like assistant_type: it decides whose transaction data is+ # sent to Jev. Guarded by the preview gate because the selector that submits+ # it is only rendered for opted-in users.+ def update_categorization_provider+ return unless params[:family].present? && params[:family][:categorization_provider].present?+ return if ENV["CATEGORIZATION_PROVIDER"].present?+ return unless preview_features_enabled?++ provider = params[:family][:categorization_provider]+ return unless Family::CATEGORIZATION_PROVIDERS.include?(provider)++ Current.family.update!(categorization_provider: provider)+ end++ # Family-scoped like categorization_provider. Validated here rather than+ # leaning on the DB check constraint, which would surface as a 500 instead+ # of the inline error the rest of this form gives.+ def update_categorization_tuning+ return unless params[:family].present?+ return unless preview_features_enabled?++ updates = {}++ if params[:family][:categorization_confidence_threshold].present? && ENV["CATEGORIZATION_CONFIDENCE_THRESHOLD"].blank?+ updates[:categorization_confidence_threshold] = unit_interval!(+ params[:family][:categorization_confidence_threshold],+ t("settings.hostings.categorization_provider_selector.confidence_threshold_label")+ )+ end++ if params[:family][:categorization_shadow_rate].present? && ENV["CATEGORIZATION_SHADOW_RATE"].blank?+ updates[:categorization_shadow_rate] = unit_interval!(+ params[:family][:categorization_shadow_rate],+ t("settings.hostings.categorization_provider_selector.shadow_rate_label")+ )+ end++ Current.family.update!(updates) if updates.any?+ end++ def unit_interval!(raw, field_label)+ value = Float(raw.to_s.strip) rescue nil++ if value.nil? || value.negative? || value > 1+ raise Setting::ValidationError,+ t("settings.hostings.update.invalid_categorization_rate", field: field_label)+ end++ valueenddef update_assistant_typediff --git a/app/models/categorization_comparison.rb b/app/models/categorization_comparison.rbnew file mode 100644index 0000000000..f7025254dd--- /dev/null+++ b/app/models/categorization_comparison.rb@@ -0,0 +1,30 @@+# One transaction categorized twice, by the provider in use and by the one that+# is not. Recorded by Family::AutoCategorizer when shadow mode samples a run;+# only the applied provider's answer reaches the transaction.+#+# `shadow_confidence` is null unless the shadow provider reports one, which the+# LLM providers never do.+class CategorizationComparison < ApplicationRecord+ belongs_to :family+ # Not named `transaction`: ActiveRecord already defines that method, and an+ # association of that name raises on load.+ belongs_to :categorized_transaction,+ class_name: "Transaction",+ foreign_key: :transaction_id,+ optional: true,+ inverse_of: false++ validates :applied_provider, :shadow_provider, presence: true++ scope :disagreements, -> { where(agreed: false) }+ scope :chronological, -> { order(:created_at) }++ # Share of sampled transactions where the two providers picked the same+ # category. Both answering "no category" counts as agreement.+ def self.agreement_rate+ total = count+ return nil if total.zero?++ (where(agreed: true).count.to_f / total * 100).round(2)+ end+enddiff --git a/app/models/eval/langfuse/experiment_runner.rb b/app/models/eval/langfuse/experiment_runner.rbindex 8c9b6e1cc4..6552532529 100644--- a/app/models/eval/langfuse/experiment_runner.rb+++ b/app/models/eval/langfuse/experiment_runner.rb@@ -8,7 +8,12 @@ class Eval::Langfuse::ExperimentRunner@model = model@provider = provider@client = client || Eval::Langfuse::Client.new- @provider_config = provider_config+ # This class reads provider_config with symbol keys, but the same config is+ # spelled with string keys everywhere else — Eval::Run#provider_config is a+ # jsonb column, so it always reads back as strings. Normalizing means a+ # caller passing either spelling gets the configured value instead of+ # silently falling through to ENV.+ @provider_config = (provider_config || {}).with_indifferent_accessenddef run(run_name: nil)@@ -348,23 +353,11 @@ class Eval::Langfuse::ExperimentRunner@llm_provider ||= build_providerend+ # Mirrors Eval::Runners::Base#build_provider — the two runners construct+ # providers independently, so a provider added to one has to be added here+ # too or Langfuse experiments reject it.def build_provider- case provider- when "openai"- access_token = provider_config[:access_token] ||- ENV["OPENAI_ACCESS_TOKEN"] ||- Setting.openai_access_token-- raise "OpenAI access token not configured" unless access_token.present?-- uri_base = provider_config[:uri_base] ||- ENV["OPENAI_URI_BASE"] ||- Setting.openai_uri_base-- Provider::Openai.new(access_token, uri_base: uri_base, model: model)- else- raise "Unsupported provider: #{provider}"- end+ Eval::ProviderFactory.build(provider: provider, model: model, config: provider_config)end# Determine the effective JSON mode for a batch based on expected null ratiodiff --git a/app/models/eval/metrics/base.rb b/app/models/eval/metrics/base.rbindex e602113d94..e90d039fdc 100644--- a/app/models/eval/metrics/base.rb+++ b/app/models/eval/metrics/base.rb@@ -36,17 +36,54 @@ class Eval::Metrics::Base(correct_count.to_f / total_count * 100).round(2)end+ # A provider outage, an expired API key or a stale model slug records every+ # sample as incorrect, which is indistinguishable from genuinely wrong+ # answers in the accuracy figure alone — a 404 reads as a plausible 0%.+ # Counting errored samples separately keeps a broken run from being mistaken+ # for a benchmark result.+ def error_count+ # Memoized because `results` is a relation, not a loaded collection —+ # error_rate and samples_errored would otherwise each re-query.+ @error_count ||= results.where("metadata->>'error' IS NOT NULL").count+ end++ def error_rate+ return 0.0 if total_count.zero?+ (error_count.to_f / total_count * 100).round(2)+ end++ # Whether the provider's stated confidence tracks how often it was right.+ # Absent for providers that report no confidence, which is a different thing+ # from being badly calibrated — see Eval::Metrics::Calibration.+ def calibration+ @calibration ||= Eval::Metrics::Calibration.new(eval_run)+ end+def avg_latency_msreturn nil if total_count.zero?results.average(:latency_ms)&.round(0)end+ # nil when no result reported a cost at all, which is NOT the same as a run+ # that cost nothing. `sum` returns 0 over all-NULL, so without this guard an+ # uninstrumented provider reports as free — the OpenAI path never populates+ # `cost`, and TypeSafe's native API returns token counts without a settled+ # price (only the OpenRouter gateway prices each call). Reporting those as+ # $0.00 would make the cheapest-provider comparison pick whichever provider+ # measures cost least.+ def cost_reported?+ return @cost_reported if defined?(@cost_reported)+ @cost_reported = results.where.not(cost: nil).exists?+ end+def total_cost+ return nil unless cost_reported?results.sum(:cost)&.to_f&.round(6)enddef cost_per_samplereturn nil if total_count.zero?+ return nil unless cost_reported?(total_cost / total_count).round(6)enddiff --git a/app/models/eval/metrics/calibration.rb b/app/models/eval/metrics/calibration.rbnew file mode 100644index 0000000000..4b7cf9ef09--- /dev/null+++ b/app/models/eval/metrics/calibration.rb@@ -0,0 +1,121 @@+# Compares a provider's stated confidence against how often it was actually+# right. A provider that says 0.9 should be right about nine times in ten; one+# that says 0.9 and is right six times in ten has confidence that cannot be+# used to gate anything.+#+# This is reported separately from accuracy because it answers a different+# question. Accuracy asks "how often is it right"; calibration asks "does it+# know when it is wrong" — which is what decides whether a confidence threshold+# can drive product behaviour, such as auto-applying a category versus queueing+# it for review.+#+# Providers that report no confidence at all (the next-token path) are not+# badly calibrated, they are unmeasurable. `supported?` distinguishes the two so+# a caller never reads an absent signal as a bad one.+class Eval::Metrics::Calibration+ BUCKET_COUNT = 10+ BUCKET_WIDTH = 1.0 / BUCKET_COUNT++ def initialize(eval_run)+ @eval_run = eval_run+ end++ def supported?+ scored.any?+ end++ def sample_count+ scored.size+ end++ # One entry per populated bucket: how confident the provider said it was, and+ # how often it was actually right at that confidence.+ def curve+ @curve ||= scored.group_by { |confidence, _correct| bucket_index(confidence) }.sort.map do |index, entries|+ count = entries.size+ mean_confidence = entries.sum { |confidence, _| confidence } / count+ accuracy = entries.count { |_, correct| correct }.to_f / count++ {+ range: bucket_label(index),+ count: count,+ mean_confidence: mean_confidence.round(4),+ accuracy: accuracy.round(4),+ # Negative means overconfident: it claimed more certainty than it earned.+ gap: (accuracy - mean_confidence).round(4)+ }+ end+ end++ # Weighted mean distance between stated confidence and observed accuracy.+ # 0.0 is perfect; 0.1 means the provider is out by ten points on average.+ def expected_calibration_error+ return nil unless supported?++ total = sample_count.to_f+ curve.sum { |bucket| (bucket[:count] / total) * bucket[:gap].abs }.round(4)+ end++ # Confidence that systematically overstates accuracy is the dangerous+ # direction: it is what would auto-apply a wrong category.+ def overconfident?+ return false unless supported?++ weighted_gap = curve.sum { |bucket| (bucket[:count] / sample_count.to_f) * bucket[:gap] }+ weighted_gap < -0.05+ end++ def to_h+ return { supported: false } unless supported?++ {+ supported: true,+ sample_count: sample_count,+ expected_calibration_error: expected_calibration_error,+ overconfident: overconfident?,+ buckets: curve+ }+ end++ def to_table+ return "No confidence reported — calibration cannot be measured for this provider." unless supported?++ lines = []+ lines << format("%-12s %7s %12s %10s %8s", "Confidence", "Samples", "Claimed", "Actual", "Gap")+ lines << "-" * 53++ curve.each do |bucket|+ lines << format(+ "%-12s %7d %11.1f%% %9.1f%% %+7.1f",+ bucket[:range],+ bucket[:count],+ bucket[:mean_confidence] * 100,+ bucket[:accuracy] * 100,+ bucket[:gap] * 100+ )+ end++ lines << "-" * 53+ lines << format("Expected calibration error: %.1f points%s",+ expected_calibration_error * 100,+ overconfident? ? " (overconfident)" : "")+ lines.join("\n")+ end++ private+ def scored+ @scored ||= @eval_run.results+ .where("metadata->>'confidence' IS NOT NULL")+ .pluck(Arel.sql("(metadata->>'confidence')::float"), :correct)+ end++ def bucket_index(confidence)+ return 0 if confidence.negative?++ [ (confidence / BUCKET_WIDTH).floor, BUCKET_COUNT - 1 ].min+ end++ def bucket_label(index)+ format("%.1f-%.1f", index * BUCKET_WIDTH, (index + 1) * BUCKET_WIDTH)+ end+enddiff --git a/app/models/eval/metrics/categorization_metrics.rb b/app/models/eval/metrics/categorization_metrics.rbindex 04e81b62e5..557d3c2bbc 100644--- a/app/models/eval/metrics/categorization_metrics.rb+++ b/app/models/eval/metrics/categorization_metrics.rb@@ -11,9 +11,12 @@ class Eval::Metrics::CategorizationMetrics < Eval::Metrics::Basehierarchical_accuracy: hierarchical_accuracy,samples_processed: total_count,samples_correct: correct_count,+ samples_errored: error_count,+ error_rate: error_rate,avg_latency_ms: avg_latency_ms,total_cost: total_cost,cost_per_sample: cost_per_sample,+ calibration: calibration.to_h,by_difficulty: metrics_by_difficulty,by_category: metrics_by_category}diff --git a/app/models/eval/provider_factory.rb b/app/models/eval/provider_factory.rbnew file mode 100644index 0000000000..a440c4e937--- /dev/null+++ b/app/models/eval/provider_factory.rb@@ -0,0 +1,64 @@+# Builds the provider an eval run exercises.+#+# Separate from Provider::Registry because evals need per-run overrides the+# registry deliberately does not accept: a model chosen per run, credentials+# from the run's own config, and provider knobs like Jev's concurrency. The+# registry answers "what is this install configured to use"; this answers "what+# is this particular run measuring".+#+# Both Eval::Runners::Base and Eval::Langfuse::ExperimentRunner call this. They+# previously carried their own copies, so adding a provider meant two edits with+# no failure signal if you made only one.+class Eval::ProviderFactory+ Error = Class.new(StandardError)++ # config arrives as jsonb (string keys) from Eval::Run and as a plain hash+ # from ExperimentRunner, so it is normalized rather than trusted either way.+ def self.build(provider:, model:, config: {})+ new(provider: provider, model: model, config: config).build+ end++ def initialize(provider:, model:, config: {})+ @provider = provider.to_s+ @model = model+ @config = (config || {}).with_indifferent_access+ end++ def build+ case provider+ when "openai" then build_openai+ when "jev" then build_jev+ else raise Error, "Unsupported provider: #{provider}"+ end+ end++ private+ attr_reader :provider, :model, :config++ def build_openai+ access_token = config[:access_token].presence ||+ ENV["OPENAI_ACCESS_TOKEN"].presence ||+ Setting.openai_access_token++ raise Error, "OpenAI access token not configured" unless access_token.present?++ uri_base = config[:uri_base].presence ||+ ENV["OPENAI_URI_BASE"].presence ||+ Setting.openai_uri_base++ Provider::Openai.new(access_token, uri_base: uri_base, model: model)+ end++ def build_jev+ api_key = config[:api_key].presence || Provider::Jev.api_key # pipelock:ignore++ raise Error, "Jev API key not configured" unless api_key.present?++ Provider::Jev.new(+ api_key,+ endpoint: config[:endpoint].presence || Provider::Jev.effective_endpoint,+ model: model,+ concurrency: config[:concurrency]+ )+ end+enddiff --git a/app/models/eval/reporters/cascade_report.rb b/app/models/eval/reporters/cascade_report.rbnew file mode 100644index 0000000000..f67e070479--- /dev/null+++ b/app/models/eval/reporters/cascade_report.rb@@ -0,0 +1,207 @@+# Reports the categorization cascade as it actually runs in production:+# Family::BayesCategorizer first, then a paid provider on whatever Bayes+# declined.+#+# The reason this exists rather than a three-column accuracy table: a flat table+# credits every provider for the easy rows Bayes would have absorbed for free,+# so it measures work the provider never performs. The number that decides+# whether a provider is worth paying for is its accuracy on the residual — the+# tail Bayes could not classify, which is systematically harder than the dataset+# average.+#+# Both legs must have been run over the same test split (same seed and ratio),+# or the residual is not the residual. Mismatches are reported rather than+# silently papered over.+class Eval::Reporters::CascadeReport+ def initialize(bayes_run:, provider_runs:)+ @bayes_run = bayes_run+ @provider_runs = Array(provider_runs)+ end++ def to_s+ lines = []+ lines << "=" * 78+ lines << "Categorization cascade — #{bayes_run.dataset.name}"+ lines << "=" * 78+ lines << split_description+ lines << ""+ lines.concat(split_mismatch_warnings)+ lines << stage_one+ lines << ""+ lines << stage_two+ lines << ""+ lines << cascade_totals+ lines << ""+ lines << (degenerate_bayes? ? DEGENERATE_WARNING : LIMITATION)+ lines.join("\n")+ end++ # Zero coverage means the dataset could not train the model, not that the+ # model declined to classify. Callers use this to avoid quoting the number.+ def degenerate_bayes?+ bayes_results.any? && bayes_covered.empty?+ end++ def summary+ {+ bayes: {+ covered: bayes_covered.size,+ declined: bayes_declined_sample_ids.size,+ test_size: bayes_results.size,+ coverage: percentage(bayes_covered.size, bayes_results.size),+ accuracy_on_covered: percentage(bayes_correct.size, bayes_covered.size)+ },+ providers: provider_runs.to_h { |run| [ label_for(run), provider_summary(run) ] }+ }+ end++ private+ attr_reader :bayes_run, :provider_runs++ # Coverage of zero is not a result. It means the dataset could not train the+ # model at all, and a reader must not carry away "Bayes classified nothing"+ # as a finding about Bayes.+ DEGENERATE_WARNING = <<~TEXT.strip+ THIS RUN DOES NOT MEASURE BAYES. Coverage is zero, which on a golden+ dataset means the model had nothing to generalize from rather than that it+ failed. These datasets carry roughly one transaction per distinct merchant,+ so a held-out sample shares almost no vocabulary with training, and what it+ does share is generic (state codes, digits) rather than merchant identity.+ Measured on categorization_golden_v2: the highest confidence any held-out+ sample reached was 0.217 against a 0.70 gate, with a median of 0.087, and+ a uniform guess across 23 categories is 0.043. There is no signal to+ threshold.++ Consequently the residual below is the entire test set, so the provider+ columns are identical and the cascade cannot be assessed from this data.+ Evaluating Bayes needs a dataset with realistic repetition — the same+ merchants recurring, as a real family's history does. Until then, treat+ the Stage 1 row as "not measured", not as zero.+ TEXT++ LIMITATION = <<~TEXT.strip+ Caveat on the Bayes leg: a golden dataset is roughly one transaction per+ distinct merchant, while a real family's history is the same few merchants+ repeating. Naive Bayes depends on that repetition and has almost none here,+ so its coverage below is close to a worst case and very likely understates+ production. The provider-on-residual figures inherit that: if Bayes really+ covers more in production, the residual is harder still than shown here.+ TEXT++ def split_description+ describe = bayes_run.provider_config.slice("split_role", "split_seed", "split_ratio")+ counts = bayes_results.size+ nulls = bayes_results.count(&:null_expected)+ "Split: #{describe.to_json} — test set #{counts} samples (#{nulls} null-expected)"+ end++ def split_mismatch_warnings+ keys = %w[split_seed split_ratio split_role]+ expected = bayes_run.provider_config.slice(*keys)++ provider_runs.filter_map do |run|+ actual = run.provider_config.slice(*keys)+ next if actual == expected++ "WARNING: #{label_for(run)} ran on a different split (#{actual.to_json}); " \+ "its residual figures are not comparable.\n"+ end+ end++ def stage_one+ covered = bayes_covered.size+ total = bayes_results.size+ correct = bayes_correct.size++ [+ "STAGE 1 — naive Bayes (local, no API cost)",+ format(" covered %4d / %-4d (%s of test set)", covered, total, percentage_s(covered, total)),+ format(" accuracy on covered %s", percentage_s(correct, covered)),+ format(" resolved correctly %4d / %-4d (%s of test set)", correct, total, percentage_s(correct, total))+ ].join("\n")+ end++ def stage_two+ residual = bayes_declined_sample_ids+ rows = provider_runs.map do |run|+ s = provider_summary(run)+ format(+ " %-26s %-12s %-14s %s",+ label_for(run),+ percentage_s(s[:residual_correct], s[:residual_scored]),+ percentage_s(s[:full_correct], s[:full_scored]),+ s[:residual_scored] == residual.size ? "" : "(only #{s[:residual_scored]}/#{residual.size} of residual scored)"+ ).rstrip+ end++ [+ "STAGE 2 — on the #{residual.size} samples Bayes declined",+ format(" %-26s %-12s %-14s", "provider", "on residual", "on full test"),+ format(" %-26s %-12s %-14s", "-" * 26, "-" * 12, "-" * 14),+ *rows,+ "",+ " The gap between those two columns is what a full-dataset benchmark",+ " overstates: the left column is the work the provider actually receives."+ ].join("\n")+ end++ def cascade_totals+ total = bayes_results.size+ rows = provider_runs.map do |run|+ s = provider_summary(run)+ combined = bayes_correct.size + s[:residual_correct]+ format(" bayes + %-20s %4d / %-4d (%s)", label_for(run), combined, total, percentage_s(combined, total))+ end++ [ "CASCADE TOTAL — share of the test set resolved correctly end to end", *rows ].join("\n")+ end++ def provider_summary(run)+ results = run.results.includes(:sample).to_a+ residual = results.select { |result| bayes_declined_sample_ids.include?(result.eval_sample_id) }++ {+ residual_scored: residual.size,+ residual_correct: residual.count(&:correct),+ residual_accuracy: percentage(residual.count(&:correct), residual.size),+ full_scored: results.size,+ full_correct: results.count(&:correct),+ full_accuracy: percentage(results.count(&:correct), results.size)+ }+ end++ def bayes_results+ @bayes_results ||= bayes_run.results.includes(:sample).to_a+ end++ def bayes_covered+ @bayes_covered ||= bayes_results.reject { |result| declined?(result) }+ end++ def bayes_correct+ @bayes_correct ||= bayes_covered.select(&:correct)+ end++ def bayes_declined_sample_ids+ @bayes_declined_sample_ids ||= bayes_results.select { |result| declined?(result) }.map(&:eval_sample_id).to_set+ end++ def declined?(result)+ result.metadata["declined"] == true+ end++ def label_for(run)+ "#{run.provider}:#{run.model}"+ end++ def percentage(numerator, denominator)+ return nil if denominator.to_i.zero?++ (numerator.to_f / denominator * 100).round(1)+ end++ def percentage_s(numerator, denominator)+ value = percentage(numerator, denominator)+ value.nil? ? "n/a" : "#{value}%"+ end+enddiff --git a/app/models/eval/reporters/comparison_reporter.rb b/app/models/eval/reporters/comparison_reporter.rbindex eda8b0a68b..ca9ab19b03 100644--- a/app/models/eval/reporters/comparison_reporter.rb+++ b/app/models/eval/reporters/comparison_reporter.rb@@ -2,7 +2,10 @@ class Eval::Reporters::ComparisonReporterattr_reader :runsdef initialize(runs)- @runs = Array(runs).sort_by(&:model)+ # Sorted and identified by provider as well as model: the same model name+ # can be served by more than one provider, and a comparison run exists+ # precisely to put two providers side by side.+ @runs = Array(runs).sort_by { |run| [ run.provider.to_s, run.model.to_s ] }end# Generate a text table for terminal display@@ -59,17 +62,23 @@ class Eval::Reporters::ComparisonReporter{best_accuracy: {+ provider: best_accuracy.provider,model: best_accuracy.model,+ label: run_label(best_accuracy),value: best_accuracy.metrics["accuracy"],run_id: best_accuracy.id},lowest_cost: {+ provider: lowest_cost.provider,model: lowest_cost.model,+ label: run_label(lowest_cost),value: lowest_cost.total_cost&.to_f,run_id: lowest_cost.id},fastest: {+ provider: fastest.provider,model: fastest.model,+ label: run_label(fastest),value: fastest.metrics["avg_latency_ms"],run_id: fastest.id},@@ -91,13 +100,14 @@ class Eval::Reporters::ComparisonReporterprivatedef build_headers- [ "Model", "Status", "Accuracy", "Precision", "Recall", "F1", "Latency (ms)", "Cost ($)", "Samples" ]+ [ "Provider", "Model", "Status", "Accuracy", "Precision", "Recall", "F1", "Latency (ms)", "Cost ($)", "Samples" ]enddef build_row(run)metrics = run.metrics || {}[+ run.provider,run.model,run.status,format_percentage(metrics["accuracy"]),@@ -146,6 +156,13 @@ class Eval::Reporters::ComparisonReporter]end+ # Identifies a run in prose and in summary keys. Model alone is ambiguous+ # once two providers are in the same comparison — and can collide outright+ # when both serve the same model name.+ def run_label(run)+ "#{run.provider}:#{run.model}"+ end+def format_percentage(value)return "-" if value.nil?"#{value}%"@@ -163,6 +180,7 @@ class Eval::Reporters::ComparisonReporterruns.combination(2).each do |run1, run2|comparisons << {models: [ run1.model, run2.model ],+ labels: [ run_label(run1), run_label(run2) ],accuracy_diff: ((run1.metrics["accuracy"] || 0) - (run2.metrics["accuracy"] || 0)).round(2),cost_diff: ((run1.total_cost || 0) - (run2.total_cost || 0)).to_f.round(6),latency_diff: ((run1.metrics["avg_latency_ms"] || 0) - (run2.metrics["avg_latency_ms"] || 0)).round(0)@@ -176,19 +194,19 @@ class Eval::Reporters::ComparisonReporter# If one model wins all categoriesif best_accuracy.id == lowest_cost.id && lowest_cost.id == fastest.id- return "#{best_accuracy.model} is the best choice overall (highest accuracy, lowest cost, fastest)."+ return "#{run_label(best_accuracy)} is the best choice overall (highest accuracy, lowest cost, fastest)."end# Accuracy recommendationif best_accuracy.metrics["accuracy"] && best_accuracy.metrics["accuracy"] >= 90- parts << "For maximum accuracy, use #{best_accuracy.model} (#{best_accuracy.metrics['accuracy']}% accuracy)"+ parts << "For maximum accuracy, use #{run_label(best_accuracy)} (#{best_accuracy.metrics['accuracy']}% accuracy)"end# Cost recommendation if significantly cheaperif lowest_cost.total_cost && lowest_cost.total_cost > 0cost_ratio = (best_accuracy.total_cost || 0) / lowest_cost.total_costif cost_ratio > 1.5- parts << "For cost efficiency, consider #{lowest_cost.model} (#{format_cost(lowest_cost.total_cost)} vs #{format_cost(best_accuracy.total_cost)})"+ parts << "For cost efficiency, consider #{run_label(lowest_cost)} (#{format_cost(lowest_cost.total_cost)} vs #{format_cost(best_accuracy.total_cost)})"endend@@ -196,7 +214,7 @@ class Eval::Reporters::ComparisonReporterif fastest.metrics["avg_latency_ms"] && fastest.id != best_accuracy.idlatency_ratio = (best_accuracy.metrics["avg_latency_ms"] || 0) / (fastest.metrics["avg_latency_ms"] || 1)if latency_ratio > 1.5- parts << "For speed, consider #{fastest.model} (#{fastest.metrics['avg_latency_ms']}ms vs #{best_accuracy.metrics['avg_latency_ms']}ms)"+ parts << "For speed, consider #{run_label(fastest)} (#{fastest.metrics['avg_latency_ms']}ms vs #{best_accuracy.metrics['avg_latency_ms']}ms)"endenddiff --git a/app/models/eval/reporters/disagreement_report.rb b/app/models/eval/reporters/disagreement_report.rbnew file mode 100644index 0000000000..202c055037--- /dev/null+++ b/app/models/eval/reporters/disagreement_report.rb@@ -0,0 +1,148 @@+# Where two providers actually differ, sample by sample.+#+# Two accuracy percentages can be identical and still describe completely+# different behaviour: 96% and 95% might be near-identical answers, or might be+# two providers failing on disjoint halves of the dataset. Only a paired+# comparison tells them apart, and it is the paired view that says whether one+# provider is a safe replacement for the other or merely equally good on+# average.+#+# Pairs on sample, so both runs must cover the same dataset.+class Eval::Reporters::DisagreementReport+ MAX_EXAMPLES = 5++ attr_reader :baseline, :candidate++ def initialize(baseline, candidate)+ @baseline = baseline+ @candidate = candidate+ end++ def comparable?+ baseline.eval_dataset_id == candidate.eval_dataset_id && paired.any?+ end++ def paired_count+ paired.size+ end++ # Candidate right where the baseline was wrong — the cases that argue for it.+ def candidate_wins+ @candidate_wins ||= paired.select { |base, cand| cand.correct && !base.correct }+ end++ # Baseline right where the candidate was wrong — the regressions a switch buys.+ def candidate_losses+ @candidate_losses ||= paired.select { |base, cand| base.correct && !cand.correct }+ end++ def both_correct+ @both_correct ||= paired.select { |base, cand| base.correct && cand.correct }+ end++ def both_wrong+ @both_wrong ||= paired.reject { |base, cand| base.correct || cand.correct }+ end++ # Both wrong with the same answer usually indicts the dataset, not the+ # providers — worth separating before anyone "fixes" a model.+ def both_wrong_same_answer+ both_wrong.select { |base, cand| base.actual_output == cand.actual_output }+ end++ def both_wrong_different_answers+ both_wrong.reject { |base, cand| base.actual_output == cand.actual_output }+ end++ # How often they produced the identical answer, right or wrong. High agreement+ # with a small accuracy gap means the providers are near-interchangeable.+ def agreement_rate+ return nil if paired.empty?++ same = paired.count { |base, cand| base.actual_output == cand.actual_output }+ (same.to_f / paired.size * 100).round(2)+ end++ def to_h+ return { comparable: false } unless comparable?++ {+ comparable: true,+ baseline: run_label(baseline),+ candidate: run_label(candidate),+ paired_samples: paired_count,+ agreement_rate: agreement_rate,+ both_correct: both_correct.size,+ candidate_wins: candidate_wins.size,+ candidate_losses: candidate_losses.size,+ both_wrong_same_answer: both_wrong_same_answer.size,+ both_wrong_different_answers: both_wrong_different_answers.size,+ examples: {+ wins: examples(candidate_wins),+ losses: examples(candidate_losses)+ }+ }+ end++ def to_table+ unless comparable?+ return "Runs are not comparable — they must cover the same dataset and share samples."+ end++ lines = []+ lines << "#{run_label(candidate)} vs #{run_label(baseline)} over #{paired_count} paired samples"+ lines << ""+ lines << format(" %-32s %5d", "Both correct", both_correct.size)+ lines << format(" %-32s %5d", "#{run_label(candidate)} wins", candidate_wins.size)+ lines << format(" %-32s %5d", "#{run_label(candidate)} loses", candidate_losses.size)+ lines << format(" %-32s %5d", "Both wrong (same answer)", both_wrong_same_answer.size)+ lines << format(" %-32s %5d", "Both wrong (different answers)", both_wrong_different_answers.size)+ lines << ""+ lines << " Agreement rate: #{agreement_rate}%"++ if candidate_losses.any?+ lines << ""+ lines << " Regressions a switch would buy:"+ examples(candidate_losses).each do |example|+ lines << " #{example[:sample]}"+ lines << " expected #{example[:expected].inspect}, got #{example[:candidate].inspect}"+ end+ end++ lines.join("\n")+ end++ private+ def paired+ @paired ||= begin+ base_by_sample = baseline.results.includes(:sample).index_by(&:eval_sample_id)+ cand_by_sample = candidate.results.includes(:sample).index_by(&:eval_sample_id)++ (base_by_sample.keys & cand_by_sample.keys).map do |sample_id|+ [ base_by_sample[sample_id], cand_by_sample[sample_id] ]+ end+ end+ end++ def examples(pairs)+ pairs.first(MAX_EXAMPLES).map do |base, cand|+ {+ sample: sample_label(cand.sample),+ expected: cand.sample.expected_output,+ baseline: base.actual_output,+ candidate: cand.actual_output+ }+ end+ end++ # Datasets differ by eval type, so fall back through the likely description+ # fields rather than assuming a categorization shape.+ def sample_label(sample)+ input = sample.input_data || {}+ input["description"].presence || input["name"].presence || input["prompt"].presence || "sample #{sample.id}"+ end++ def run_label(run)+ "#{run.provider}:#{run.model}"+ end+enddiff --git a/app/models/eval/reporters/recommendation.rb b/app/models/eval/reporters/recommendation.rbnew file mode 100644index 0000000000..dc2426817d--- /dev/null+++ b/app/models/eval/reporters/recommendation.rb@@ -0,0 +1,238 @@+# Turns a paired comparison into replace / shadow / skip, with the reasoning+# stated rather than implied.+#+# The bar for "replace" is deliberately high. Two providers scoring 96% and 95%+# on 200 samples differ by two samples, which is noise — a report that called+# that a win would be actively misleading. Significance is tested with McNemar's+# test because the comparison is paired: both providers answered the same+# samples, so what matters is the count of samples where they disagreed, not the+# difference of two independent proportions.+#+# Default verdict is "shadow": run it alongside, gather production evidence,+# decide later.+class Eval::Reporters::Recommendation+ # Replace demands strong evidence; a tie is judged at the conventional 0.05.+ REPLACE_SIGNIFICANCE = 0.01+ TIE_SIGNIFICANCE = 0.05++ # Below this, a paired test cannot say much either way.+ MIN_SAMPLES_FOR_VERDICT = 50+ MIN_SAMPLES_TO_REPLACE = 100++ # A speed or cost edge only counts if it is worth changing a provider over.+ MATERIAL_RATIO = 2.0++ attr_reader :baseline, :candidate, :disagreement, :calibration++ def initialize(baseline:, candidate:, disagreement: nil, calibration: nil)+ @baseline = baseline+ @candidate = candidate+ @disagreement = disagreement || Eval::Reporters::DisagreementReport.new(baseline, candidate)+ @calibration = calibration || Eval::Metrics::Calibration.new(candidate)+ end++ def verdict+ to_h[:verdict]+ end++ def to_h+ return skip("runs are not comparable — different datasets or no shared samples") unless disagreement.comparable?+ return skip(broken_reason) if broken?+ return shadow("only #{disagreement.paired_count} paired samples; too few to judge") if too_few_samples?++ if significantly_worse?+ skip(accuracy_sentence("worse"))+ elsif significantly_better?+ replace_or_shadow+ else+ tie+ end+ end++ def to_table+ result = to_h+ lines = [ "Recommendation: #{result[:verdict].upcase}" ]+ lines << ""+ result[:reasons].each { |reason| lines << " - #{reason}" }+ lines << ""+ lines << " p = #{result[:p_value]} (McNemar, #{disagreement.candidate_wins.size} wins vs #{disagreement.candidate_losses.size} losses)" if result[:p_value]+ lines.join("\n")+ end++ # Two-sided McNemar with continuity correction. Only the discordant pairs+ # carry information: samples both providers got right, or both got wrong, say+ # nothing about which is better.+ def p_value+ @p_value ||= begin+ wins = disagreement.candidate_wins.size+ losses = disagreement.candidate_losses.size+ discordant = wins + losses++ if discordant.zero?+ 1.0+ else+ chi_square = (((wins - losses).abs - 1)**2) / discordant.to_f+ # Exact survival function for chi-square with one degree of freedom.+ Math.erfc(Math.sqrt(chi_square / 2.0)).round(4)+ end+ end+ end++ private+ def broken?+ candidate_errors.positive? || candidate.status != "completed"+ end++ def broken_reason+ if candidate.status != "completed"+ "candidate run did not complete (status: #{candidate.status})"+ else+ "#{candidate_errors} of #{disagreement.paired_count} candidate requests errored; the run is not a valid measurement"+ end+ end++ def candidate_errors+ (candidate.metrics || {})["samples_errored"].to_i+ end++ def too_few_samples?+ disagreement.paired_count < MIN_SAMPLES_FOR_VERDICT+ end++ def significantly_better?+ p_value < TIE_SIGNIFICANCE && disagreement.candidate_wins.size > disagreement.candidate_losses.size+ end++ def significantly_worse?+ p_value < TIE_SIGNIFICANCE && disagreement.candidate_losses.size > disagreement.candidate_wins.size+ end++ def replace_or_shadow+ reasons = [ accuracy_sentence("better") ]+ reasons.concat(performance_reasons)+ reasons << calibration_sentence if calibration_sentence++ if p_value < REPLACE_SIGNIFICANCE && disagreement.paired_count >= MIN_SAMPLES_TO_REPLACE+ build(:replace, reasons + [ "evidence is strong enough to switch the default" ])+ else+ build(:shadow, reasons + [ "advantage is real but thin; run it alongside before switching" ])+ end+ end++ def tie+ reasons = [ accuracy_sentence("indistinguishable") ]+ perf = performance_reasons+ reasons.concat(perf)+ reasons << calibration_sentence if calibration_sentence++ if perf.any?+ build(:shadow, reasons + [ "no quality difference, but the throughput or cost edge may justify it in production" ])+ else+ build(:skip, reasons + [ "no measurable advantage on any axis" ])+ end+ end++ def accuracy_sentence(direction)+ wins = disagreement.candidate_wins.size+ losses = disagreement.candidate_losses.size++ case direction+ when "indistinguishable"+ "accuracy is statistically indistinguishable (#{wins} wins, #{losses} losses over " \+ "#{disagreement.paired_count} paired samples, p = #{p_value})"+ else+ "candidate is significantly #{direction} (#{wins} wins, #{losses} losses, p = #{p_value})"+ end+ end++ def performance_reasons+ reasons = []+ reasons << latency_sentence if latency_advantage&.>= MATERIAL_RATIO+ reasons << cost_sentence if cost_sentence+ reasons+ end++ def latency_advantage+ base = metric(baseline, "avg_latency_ms")+ cand = metric(candidate, "avg_latency_ms")+ return nil unless base&.positive? && cand&.positive?++ base / cand+ end++ def latency_sentence+ format("candidate is %.1fx faster per sample (%dms vs %dms)",+ latency_advantage,+ metric(candidate, "avg_latency_ms"),+ metric(baseline, "avg_latency_ms"))+ end++ # Cost is only comparable when both sides recorded it. The OpenAI path does+ # not populate eval_results.cost, so its total lands at zero — which must not+ # be read as "free".+ def cost_sentence+ if !cost_instrumented?(baseline) && cost_instrumented?(candidate)+ "cost comparison unavailable: only the candidate reports per-call cost " \+ "(#{format_cost(observed_cost(candidate))} total); the baseline records none"+ elsif cost_instrumented?(baseline) && cost_instrumented?(candidate)+ candidate_cost = observed_cost(candidate)+ return nil unless candidate_cost.positive?++ ratio = observed_cost(baseline) / candidate_cost+ return nil unless ratio >= MATERIAL_RATIO++ format("candidate costs %.1fx less (%s vs %s)", ratio,+ format_cost(candidate_cost), format_cost(observed_cost(baseline)))+ end+ end++ # Summed from the results rather than read off Eval::Run#total_cost: that+ # column is denormalized at completion and sits at zero for a run whose+ # provider reports no cost, which is indistinguishable from genuinely free.+ def observed_cost(run)+ run.results.sum(:cost).to_f+ end++ def cost_instrumented?(run)+ run.results.where.not(cost: nil).exists?+ end++ def calibration_sentence+ return nil unless calibration.supported?++ if calibration.overconfident?+ "candidate confidence is overconfident (calibration error " \+ "#{(calibration.expected_calibration_error * 100).round(1)} points) — " \+ "not safe to gate behaviour on yet"+ else+ "candidate reports usable confidence (calibration error " \+ "#{(calibration.expected_calibration_error * 100).round(1)} points)"+ end+ end++ def metric(run, key)+ (run.metrics || {})[key]&.to_f+ end++ def format_cost(value)+ "$#{value.to_f.round(6)}"+ end++ def skip(reason)+ build(:skip, [ reason ])+ end++ def shadow(reason)+ build(:shadow, [ reason ])+ end++ def build(verdict, reasons)+ {+ verdict: verdict.to_s,+ baseline: "#{baseline.provider}:#{baseline.model}",+ candidate: "#{candidate.provider}:#{candidate.model}",+ reasons: reasons,+ p_value: disagreement.comparable? ? p_value : nil+ }+ end+enddiff --git a/app/models/eval/run.rb b/app/models/eval/run.rbindex c9cbdc9886..ce41d54cc8 100644--- a/app/models/eval/run.rb+++ b/app/models/eval/run.rb@@ -38,7 +38,11 @@ class Eval::Run < ApplicationRecordmetrics: calculated_metrics,total_prompt_tokens: results.sum(:prompt_tokens),total_completion_tokens: results.sum(:completion_tokens),- total_cost: results.sum(:cost)+ # nil, not 0, when nothing reported a cost. `sum` returns 0 over all-NULL,+ # and Eval::Reporters::ComparisonReporter picks the cheapest run with+ # `total_cost || Float::INFINITY` — so a stored 0 would beat every+ # instrumented run and crown whichever provider measures cost least.+ total_cost: (results.sum(:cost) if results.where.not(cost: nil).exists?))enddiff --git a/app/models/eval/runners/base.rb b/app/models/eval/runners/base.rbindex 42018c80d1..aec2b2582e 100644--- a/app/models/eval/runners/base.rb+++ b/app/models/eval/runners/base.rb@@ -30,8 +30,27 @@ class Eval::Runners::Baseraise NotImplementedError, "Subclasses must implement #calculate_metrics"end+ # The whole dataset unless the run asks for one side of a train/test split.+ # Bayes has to be trained on held-out samples, so every provider it is+ # compared against must be evaluated on the same test set — a provider+ # scored over the full dataset is not comparable to one scored over the+ # residual. See Eval::Runners::SampleSplit.def samples- eval_run.dataset.samples+ return eval_run.dataset.samples if split_role.blank?++ sample_split.for_role(split_role)+ end++ def split_role+ eval_run.provider_config["split_role"].presence+ end++ def sample_split+ @sample_split ||= Eval::Runners::SampleSplit.new(+ eval_run.dataset.samples,+ seed: eval_run.provider_config.fetch("split_seed", Eval::Runners::SampleSplit::DEFAULT_SEED),+ train_ratio: eval_run.provider_config.fetch("split_ratio", Eval::Runners::SampleSplit::DEFAULT_TRAIN_RATIO)+ )enddef provider@@ -45,26 +64,11 @@ class Eval::Runners::Baseprivatedef build_provider- case eval_run.provider- when "openai"- build_openai_provider- else- raise "Unsupported provider: #{eval_run.provider}"- end- end-- def build_openai_provider- access_token = eval_run.provider_config["access_token"].presence ||- ENV["OPENAI_ACCESS_TOKEN"].presence ||- Setting.openai_access_token-- raise "OpenAI access token not configured" unless access_token.present?-- uri_base = eval_run.provider_config["uri_base"].presence ||- ENV["OPENAI_URI_BASE"].presence ||- Setting.openai_uri_base-- Provider::Openai.new(access_token, uri_base: uri_base, model: model)+ Eval::ProviderFactory.build(+ provider: eval_run.provider,+ model: model,+ config: eval_run.provider_config+ )enddef record_result(sample:, actual_output:, correct:, **attributes)diff --git a/app/models/eval/runners/bayes_runner.rb b/app/models/eval/runners/bayes_runner.rbnew file mode 100644index 0000000000..d56450f05f--- /dev/null+++ b/app/models/eval/runners/bayes_runner.rb@@ -0,0 +1,206 @@+# Evaluates Family::BayesCategorizer — the free, local, first stage of the+# categorization cascade that Family#auto_categorize_transactions runs before+# any paid provider sees a transaction.+#+# Bayes is trained per-family on that family's own categorized history, so+# unlike a provider it cannot simply be handed a batch. This materializes a+# throwaway family from the training split — real Categories, Accounts, Entries+# and Transactions — trains the real classifier on it, and classifies the test+# split through the real `#classify`. Nothing about the scoring is+# reimplemented here; a copy would drift from production the first time+# BayesCategorizer changed.+#+# READ THE LIMITATION BEFORE QUOTING ANY NUMBER FROM THIS RUNNER. A golden+# dataset is roughly one transaction per distinct merchant, chosen for coverage.+# A real family's history is the opposite shape: the same handful of merchants+# repeating hundreds of times. Naive Bayes feeds on exactly that repetition, and+# has almost none of it here, so this run is close to a worst case for Bayes and+# very likely understates the coverage it achieves in production. Treat the+# Bayes leg as a lower bound, not a measurement.+class Eval::Runners::BayesRunner < Eval::Runners::CategorizationRunner+ # Marker so a run that dies mid-way leaves something obviously disposable+ # behind rather than a family that looks real.+ FAMILY_NAME_PREFIX = "[eval] bayes fixture".freeze++ def run+ super+ ensure+ destroy_fixture_family+ end++ protected++ def process_samples+ split = sample_split+ log_progress("Split: #{split.describe.to_json}")++ if split.train.empty?+ raise "Bayes evaluation needs a training split; got none. Check split_ratio."+ end++ build_fixture_family(split.train)+ classify_test_samples(split.test)+ end++ # Bayes never uses a provider — it is pure Ruby with no credentials. Guard+ # rather than inherit Base#provider, so a misconfigured run fails loudly+ # instead of trying to build an API client.+ def provider+ raise "Eval::Runners::BayesRunner does not use a provider"+ end++ private++ def categorizer+ @categorizer ||= Family::BayesCategorizer.new(fixture_family)+ end++ def classify_test_samples(test_samples)+ log_progress("Classifying #{test_samples.size} held-out samples")++ unless categorizer.enough_training_data?+ log_progress("Training guard failed — Bayes declines everything, as it would in production")+ end++ test_samples.each do |sample|+ start_time = Time.current+ transaction = build_transaction_for(sample, category: nil)+ classification = categorizer.classify(transaction)+ latency_ms = ((Time.current - start_time) * 1000).to_i++ record_classification(sample, classification, latency_ms)+ end+ end++ def record_classification(sample, classification, latency_ms)+ category_id, confidence = classification+ actual_category = category_id ? category_names_by_id[category_id] : nil+ declined = classification.nil?++ expected_category = sample.expected_category_name+ acceptable = sample.all_acceptable_categories++ # A decline is not an answer of "no category". In the cascade it means+ # "pass this to the next stage", so it is never scored as correct — even+ # for a null-expected sample, where the *cascade* may still end up right+ # once the provider stage answers. Eval::Reporters::CascadeReport is what+ # reads these apart; the headline accuracy on this run is deliberately+ # "share of the test set Bayes resolved correctly on its own".+ correct = if declined+ false+ else+ evaluate_correctness_with_alternatives(actual_category, expected_category, acceptable)+ end++ record_result(+ sample: sample,+ actual_output: { "category_name" => actual_category },+ correct: correct,+ exact_match: !declined && actual_category == expected_category,+ alternative_match: !declined && acceptable.include?(actual_category) && actual_category != expected_category,+ hierarchical_match: declined ? false : evaluate_hierarchical_match(actual_category, expected_category, sample),+ null_expected: expected_category.nil?,+ null_returned: actual_category.nil?,+ latency_ms: latency_ms,+ cost: 0,+ metadata: {+ "declined" => declined,+ "confidence" => confidence+ }.compact+ )+ end++ # --- fixture construction -------------------------------------------------++ def fixture_family+ @fixture_family || raise("Fixture family not built yet")+ end++ def build_fixture_family(train_samples)+ @fixture_family = Family.create!(name: "#{FAMILY_NAME_PREFIX} #{eval_run.id}")+ @fixture_account = @fixture_family.accounts.create!(+ name: "Eval account",+ balance: 0,+ currency: "USD",+ accountable: Depository.new+ )++ build_categories+ train_samples.each { |sample| build_transaction_for(sample, category: category_for(sample)) }++ log_progress(+ "Fixture family: #{@fixture_family.categories.count} categories, " \+ "#{train_samples.size} training transactions"+ )+ end++ # Built from the dataset's own category context so the names Bayes can+ # return match the names the expectations are written against.+ def build_categories+ context = samples_context+ created = {}++ # Parents first: a subcategory's parent_id has to resolve to a real row.+ context.sort_by { |category| category["parent_id"].present? ? 1 : 0 }.each do |category|+ created[category["id"].to_s] = fixture_family.categories.create!(+ name: category["name"],+ parent: created[category["parent_id"].to_s]+ )+ end++ @categories_by_context_id = created+ end++ def samples_context+ eval_run.dataset.samples.first&.categories_context || []+ end++ def categories_by_context_id+ @categories_by_context_id ||= {}+ end++ def category_names_by_id+ @category_names_by_id ||= categories_by_context_id.values.index_by(&:id).transform_values(&:name)+ end++ def category_for(sample)+ categories_by_context_id.values.find { |category| category.name == sample.expected_category_name }+ end++ # Mirrors Family::AutoCategorizer#transactions_input: the description is the+ # entry name plus notes, and the merchant is a separate signal. Bayes reads+ # exactly those three fields, so building them any other way would evaluate+ # a different input than production sees.+ def build_transaction_for(sample, category:)+ input = sample.to_transaction_input++ entry = @fixture_account.entries.create!(+ name: input[:description].to_s,+ date: Date.current,+ currency: "USD",+ amount: input[:amount] || 0,+ entryable: Transaction.new(+ category: category,+ merchant: merchant_for(input[:merchant])+ )+ )++ entry.entryable+ end++ def merchant_for(name)+ return nil if name.blank?++ @merchants ||= {}+ @merchants[name] ||= fixture_family.merchants.find_or_create_by!(name: name)+ end++ def destroy_fixture_family+ @fixture_family&.destroy+ @fixture_family = nil+ rescue => e+ # A leaked fixture family is untidy but not worth failing a completed run+ # over; the marker prefix makes it findable.+ Rails.logger.warn("[Eval::Runner] Failed to clean up Bayes fixture family: #{e.class}: #{e.message}")+ end+enddiff --git a/app/models/eval/runners/categorization_runner.rb b/app/models/eval/runners/categorization_runner.rbindex 3bc6994c4c..94fc6cb709 100644--- a/app/models/eval/runners/categorization_runner.rb+++ b/app/models/eval/runners/categorization_runner.rb@@ -101,7 +101,9 @@ class Eval::Runners::CategorizationRunner < Eval::Runners::Basehierarchical_match: hierarchical,null_expected: expected_category.nil?,null_returned: actual_category.nil?,- latency_ms: per_sample_latency+ latency_ms: per_sample_latency,+ metadata: confidence_metadata(categorization),+ **usage_attributes(categorization))endend@@ -124,6 +126,32 @@ class Eval::Runners::CategorizationRunner < Eval::Runners::Baseendend+ # Providers that report calibrated confidence (Jev) carry it alongside the+ # chosen category; next-token providers return the bare name. Stored in+ # metadata so calibration can be measured without a schema change.+ def confidence_metadata(categorization)+ return {} unless categorization.respond_to?(:confidence)++ {+ "confidence" => categorization.confidence,+ "probabilities" => categorization.probabilities+ }.compact+ end++ # Providers that spend one request per transaction report usage per sample,+ # so cost and tokens can be attributed directly. Batching providers bill per+ # call rather than per transaction and report nothing here.+ def usage_attributes(categorization)+ usage = categorization.usage if categorization.respond_to?(:usage)+ return {} if usage.blank?++ {+ cost: usage["cost"],+ prompt_tokens: usage["input_tokens"],+ completion_tokens: usage["output_tokens"]+ }.compact+ end+# Determine the effective JSON mode for a batch based on expected null ratio# This prevents the auto-categorizer from incorrectly retrying when many nulls are expecteddef json_mode_for_batch(batch_samples)diff --git a/app/models/eval/runners/sample_split.rb b/app/models/eval/runners/sample_split.rbnew file mode 100644index 0000000000..49eb16e971--- /dev/null+++ b/app/models/eval/runners/sample_split.rb@@ -0,0 +1,85 @@+# Deterministic train/test split over a dataset's samples. Family::BayesCategorizer+# trains on a family's own history rather than shipping pre-trained, so every+# provider must be scored on the same held-out samples to stay comparable. The+# seed is what lets a later provider leg land on the Bayes leg's test set.+#+# Two rules shape it:+#+# 1. Null-expected samples always land in test. Bayes trains on+# `where.not(category_id: nil)` and cannot learn from them.+# 2. The categorized remainder is stratified by difficulty, so training does+# not absorb the easy samples and leave a uniformly hard test set.+class Eval::Runners::SampleSplit+ DEFAULT_SEED = 42+ DEFAULT_TRAIN_RATIO = 0.5++ ROLES = %w[train test].freeze++ def initialize(samples, seed: DEFAULT_SEED, train_ratio: DEFAULT_TRAIN_RATIO)+ @samples = samples.to_a+ @seed = seed.to_i+ @train_ratio = train_ratio.to_f+ end++ def for_role(role)+ case role.to_s+ when "train" then train+ when "test" then test+ else raise ArgumentError, "Unknown split role #{role.inspect}; expected one of #{ROLES.join(', ')}"+ end+ end++ def train+ @train ||= partition.first+ end++ def test+ @test ||= partition.last+ end++ # Recorded in the run output so a split can be reproduced. The null-expected+ # share matters when comparing runs: rule 1 moves it with the dataset's+ # categorized ratio, so two runs over the same dataset can still differ.+ def describe+ {+ "seed" => seed,+ "train_ratio" => train_ratio,+ "train_size" => train.size,+ "test_size" => test.size,+ "test_null_expected" => test.count { |sample| sample.expected_category_name.nil? },+ "by_difficulty" => {+ "train" => train.group_by(&:difficulty).transform_values(&:size),+ "test" => test.group_by(&:difficulty).transform_values(&:size)+ }+ }+ end++ private+ attr_reader :samples, :seed, :train_ratio++ def partition+ @partition ||= begin+ trainable, untrainable = samples.partition { |sample| sample.expected_category_name.present? }++ train_set = []+ test_set = untrainable++ trainable.group_by(&:difficulty).each do |difficulty, group|+ ordered = group.sort_by(&:id).shuffle(random: Random.new(seed + difficulty_offset(difficulty)))+ take = (ordered.size * train_ratio).round+ train_set.concat(ordered.first(take))+ test_set.concat(ordered.drop(take))+ end++ [ train_set.sort_by(&:id), test_set.sort_by(&:id) ]+ end+ end++ # Not String#hash, which Ruby seeds per process — the legs of a cascade run+ # are separate `rake evals:run` processes, so one seed gave two shuffles.+ # Eval::Reporters::CascadeReport compares only seed and train_ratio, so it+ # cannot catch a regression here.+ def difficulty_offset(difficulty)+ Digest::SHA256.hexdigest(difficulty.to_s)[0, 8].to_i(16)+ end+enddiff --git a/app/models/family.rb b/app/models/family.rbindex 7d25ca9e45..2638b7191f 100644--- a/app/models/family.rb+++ b/app/models/family.rb@@ -35,6 +35,11 @@ class Family < ApplicationRecordMONIKERS = [ "Family", "Group" ].freezeASSISTANT_TYPES = %w[builtin external].freeze++ # Which provider categorizes this family's transactions. Family-level rather+ # than a global Setting because it decides whose transaction descriptions get+ # sent to a third party — the same reason assistant_type lives here.+ CATEGORIZATION_PROVIDERS = %w[llm jev].freezeSHARING_DEFAULTS = %w[shared private].freezehas_many :users, dependent: :destroy@@ -55,6 +60,7 @@ class Family < ApplicationRecordhas_many :tags, dependent: :destroyhas_many :categories, dependent: :destroy+ has_many :categorization_comparisons, dependent: :destroyhas_many :merchants, dependent: :destroy, class_name: "FamilyMerchant"has_many :budgets, dependent: :destroy@@ -153,6 +159,84 @@ class Family < ApplicationRecordvalidates :month_start_day, inclusion: { in: 1..28 }validates :moniker, inclusion: { in: MONIKERS }validates :assistant_type, inclusion: { in: ASSISTANT_TYPES }+ validates :categorization_provider, inclusion: { in: CATEGORIZATION_PROVIDERS }+ validates :categorization_confidence_threshold,+ numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 1 }+ validates :categorization_shadow_rate,+ numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 1 }++ # Single definition of the ENV-over-column precedence, so the resolver and the+ # settings UI can never disagree about which provider is actually in force.+ def effective_categorization_provider+ ENV["CATEGORIZATION_PROVIDER"].presence || categorization_provider+ end++ # The provider that will actually categorize this family's transactions,+ # falling back to the LLM path when Jev is unselected or unconfigured.+ # Credentials alone never select Jev; the family has to choose it, because+ # this decides whose transaction descriptions reach a third party.+ #+ # Anything naming the provider calls this, including the rule confirmation+ # screen's cost estimate, or it quotes a provider that will not run. Views+ # call it while rendering, so it writes nothing itself; a caller that runs+ # categorization passes a block to hear why Jev could not be built.+ def resolved_categorization_provider(&on_jev_error)+ jev = configured_jev_provider(&on_jev_error) if effective_categorization_provider == "jev"++ # Honors Setting.llm_provider (#2113); Provider::Anthropic gained+ # auto_categorize in #1984, so either LLM provider can serve this.+ jev || Provider::Registry.preferred_llm_provider+ end++ def categorization_model_name+ provider = resolved_categorization_provider+ return unless provider++ case provider+ when Provider::Jev then Provider::Jev.effective_model+ when Provider::Anthropic then Provider::Anthropic.effective_model+ else Provider::Openai.effective_model+ end+ end++ # Answers below this confidence are not applied. Zero applies everything and+ # is the default. Only providers reporting calibrated confidence can be gated;+ # the LLM providers return a bare category name. Clamped because the ENV+ # override bypasses both the column validation and the DB check constraint.+ def effective_categorization_confidence_threshold+ (ENV["CATEGORIZATION_CONFIDENCE_THRESHOLD"].presence || categorization_confidence_threshold).to_f.clamp(0.0, 1.0)+ end++ # Fraction of categorization runs that also ask the provider not in use, for+ # comparison only. Zero disables it. Doubles spend on the runs it samples, so+ # it is sampled rather than all-or-nothing. Clamped because `rand < rate` on+ # an unbounded override samples every run.+ def effective_categorization_shadow_rate+ (ENV["CATEGORIZATION_SHADOW_RATE"].presence || categorization_shadow_rate).to_f.clamp(0.0, 1.0)+ end++ # The provider to run alongside the one in use, for comparison. Symmetric —+ # returns whichever of the two is not selected, so either can be trialled+ # against the other without a second mechanism.+ def shadow_categorization_provider(&on_jev_error)+ if effective_categorization_provider == "jev"+ Provider::Registry.preferred_llm_provider+ else+ configured_jev_provider(&on_jev_error)+ end+ end++ # Returns Jev, or nil when it cannot be built. The registry constructs a fresh+ # Provider::Jev per lookup and its constructor rejects a cleartext endpoint,+ # which JEV_ENDPOINT can set without passing the settings form's check.+ def configured_jev_provider+ Provider::Registry.get_provider(:jev)+ rescue Provider::Error => error+ yield error if block_given?+ nil+ end+ private :configured_jev_provider+validates :default_account_sharing, inclusion: { in: SHARING_DEFAULTS }validates :personal_budgets, inclusion: { in: [ true, false ] }validates :household_budget_enabled, inclusion: { in: [ true, false ] }diff --git a/app/models/family/auto_categorizer.rb b/app/models/family/auto_categorizer.rbindex 91f0375e6e..4bd67e0cc7 100644--- a/app/models/family/auto_categorizer.rb+++ b/app/models/family/auto_categorizer.rb@@ -7,7 +7,7 @@ class Family::AutoCategorizerenddef auto_categorize- raise Error, "No LLM provider for auto-categorization" unless llm_provider+ raise Error, "No LLM provider for auto-categorization" unless categorization_providerprotected_ids = protected_transaction_idscached_ids = cached_transaction_ids@@ -33,7 +33,7 @@ class Family::AutoCategorizermessage: "AI categorization failed: no categories available",source: self.class.name,family: family,- provider: llm_provider,+ provider: categorization_provider,metadata: {requested_transaction_ids: transaction_ids}@@ -41,7 +41,7 @@ class Family::AutoCategorizerraise Error, "No categories available for auto-categorization"end- result = llm_provider.auto_categorize(+ result = categorization_provider.auto_categorize(transactions: transactions_input,user_categories: categories_input,family: family@@ -51,40 +51,62 @@ class Family::AutoCategorizerraise Error, "Failed to auto-categorize transactions: #{result.error.message}"end+ shadow_decisions = run_shadow(categories_input)+modified_count = 0categorized_transaction_ids = []+ withheld = []+scope.each do |transaction|auto_categorization = result.data.find { |c| c.transaction_id == transaction.id }category_id = categories_input.find { |c| c[:name] == auto_categorization&.category_name }&.dig(:id)- if category_id.present?- categorized_transaction_ids << transaction.id- was_modified = transaction.enrich_attribute(- :category_id,- category_id,- source: "ai"- )- transaction.lock_attr!(:category_id)- # enrich_attribute returns true if the transaction was actually modified- modified_count += 1 if was_modified+ next if category_id.blank?++ # Withheld rather than applied: the transaction is left unlocked and still+ # enrichable, so a later run (or a better model) can try again. Applying a+ # coin-flip guess and locking it would be worse than leaving it blank,+ # because the lock is what stops anything else from correcting it.+ if withhold?(auto_categorization)+ withheld << {+ transaction_id: transaction.id,+ category_name: auto_categorization.category_name,+ confidence: confidence_for(auto_categorization)+ }+ nextend++ categorized_transaction_ids << transaction.id+ was_modified = transaction.enrich_attribute(+ :category_id,+ category_id,+ source: "ai"+ )+ transaction.lock_attr!(:category_id)+ # enrich_attribute returns true if the transaction was actually modified+ modified_count += 1 if was_modifiedend+ record_shadow_comparisons(result.data, shadow_decisions) if shadow_decisions+DebugLogEntry.capture(category: "auto_categorization",level: "info",message: "AI categorization completed",source: self.class.name,family: family,- provider: llm_provider,+ provider: categorization_provider,metadata: {requested_transaction_ids: transaction_ids,categorized_transaction_ids: categorized_transaction_ids,cached_transaction_ids: cached_ids,blocked_transaction_ids: blocked_ids,- modified_count: modified_count- }+ modified_count: modified_count,+ confidence_threshold: family.effective_categorization_confidence_threshold,+ withheld_low_confidence: withheld,+ shadow_compared_count: shadow_decisions ? shadow_decisions.size : 0+ }.compact)modified_count@@ -93,11 +115,132 @@ class Family::AutoCategorizerprivateattr_reader :family, :transaction_ids- # Honors Setting.llm_provider (issue #2113) — Provider::Anthropic implements- # auto_categorize (PR #1984), so batch categorization routes to the configured- # provider, with fallback handled by Provider::Registry.preferred_llm_provider.- def llm_provider- Provider::Registry.preferred_llm_provider+ # Memoized: this is read once to guard, once per DebugLogEntry and once to+ # run, and each registry lookup builds a fresh provider object. Memoizing+ # also guarantees the provider named in the logs is the one that actually+ # ran, rather than whatever a later lookup happens to resolve.+ def categorization_provider+ return @categorization_provider if defined?(@categorization_provider)++ # Resolution lives on Family so the rule confirmation screen names the+ # same provider this run will use.+ @categorization_provider = family.resolved_categorization_provider do |error|+ log_jev_misconfiguration(error, "falling back to the LLM provider")+ end+ end++ def log_jev_misconfiguration(error, consequence)+ # Without this the only symptom is categorization silently running on the+ # provider the family did not choose. The endpoint is redacted because a+ # gateway URL can carry a key in userinfo or the query string.+ DebugLogEntry.capture(+ category: "auto_categorization",+ level: "error",+ message: "Jev is misconfigured; #{consequence}",+ source: self.class.name,+ family: family,+ provider: "jev",+ metadata: {+ endpoint: Provider::Jev.redacted_endpoint(Provider::Jev.effective_endpoint),+ error_class: error.class.name,+ error_message: error.message+ }+ )+ end++ # Only providers reporting calibrated confidence can be gated. The LLM+ # providers return a bare category name, so there is nothing to compare and+ # their answers always apply — a threshold must not silently suppress a+ # provider it cannot measure.+ def confidence_for(decision)+ decision.confidence if decision.respond_to?(:confidence)+ end++ # Gated on the decision TYPE, not on whether a confidence happens to be+ # present. Keying on nil conflated two different situations: the LLM+ # providers return a bare category name and must never be gated on a+ # confidence they cannot produce, but a classification provider's answer+ # arriving without one is malformed and should be withheld, not applied.+ # `to_f` turns that nil into 0, so it falls below any positive threshold.+ def withhold?(decision)+ threshold = family.effective_categorization_confidence_threshold+ return false unless threshold.positive?+ return false unless decision.is_a?(Provider::ClassificationConcept::CategoryDecision)++ confidence_for(decision).to_f < threshold+ end++ # Asks the provider that is NOT in use to categorize the same batch, so it+ # can be judged on real data before anyone switches. Its answers are never+ # applied.+ #+ # Sampled per run rather than per transaction because the LLM providers+ # categorize a whole batch in one request — sampling individual rows would+ # not reduce the number of calls. Any failure is swallowed: a diagnostic+ # must never break the categorization it is observing.+ def run_shadow(categories_input)+ rate = family.effective_categorization_shadow_rate+ return nil unless rate.positive?+ return nil unless rand < rate++ provider = family.shadow_categorization_provider do |error|+ log_jev_misconfiguration(error, "skipping the shadow comparison")+ end+ return nil if provider.nil? || provider.class == categorization_provider.class++ response = provider.auto_categorize(+ transactions: transactions_input,+ user_categories: categories_input,+ family: family+ )++ return nil unless response.success?++ @shadow_provider = provider+ response.data+ rescue => error+ Rails.logger.warn("Shadow categorization failed for family #{family.id}: #{error.class}: #{error.message}")+ nil+ end++ # Built from the decision lists rather than from `scope`, which is a fresh+ # query: by this point the applied answers have been written and locked, so+ # re-running it would match nothing.+ def record_shadow_comparisons(applied_decisions, shadow_decisions)+ ids = (applied_decisions.map(&:transaction_id) + shadow_decisions.map(&:transaction_id)).uniq++ rows = ids.filter_map do |id|+ applied = applied_decisions.find { |d| d.transaction_id == id }+ shadow = shadow_decisions.find { |d| d.transaction_id == id }+ next if applied.nil? && shadow.nil?++ {+ family_id: family.id,+ transaction_id: id,+ applied_provider: provider_key(categorization_provider),+ applied_category_name: applied&.category_name,+ shadow_provider: provider_key(@shadow_provider),+ shadow_category_name: shadow&.category_name,+ shadow_confidence: confidence_for(shadow),+ shadow_probabilities: (shadow.probabilities if shadow.respond_to?(:probabilities)) || {},+ # Both declining to guess counts as agreement — an abstention is an+ # answer. A provider returning no decision at all is not: the ids come+ # from the union of both lists, so one side can be missing entirely,+ # and comparing `nil == nil` would score that as agreement and inflate+ # the rate.+ agreed: applied.present? && shadow.present? && applied.category_name == shadow.category_name,+ created_at: Time.current,+ updated_at: Time.current+ }+ end++ CategorizationComparison.insert_all(rows) if rows.any?+ rescue => error+ Rails.logger.warn("Recording shadow comparison failed for family #{family.id}: #{error.class}: #{error.message}")+ end++ def provider_key(provider)+ provider.class.name.demodulize.underscoreenddef user_categories_inputdiff --git a/app/models/provider/classification_concept.rb b/app/models/provider/classification_concept.rbnew file mode 100644index 0000000000..0fcdcc28dc--- /dev/null+++ b/app/models/provider/classification_concept.rb@@ -0,0 +1,45 @@+# Contract for providers that answer typed questions about a state rather than+# generating text.+#+# Kept out of LlmConcept because these providers cannot produce prose.+# Provider::Registry.preferred_llm_provider assumes full capability of anything+# registered under :llm, and would route chat traffic here.+#+# One #decide call carries one state and many questions, and billing is almost+# entirely for the state — five questions cost 1.31x one against Jev. Batch+# questions into a single call rather than making one call each.+module Provider::ClassificationConcept+ extend ActiveSupport::Concern++ # One typed answer. `value` holds the primitive-specific payload:+ # choice => the selected criteria key (String)+ # score => position on the rubric (Float, 0-indexed against `legend`)+ # noul => probability the statement is true (Float, 0.0..1.0)+ #+ # `probabilities` is the full distribution for choice/score and nil for noul.+ Decision = Data.define(:key, :type, :value, :probabilities, :confidence)++ # The answers to one #decide call, with what the call cost.+ DecisionSet = Data.define(:decisions, :model, :usage) do+ def [](key)+ decisions[key.to_s]+ end++ def value_of(key)+ self[key]&.value+ end+ end++ # A categorization carrying the calibrated confidence the provider reported.+ # Responds to #transaction_id and #category_name, so callers written against+ # Provider::LlmConcept::AutoCategorization consume it unchanged. `usage` is+ # per-transaction because this provider spends one request per transaction.+ CategoryDecision = Data.define(:transaction_id, :category_name, :confidence, :probabilities, :usage)++ # Answers `questions` about `state` in a single request, returning a+ # DecisionSet. `state` is a String, Hash or Array; `questions` is a Hash of+ # question key => definition.+ def decide(state:, questions:, model: "", family: nil)+ raise NotImplementedError, "Subclasses must implement #decide"+ end+enddiff --git a/app/models/provider/jev.rb b/app/models/provider/jev.rbnew file mode 100644index 0000000000..0f06a17e11--- /dev/null+++ b/app/models/provider/jev.rb@@ -0,0 +1,416 @@+class Provider::Jev < Provider+ include ClassificationConcept+ extend SslConfigurable++ # Subclass so errors caught in this provider are raised as Provider::Jev::Error+ Error = Class.new(Provider::Error)++ # TypeSafe's own API, not a reseller — a gateway adds a party to the data+ # flow, so reaching one is an operator's choice rather than a default.+ # Gateways serve an identical payload, so this class covers both: for+ # OpenRouter set JEV_ENDPOINT to https://openrouter.ai/api/alpha/decisions+ # and JEV_MODEL to ~typesafe/jev-latest.+ DEFAULT_ENDPOINT = "https://api.typesafe.ai/v1/systemone"+ DEFAULT_MODEL = "jev-latest"++ # The vendor's own host. Anything else is a gateway, which the data-sharing+ # disclosure has to name rather than claiming TypeSafe receives the data.+ VENDOR_HOST = "api.typesafe.ai"++ # Hosts where plaintext carries no network exposure. See .endpoint_allowed?.+ # Matched against URI#hostname, which unwraps the brackets URI#host keeps on+ # an IPv6 literal, so "::1" is the only spelling needed.+ LOOPBACK_HOSTS = %w[localhost 127.0.0.1 ::1].freeze++ # Documented API limits.+ MAX_CHOICE_OPTIONS = 255+ SCORE_LEVELS = (2..10)++ QUESTION_TYPES = %w[choice score noul].freeze++ # A Choice always returns one of the keys it was given, so without an explicit+ # opt-out the model is forced to guess on a transaction that fits nothing.+ UNCATEGORIZED = "__uncategorized__"++ CATEGORY_INSTRUCTIONS = "Which spending category best fits this bank transaction? " \+ "Pick `#{UNCATEGORIZED}` only if no category is a reasonable fit.".freeze++ # Jev takes one state per request, so a batch of transactions is a batch of+ # requests. They are independent and latency-bound (~400-550ms each), so they+ # run concurrently.+ DEFAULT_CONCURRENCY = 8++ class << self+ def configured?+ api_key.present?+ end++ # Deliberately does not fall back to OPENROUTER_API_KEY. A self-hoster with+ # an OpenRouter key set for some unrelated purpose would otherwise find Jev+ # silently enabled and paying for classification they never opted into.+ # Enabling this provider has to be an explicit act.+ def api_key+ ENV["JEV_API_KEY"].presence || Setting.jev_api_key+ end++ def effective_model+ (ENV["JEV_MODEL"].presence || Setting.jev_model).presence || DEFAULT_MODEL+ end++ def effective_endpoint+ (ENV["JEV_ENDPOINT"].presence || Setting.jev_endpoint).presence || DEFAULT_ENDPOINT+ end++ # An http:// endpoint discloses the Bearer token and the family's+ # transaction descriptions in cleartext, so this is a credential leak rather+ # than a downgrade. Name the scheme explicitly — URI::HTTPS subclasses+ # URI::HTTP, so `is_a?(URI::HTTP)` silently accepts http://.+ #+ # Loopback is exempt because demanding a certificate for 127.0.0.1 pushes+ # operators towards disabling verification altogether.+ def endpoint_allowed?(url)+ uri = URI.parse(url.to_s)+ return false unless uri.is_a?(URI::HTTP) && uri.host.present?+ return true if uri.scheme == "https"++ uri.scheme == "http" && LOOPBACK_HOSTS.include?(uri.hostname.to_s.downcase)+ rescue URI::InvalidURIError+ false+ end+ end++ def initialize(api_key, endpoint: nil, model: nil, concurrency: nil)+ @api_key = api_key # pipelock:ignore+ @endpoint = endpoint.presence || DEFAULT_ENDPOINT++ # Enforced here as well as in the settings form so that JEV_ENDPOINT and+ # eval-time construction, which never touch the form, get the same check.+ unless self.class.endpoint_allowed?(@endpoint)+ raise Error, "Jev endpoint must use https (or http on loopback): #{self.class.redacted_endpoint(@endpoint)}"+ end++ @default_model = model.presence || DEFAULT_MODEL+ @concurrency = (concurrency || ENV["JEV_CONCURRENCY"]).to_i+ @concurrency = DEFAULT_CONCURRENCY unless @concurrency.positive?+ end++ def provider_name+ proxied? ? "Jev via #{endpoint_host}" : "Jev"+ end++ # True when requests reach TypeSafe through a gateway rather than directly.+ def proxied?+ endpoint_host != VENDOR_HOST+ end++ def endpoint_host+ self.class.host_for(@endpoint)+ end++ class << self+ def host_for(endpoint)+ URI.parse(endpoint.to_s).host.presence || endpoint.to_s+ rescue URI::InvalidURIError+ endpoint.to_s+ end++ # The host an operator's current configuration will actually send to, for+ # the settings disclosure.+ def effective_host+ host_for(effective_endpoint)+ end++ # The endpoint with its credential-bearing parts removed, for logs, error+ # messages and diagnostics. A gateway URL can carry a key in userinfo or in+ # the query string, and DebugLogEntry rows are exported when an operator+ # asks for support.+ #+ # `userinfo=` is not enough: Ruby returns early when passed nil, leaving the+ # credential in place. Clear the password before the user, or the assignment+ # raises on a URL that has both.+ def redacted_endpoint(url)+ uri = URI.parse(url.to_s)+ uri.password = nil if uri.respond_to?(:password) && uri.password+ uri.user = nil if uri.respond_to?(:user) && uri.user+ uri.query = nil+ uri.fragment = nil+ uri.to_s+ rescue URI::Error, NoMethodError+ "[unparseable endpoint]"+ end++ def effective_proxied?+ effective_host != VENDOR_HOST+ end+ end++ def decide(state:, questions:, model: "", family: nil)+ with_provider_response do+ decide!(state: state, questions: questions, model: model)+ end+ end++ # Mirrors Provider::LlmConcept#auto_categorize's signature so the existing+ # categorization eval runner and Family::AutoCategorizer consume this provider+ # without changes. `json_mode` is accepted and ignored: Jev's output is typed+ # at the protocol level, so there is no JSON parsing to coerce.+ def auto_categorize(transactions: [], user_categories: [], model: "", family: nil, json_mode: nil)+ with_provider_response do+ if user_categories.blank?+ Rails.logger.error("Cannot auto-categorize transactions for family #{family&.id || 'unknown'}: no categories available")+ raise Error, "No categories available for auto-categorization"+ end++ criteria = category_criteria(user_categories)+ effective_model = model.presence || @default_model++ in_parallel(transactions) do |transaction|+ categorize_one(transaction, criteria: criteria, model: effective_model)+ end.compact+ end+ end++ private+ attr_reader :api_key++ def categorize_one(transaction, criteria:, model:)+ question = {+ type: "choice",+ instructions: CATEGORY_INSTRUCTIONS,+ criteria: criteria+ }++ result = decide!(+ state: transaction_state(transaction),+ questions: { category: question },+ model: model+ )++ decision = result[:category]+ return nil unless decision++ ClassificationConcept::CategoryDecision.new(+ transaction_id: transaction[:id],+ category_name: choice_or_nil(decision.value),+ confidence: decision.confidence,+ probabilities: decision.probabilities,+ usage: result.usage+ )+ end++ # A Choice always returns one of its keys, so the opt-out sentinel is how+ # "none of these" comes back. Translate it to nil at the boundary.+ def choice_or_nil(value)+ return nil if value.nil? || value == UNCATEGORIZED++ value+ end++ # Categories carry no description column, so the criteria hint is derived+ # from the hierarchy. A nil value is valid and means "the name speaks for+ # itself".+ def category_criteria(user_categories)+ if user_categories.size >= MAX_CHOICE_OPTIONS+ raise Error, "Too many categories for one Choice question. Max is #{MAX_CHOICE_OPTIONS - 1} plus the opt-out."+ end++ by_id = user_categories.index_by { |category| category[:id].to_s }++ criteria = user_categories.each_with_object({}) do |category, acc|+ parent = by_id[category[:parent_id].to_s]+ acc[category[:name].to_s] = parent ? "Subcategory of #{parent[:name]}" : nil+ end++ criteria[UNCATEGORIZED] = "No listed category is a reasonable fit"+ criteria+ end++ def transaction_state(transaction)+ {+ description: transaction[:description],+ amount: transaction[:amount],+ classification: transaction[:classification],+ merchant: transaction[:merchant],+ hint: transaction[:hint]+ }.compact+ end++ def decide!(state:, questions:, model: "")+ raise Error, "No questions provided" if questions.blank?++ questions = questions.transform_keys(&:to_s)+ questions.each { |key, question| validate_question!(key, question) }++ response = client.post(@endpoint) do |req|+ req.body = {+ model: model.presence || @default_model,+ state: state,+ questions: questions+ }+ end++ parse_decision_set(JSON.parse(response.body))+ end++ def validate_question!(key, question)+ type = (question[:type] || question["type"]).to_s+ unless QUESTION_TYPES.include?(type)+ raise Error, "Question '#{key}' has unknown type #{type.inspect}; expected one of #{QUESTION_TYPES.join(', ')}"+ end++ criteria = question[:criteria] || question["criteria"]++ case type+ when "choice"+ if criteria.to_h.size > MAX_CHOICE_OPTIONS+ raise Error, "Question '#{key}' has #{criteria.size} options; max is #{MAX_CHOICE_OPTIONS}"+ end+ when "score"+ unless SCORE_LEVELS.cover?(criteria.to_a.size)+ raise Error, "Question '#{key}' has #{criteria.to_a.size} rubric levels; must be #{SCORE_LEVELS.min}-#{SCORE_LEVELS.max}"+ end+ end+ end++ def parse_decision_set(body)+ answers = body["answers"]+ raise Error, "Malformed Jev response: missing 'answers'" unless answers.is_a?(Hash)++ decisions = answers.each_with_object({}) do |(key, answer), acc|+ acc[key] = build_decision(key, answer)+ end++ ClassificationConcept::DecisionSet.new(+ decisions: decisions,+ model: body["model"],+ usage: build_usage(body["usage"])+ )+ end++ def build_decision(key, answer)+ type = answer["type"].to_s++ value = case type+ when "choice" then answer["choice"]+ when "score" then answer["score"]+ when "noul" then answer["noul"]+ else raise Error, "Unknown answer type #{type.inspect} for question '#{key}'"+ end++ ClassificationConcept::Decision.new(+ key: key,+ type: type,+ value: value,+ probabilities: answer["probabilities"],+ confidence: confidence_for(type, value, answer["confidence"])+ )+ end++ # Derived per type rather than with a general fallback. noul_confidence is+ # (value - 0.5).abs * 2, which is only meaningful for a noul: applied to a+ # score it produces values outside 0..1 (a score of 1.92 yields 2.84), and+ # applied to a choice it returns nil because the value is a String.+ #+ # A choice or score arriving without a confidence is a malformed response.+ # It reports 0 rather than nil so a downstream threshold reads it as+ # maximally unconfident and withholds, instead of mistaking it for a+ # provider that does not do confidence at all and waving it through.+ # Clamped because the gate that consumes this compares against a threshold+ # constrained to 0..1: an out-of-range confidence (a reported 1.5, or a+ # noul_confidence derived from a probability outside 0..1) would clear every+ # threshold and be applied and locked, which is the precise outcome the+ # withholding logic exists to prevent. A malformed answer must fail closed.+ def confidence_for(type, value, reported)+ return reported.to_f.clamp(0.0, 1.0) if reported+ return noul_confidence(value) if type == "noul"++ 0.0+ end++ # Noul answers carry no confidence field — the probability is the answer.+ # Distance from 0.5 is the equivalent signal: 0.5 is maximal uncertainty,+ # 0.0 and 1.0 are maximal certainty.+ #+ # Bounded here rather than in the caller because this is the expression that+ # can exceed 1, and because a nil must survive: it means "not a number at+ # all", which the withholding gate reads as zero and refuses, whereas+ # clamping a nil would raise on the one input worth sanitizing.+ def noul_confidence(value)+ return nil unless value.is_a?(Numeric)++ ((value - 0.5).abs * 2).clamp(0.0, 1.0)+ end++ def build_usage(usage)+ return {} unless usage.is_a?(Hash)++ {+ "input_tokens" => usage["input_tokens"].to_i,+ "output_tokens" => usage["output_tokens"].to_i,+ "total_tokens" => usage["input_tokens"].to_i + usage["output_tokens"].to_i,+ # OpenRouter reports settled cost per call; TypeSafe's native API does+ # not, so this is absent when talking to TypeSafe directly.+ "cost" => usage["cost"]+ }.compact+ end++ # Fixed pool over a work queue. Thread#join re-raises worker exceptions, so+ # a failed request still surfaces through with_provider_response.+ #+ # The executor wrap is defensive: nothing in here touches ActiveRecord+ # today, but these threads run inside a Sidekiq worker, and an unwrapped+ # thread that later grows a query would check out a connection and never+ # return it.+ # Matches the fan-out idiom in Security::Provided — total wall time is+ # max(request latencies) rather than sum. Unlike that one it runs on a+ # bounded pool: this fans out per transaction, so an unbounded+ # Promises.future would open a socket for every row in the batch.+ #+ # `value!` re-raises a worker's exception, so a failed request still+ # surfaces through with_provider_response rather than landing as a nil.+ def in_parallel(items)+ items = items.to_a+ return [] if items.empty?++ pool = Concurrent::FixedThreadPool.new([ @concurrency, items.size ].min)++ begin+ items+ .map { |item| Concurrent::Promises.future_on(pool) { Rails.application.executor.wrap { yield(item) } } }+ .map(&:value!)+ ensure+ pool.shutdown+ pool.wait_for_termination+ end+ end++ def client+ @client ||= Faraday.new(ssl: self.class.faraday_ssl_options) do |faraday|+ # Two defaults have to be overridden for this backoff to run at all.+ # faraday-retry only retries IDEMPOTENT_METHODS, which excludes POST;+ # opting POST in is safe here because a decision request has no side+ # effects. And `retry_statuses` is never consulted, because the+ # `raise_error` handler below converts the status into an exception+ # first — so the throttle and overload signals the API documents (429+ # and 529) have to be named as exception classes instead.+ faraday.request(:retry, {+ max: 3,+ interval: 0.5,+ interval_randomness: 0.5,+ backoff_factor: 2,+ methods: [ :post ],+ exceptions: Faraday::Retry::Middleware::DEFAULT_EXCEPTIONS + [+ Faraday::ConnectionFailed,+ Faraday::TooManyRequestsError,+ Faraday::ServerError+ ]+ })+ faraday.request :json+ faraday.response :raise_error+ faraday.options.timeout = ENV.fetch("JEV_REQUEST_TIMEOUT", 30).to_i+ faraday.options.open_timeout = 5+ faraday.headers["Authorization"] = "Bearer #{api_key}"+ faraday.headers["Accept"] = "application/json"+ end+ end+enddiff --git a/app/models/provider/registry.rb b/app/models/provider/registry.rbindex 5c6eecdc72..3a74fb08c6 100644--- a/app/models/provider/registry.rb+++ b/app/models/provider/registry.rb@@ -3,7 +3,7 @@ class Provider::RegistryError = Class.new(StandardError)- CONCEPTS = %i[exchange_rates securities llm property_valuations]+ CONCEPTS = %i[exchange_rates securities llm property_valuations classification]validates :concept, inclusion: { in: CONCEPTS }@@ -105,6 +105,18 @@ class Provider::RegistryProvider::Anthropic.new(access_token, base_url: base_url, model: model)end+ def jev+ api_key = Provider::Jev.api_key # pipelock:ignore++ return nil unless api_key.present?++ Provider::Jev.new(+ api_key,+ endpoint: Provider::Jev.effective_endpoint,+ model: Provider::Jev.effective_model+ )+ end+def yahoo_financeProvider::YahooFinance.newend@@ -215,6 +227,12 @@ class Provider::Registry%i[twelve_data yahoo_finance tiingo eodhd alpha_vantage mfapi binance_public moex_public tinkoff_invest mansa]when :llm%i[openai anthropic]+ when :classification+ # Only providers implementing Provider::ClassificationConcept#decide+ # belong here. OpenAI and Anthropic can auto-categorize but cannot+ # answer typed questions, so they stay under :llm — the eval runner+ # builds them by name when benchmarking against Jev.+ %i[jev]when :property_valuations%i[rentcast realie]elsediff --git a/app/models/rule/action_executor/auto_categorize.rb b/app/models/rule/action_executor/auto_categorize.rbindex ca249b974e..7556bd5375 100644--- a/app/models/rule/action_executor/auto_categorize.rb+++ b/app/models/rule/action_executor/auto_categorize.rb@@ -3,12 +3,10 @@ class Rule::ActionExecutor::AutoCategorize < Rule::ActionExecutorbase_label = "Auto-categorize transactions with AI"if rule.family.self_hoster?- # Use the same provider determination logic as Family::AutoCategorizer- llm_provider = Provider::Registry.get_provider(:openai)+ selected_model = rule.family.categorization_model_name- if llm_provider+ if selected_model.present?# Estimate cost for typical batch of 20 transactions- selected_model = Provider::Openai.effective_modelestimated_cost = LlmUsage.estimate_auto_categorize_cost(transaction_count: 20,category_count: rule.family.categories.count,@@ -22,7 +20,7 @@ class Rule::ActionExecutor::AutoCategorize < Rule::ActionExecutorend"#{base_label}#{suffix}"else- "#{base_label} (no LLM provider configured)"+ "#{base_label} (no categorization provider configured)"endelsebase_labeldiff --git a/app/models/rule/registry/transaction_resource.rb b/app/models/rule/registry/transaction_resource.rbindex f4dc219625..598e5c6b9e 100644--- a/app/models/rule/registry/transaction_resource.rb+++ b/app/models/rule/registry/transaction_resource.rb@@ -35,8 +35,11 @@ class Rule::Registry::TransactionResource < Rule::RegistryRule::ActionExecutor::SendEmailNotification.new(rule)]- if ai_enabled?+ if auto_categorization_enabled? || existing_action?("auto_categorize")enabled_executors << Rule::ActionExecutor::AutoCategorize.new(rule)+ end++ if auto_merchant_detection_enabled? || existing_action?("auto_detect_merchants")enabled_executors << Rule::ActionExecutor::AutoDetectMerchants.new(rule)end@@ -44,7 +47,15 @@ class Rule::Registry::TransactionResource < Rule::Registryendprivate- def ai_enabled?- Provider::Registry.get_provider(:openai).present?+ def auto_categorization_enabled?+ family.resolved_categorization_provider.present?+ end++ def auto_merchant_detection_enabled?+ Provider::Registry.preferred_llm_provider.present?+ end++ def existing_action?(action_type)+ rule.actions.any? { |action| action.action_type == action_type }endenddiff --git a/app/models/setting.rb b/app/models/setting.rbindex edf2dc71a1..65dab3c163 100644--- a/app/models/setting.rb+++ b/app/models/setting.rb@@ -16,6 +16,14 @@ class Setting < RailsSettings::Basefield :anthropic_base_url, type: :string, default: ENV["ANTHROPIC_BASE_URL"]field :llm_provider, type: :string, default: ENV.fetch("LLM_PROVIDER", "openai")+ # Jev (TypeSafe) — a classification provider, not an LLM. Reachable either+ # through OpenRouter's Decisions API (the default) or TypeSafe's own endpoint.+ # Deliberately no OPENROUTER_API_KEY fallback: an operator holding that key+ # for an unrelated purpose should not silently enable Jev.+ field :jev_api_key, type: :string, default: ENV["JEV_API_KEY"]+ field :jev_endpoint, type: :string, default: ENV["JEV_ENDPOINT"]+ field :jev_model, type: :string, default: ENV["JEV_MODEL"]+# LLM token budget (applies to every outbound LLM call: chat, auto-categorize,# merchant detection, enhance-merchants, PDF processing). Defaults track# Ollama's historical 2048-token baseline so local small-context models work@@ -105,6 +113,7 @@ class Setting < RailsSettings::Baserealie_api_keyopenai_access_tokenanthropic_access_token+ jev_api_keyexternal_assistant_token].freezediff --git a/app/views/settings/hostings/_categorization_provider_selector.html.erb b/app/views/settings/hostings/_categorization_provider_selector.html.erbnew file mode 100644index 0000000000..11ac6afeb6--- /dev/null+++ b/app/views/settings/hostings/_categorization_provider_selector.html.erb@@ -0,0 +1,124 @@+<%+ locked = ENV["CATEGORIZATION_PROVIDER"].present?+ effective = Current.family.effective_categorization_provider+ jev_active = effective == "jev"+ threshold_locked = ENV["CATEGORIZATION_CONFIDENCE_THRESHOLD"].present?+ shadow_locked = ENV["CATEGORIZATION_SHADOW_RATE"].present?+%>++<div class="space-y-3">+ <div>+ <div class="flex items-center gap-2 mb-1">+ <h2 class="font-medium"><%= t(".title") %></h2>+ <%= render DS::Pill.new(label: t(".preview_pill")) %>+ </div>+ <% if locked %>+ <p class="text-sm text-secondary"><%= t(".env_notice", type: ENV["CATEGORIZATION_PROVIDER"]) %></p>+ <% else %>+ <p class="text-secondary text-sm"><%= t(".description") %></p>+ <% end %>+ </div>++ <%# Scoped to the family, not a global Setting: this decides whose transaction+ descriptions leave the instance. Mirrors the assistant_type selector. %>+ <%= styled_form_with model: Current.family,+ url: settings_hosting_path,+ method: :patch,+ class: "space-y-4",+ data: {+ controller: "auto-submit-form",+ "auto-submit-form-trigger-event-value": "change"+ } do |form| %>+ <%= form.select :categorization_provider,+ options_for_select(+ [+ [ t(".provider_llm"), "llm" ],+ [ t(".provider_jev"), "jev" ]+ ],+ effective+ ),+ { label: t(".provider_label") },+ { disabled: locked,+ data: { "auto-submit-form-target": "auto" } } %>+ <% end %>++ <p class="text-xs text-secondary"><%= t(".provider_help") %></p>++ <%# Credentials live inside this panel rather than beside it: selecting the+ provider and giving it a key are one task, and splitting them meant the+ panel had to explain that a key alone changes nothing. Same shape as the+ external-assistant fields in _assistant_settings. %>+ <% if jev_active %>+ <div class="flex items-center gap-2 text-sm">+ <% if Provider::Jev.configured? %>+ <span class="inline-block w-2 h-2 rounded-full bg-success"></span>+ <span class="text-secondary"><%= t(".jev_configured") %></span>+ <% else %>+ <span class="inline-block w-2 h-2 rounded-full bg-destructive"></span>+ <span class="text-secondary"><%= t(".jev_not_configured") %></span>+ <% end %>+ </div>++ <%= render "settings/hostings/jev_settings" %>++ <%# Only meaningful for a provider that reports confidence — the LLM+ providers return a bare category name, so there is nothing to threshold+ against. %>+ <%= styled_form_with model: Current.family,+ url: settings_hosting_path,+ method: :patch,+ class: "space-y-1",+ data: {+ controller: "auto-submit-form",+ "auto-submit-form-trigger-event-value": "change"+ } do |form| %>+ <%= form.number_field :categorization_confidence_threshold,+ label: t(".confidence_threshold_label"),+ in: 0..1,+ step: 0.05,+ value: Current.family.effective_categorization_confidence_threshold,+ disabled: threshold_locked,+ data: { "auto-submit-form-target": "auto" } %>+ <% end %>+ <p class="text-xs text-secondary"><%= t(".confidence_threshold_help") %></p>+ <% if threshold_locked %>+ <p class="text-xs text-secondary"><%= t(".confidence_threshold_env_notice") %></p>+ <% end %>++ <%# Names the host actually configured. Saying "sent to TypeSafe" would be+ wrong whenever a gateway is in front of it — the descriptions transit+ that party too. %>+ <%= render DS::Note.new(title: t(".data_retention_heading")) do %>+ <% if Provider::Jev.effective_proxied? %>+ <p><%= t(".data_retention_proxied", host: Provider::Jev.effective_host) %></p>+ <% else %>+ <p><%= t(".data_retention_direct") %></p>+ <% end %>+ <% end %>+ <% end %>++ <%# Shadow mode runs whichever provider is NOT selected alongside the one that+ is, so it is worth offering either way round. %>+ <%= styled_form_with model: Current.family,+ url: settings_hosting_path,+ method: :patch,+ class: "space-y-1",+ data: {+ controller: "auto-submit-form",+ "auto-submit-form-trigger-event-value": "change"+ } do |form| %>+ <%= form.number_field :categorization_shadow_rate,+ label: t(".shadow_rate_label"),+ in: 0..1,+ step: 0.05,+ value: Current.family.effective_categorization_shadow_rate,+ disabled: shadow_locked,+ data: { "auto-submit-form-target": "auto" } %>+ <% end %>+ <p class="text-xs text-warning"><%= t(".shadow_rate_help") %></p>+ <% if shadow_locked %>+ <p class="text-xs text-secondary"><%= t(".shadow_rate_env_notice") %></p>+ <% end %>++ <%= render "settings/hostings/categorization_shadow_results" %>+</div>diff --git a/app/views/settings/hostings/_categorization_shadow_results.html.erb b/app/views/settings/hostings/_categorization_shadow_results.html.erbnew file mode 100644index 0000000000..f93d976f3b--- /dev/null+++ b/app/views/settings/hostings/_categorization_shadow_results.html.erb@@ -0,0 +1,39 @@+<%# Shadow mode exists so an operator can look at real disagreements before+ switching provider. Leaving that in the database means reaching for a Rails+ console, which defeats the point — so the summary lives here. %>+<%+ comparisons = Current.family.categorization_comparisons+ sampled = comparisons.count+ agreement = comparisons.agreement_rate+ recent_disagreements = comparisons.disagreements.order(created_at: :desc).limit(5)+%>++<%= render DS::Note.new(title: t(".shadow_results_heading")) do %>+ <% if sampled.zero? %>+ <%# Not "0% agreement": no data and total disagreement look identical in a+ bare percentage, and they mean opposite things. %>+ <p><%= t(".shadow_results_empty") %></p>+ <% else %>+ <p><%= t(".shadow_results_summary", agreement: agreement, count: sampled) %></p>++ <% if recent_disagreements.any? %>+ <p class="font-medium text-primary pt-1"><%= t(".shadow_disagreements_heading") %></p>+ <ul class="space-y-1">+ <% recent_disagreements.each do |comparison| %>+ <li>+ <%= t(".shadow_disagreement_row",+ applied_provider: comparison.applied_provider,+ applied_category: comparison.applied_category_name.presence || t(".shadow_no_category"),+ shadow_provider: comparison.shadow_provider,+ shadow_category: comparison.shadow_category_name.presence || t(".shadow_no_category")) %>+ <% if comparison.shadow_confidence.present? %>+ <%= t(".shadow_disagreement_confidence", confidence: number_with_precision(comparison.shadow_confidence, precision: 2)) %>+ <% end %>+ </li>+ <% end %>+ </ul>+ <% else %>+ <p><%= t(".shadow_no_disagreements") %></p>+ <% end %>+ <% end %>+<% end %>diff --git a/app/views/settings/hostings/_jev_settings.html.erb b/app/views/settings/hostings/_jev_settings.html.erbnew file mode 100644index 0000000000..0db1742acb--- /dev/null+++ b/app/views/settings/hostings/_jev_settings.html.erb@@ -0,0 +1,51 @@+<%# Credential fields only. The heading, Preview pill and data-sharing notice+ belong to _categorization_provider_selector, which renders this once Jev is+ the selected provider. %>+<div class="space-y-4">+ <% if ENV["JEV_API_KEY"].present? %>+ <p class="text-sm text-secondary"><%= t(".env_configured_message") %></p>+ <% end %>++ <%= styled_form_with model: Setting.new,+ url: settings_hosting_path,+ method: :patch,+ class: "space-y-4",+ data: {+ controller: "auto-submit-form",+ "auto-submit-form-trigger-event-value": "blur"+ } do |form| %>+ <%= form.password_field :jev_api_key,+ label: t(".api_key_label"),+ placeholder: t(".api_key_placeholder"),+ value: (Setting.jev_api_key.present? ? "********" : nil),+ autocomplete: "off",+ autocapitalize: "none",+ spellcheck: "false",+ inputmode: "text",+ disabled: ENV["JEV_API_KEY"].present?,+ data: { "auto-submit-form-target": "auto" } %>++ <%= form.text_field :jev_endpoint,+ label: t(".endpoint_label"),+ placeholder: t(".endpoint_placeholder"),+ value: @jev_endpoint_input || Provider::Jev.effective_endpoint,+ autocomplete: "off",+ autocapitalize: "none",+ spellcheck: "false",+ inputmode: "url",+ disabled: ENV["JEV_ENDPOINT"].present?,+ data: { "auto-submit-form-target": "auto" } %>++ <%= form.text_field :jev_model,+ label: t(".model_label"),+ placeholder: t(".model_placeholder"),+ value: @jev_model_input || Provider::Jev.effective_model,+ autocomplete: "off",+ autocapitalize: "none",+ spellcheck: "false",+ inputmode: "text",+ disabled: ENV["JEV_MODEL"].present?,+ data: { "auto-submit-form-target": "auto" } %>+ <p class="text-xs text-secondary mt-1"><%= t(".model_help") %></p>+ <% end %>+</div>diff --git a/app/views/settings/hostings/_llm_provider_selector.html.erb b/app/views/settings/hostings/_llm_provider_selector.html.erbindex 22b0c67b8f..84c66b7807 100644--- a/app/views/settings/hostings/_llm_provider_selector.html.erb+++ b/app/views/settings/hostings/_llm_provider_selector.html.erb@@ -54,8 +54,7 @@<p class="text-xs text-warning"><%= t(".not_configured_hint", provider: t(".provider_#{active}")) %></p><% end %>- <div class="rounded-md border border-secondary p-3 bg-container-inset text-xs text-secondary space-y-1">- <p class="font-medium text-primary"><%= t(".data_retention_heading") %></p>+ <%= render DS::Note.new(title: t(".data_retention_heading")) do %><p><%= t(".data_retention") %></p>- </div>+ <% end %></div>diff --git a/app/views/settings/hostings/show.html.erb b/app/views/settings/hostings/show.html.erbindex e230197b69..d410c9d791 100644--- a/app/views/settings/hostings/show.html.erb+++ b/app/views/settings/hostings/show.html.erb@@ -15,6 +15,19 @@hidden: Setting.llm_provider != "anthropic" do %><%= render "settings/hostings/anthropic_settings" %><% end %>+ <%# Jev is a classification provider, not an LLM: it answers typed questions+ and cannot generate text. This sits outside the panels above so the+ llm_provider selector never shows or hides it — that selector governs+ chat and PDF, which Jev can never serve. The panel renders its own+ credential fields once Jev is selected.++ Preview gates the entry point only — see+ docs/llm-guides/gating-a-preview-feature.md. Resolution reads the family+ column, so a family that opts in and then picks the LLM provider keeps+ the LLM provider. %>+ <% if preview_features_enabled? %>+ <%= render "settings/hostings/categorization_provider_selector" %>+ <% end %><%= render "settings/hostings/brand_fetch_settings" %></div><% end %>diff --git a/config/locales/views/settings/hostings/en.yml b/config/locales/views/settings/hostings/en.ymlindex fb81421752..146dd6d5e4 100644--- a/config/locales/views/settings/hostings/en.yml+++ b/config/locales/views/settings/hostings/en.yml@@ -100,7 +100,7 @@ en:high_res_description: When enabled, logos will be retrieved at 120x120 resolution instead of 40x40. This provides sharper images on high-DPI displays.llm_provider_selector:title: AI Provider- description: Choose which LLM powers AI chat. Batch operations (transaction categorization, merchant detection, and PDF processing) currently always use OpenAI.+ description: Choose which LLM powers AI chat, merchant detection and PDF processing. Transaction categorization is configured separately below.env_configured_message: Successfully configured through the LLM_PROVIDER environment variable.provider_label: Active LLM providerprovider_openai: OpenAI@@ -120,6 +120,44 @@ en:model_label: Default Model (Optional)model_placeholder: "claude-sonnet-4-6 (default)"model_help: Used for chat and PDF processing. Batch operations (categorize, merchant detection) default to Haiku for cost.+ categorization_provider_selector:+ title: Transaction Categorization+ preview_pill: Preview+ description: Choose which provider categorizes transactions. This is separate from the AI provider above, which handles chat and PDF processing.+ env_notice: "Set to %{type} through environment variables."+ provider_label: Categorization provider+ provider_llm: AI provider (OpenAI or Anthropic)+ provider_jev: Jev (TypeSafe)+ provider_help: The AI provider reads a batch of transactions and writes back category names. Jev picks from your category list and returns a calibrated confidence for each transaction.+ jev_configured: Jev API key configured.+ jev_not_configured: Jev is selected but has no API key configured. Categorization keeps using the AI provider until you add one below.+ data_retention_heading: Data sharing+ data_retention_direct: Transaction descriptions, amounts and your category names are sent to TypeSafe to be categorized. Review their retention policy before enabling this on real data.+ data_retention_proxied: Transaction descriptions, amounts and your category names are sent to %{host}, which forwards them to TypeSafe. Review both providers' retention policies before enabling this on real data.+ confidence_threshold_label: Minimum confidence (0–1)+ confidence_threshold_help: Below this confidence the category is not applied and the transaction is left uncategorized, so a later run can try again. Nothing is discarded. Set to 0 to apply every answer.+ confidence_threshold_env_notice: Locked by the CATEGORIZATION_CONFIDENCE_THRESHOLD environment variable.+ shadow_rate_label: Shadow comparison rate (0–1)+ shadow_rate_help: Runs the provider you did NOT select alongside the one you did, recording where they disagree without changing any category. This doubles the API spend on every categorization run it samples. Set to 0 to turn it off.+ shadow_rate_env_notice: Locked by the CATEGORIZATION_SHADOW_RATE environment variable.+ categorization_shadow_results:+ shadow_results_heading: Shadow comparison+ shadow_results_empty: No comparisons recorded yet. Set a shadow comparison rate above 0 and run categorization to collect some.+ shadow_results_summary: "%{agreement}%% agreement across %{count} sampled transactions."+ shadow_disagreements_heading: Most recent disagreements+ shadow_disagreement_row: "%{applied_provider} chose %{applied_category}; %{shadow_provider} chose %{shadow_category}."+ shadow_disagreement_confidence: "(confidence %{confidence})"+ shadow_no_disagreements: The two providers agreed on every sampled transaction.+ shadow_no_category: no category+ jev_settings:+ env_configured_message: Successfully configured through environment variables.+ api_key_label: API Key+ api_key_placeholder: Enter your TypeSafe API key+ endpoint_label: Endpoint (Optional)+ endpoint_placeholder: "https://api.typesafe.ai/v1/systemone (default)"+ model_label: Model (Optional)+ model_placeholder: "jev-latest (default)"+ model_help: Defaults to TypeSafe directly. To reach Jev through OpenRouter instead, set the endpoint to https://openrouter.ai/api/alpha/decisions and the model to ~typesafe/jev-latest.openai_settings:description: Enter the access token and optionally configure a custom OpenAI-compatible providerenv_configured_message: Successfully configured through environment variables.@@ -254,6 +292,8 @@ en:invalid_llm_budget: "%{field} must be a whole number ≥ %{minimum}."invalid_anthropic_base_url: Anthropic Base URL must be an http(s) URL.anthropic_model_required_for_base_url: Anthropic Model is required when a custom Base URL is set.+ invalid_jev_endpoint: Jev Endpoint must be an https URL. Plain http is accepted only for localhost.+ invalid_categorization_rate: "%{field} must be a number between 0 and 1."scheduler_sync_failed: Settings saved, but failed to update the sync schedule. Please try again or check the server logs.disconnect_external_assistant:external_assistant_disconnected: External assistant disconnecteddiff --git a/db/migrate/20260920150000_add_categorization_provider_to_families.rb b/db/migrate/20260920150000_add_categorization_provider_to_families.rbnew file mode 100644index 0000000000..a5eb900485--- /dev/null+++ b/db/migrate/20260920150000_add_categorization_provider_to_families.rb@@ -0,0 +1,12 @@+class AddCategorizationProviderToFamilies < ActiveRecord::Migration[8.1]+ def change+ add_column :families, :categorization_provider, :string, default: "llm", null: false++ # Matches chk_families_default_account_sharing on this table: the model+ # validation does not bind update_column or a data migration, and a garbage+ # value here silently changes which provider sees a family's transactions.+ add_check_constraint :families,+ "categorization_provider::text = ANY (ARRAY['llm'::character varying::text, 'jev'::character varying::text])",+ name: "chk_families_categorization_provider"+ end+enddiff --git a/db/migrate/20260920160000_add_categorization_confidence_controls_to_families.rb b/db/migrate/20260920160000_add_categorization_confidence_controls_to_families.rbnew file mode 100644index 0000000000..50426cd997--- /dev/null+++ b/db/migrate/20260920160000_add_categorization_confidence_controls_to_families.rb@@ -0,0 +1,25 @@+class AddCategorizationConfidenceControlsToFamilies < ActiveRecord::Migration[8.1]+ def change+ # 0.7 is where the confidence signal stops paying. Measured over the+ # 200-sample categorization golden set: withholding below 0.7 leaves 91.5% of+ # transactions categorized and takes the error rate on what IS applied from+ # 4.5% to 1.6% — two thirds of the mistakes, for 8.5% of the coverage.+ # Raising it further buys nothing (0.8 and 0.9 both score marginally worse on+ # small denominators) while withholding far more. Errors concentrate sharply:+ # 35.3% of answers below 0.7 were wrong, against 0% from 0.70-0.89.+ #+ # Only affects providers that report a confidence. The LLM path returns a+ # bare category name and is never gated, so this changes nothing for anyone+ # who has not selected Jev.+ add_column :families, :categorization_confidence_threshold, :decimal, precision: 3, scale: 2, default: 0.7, null: false+ # Shadow stays off: it runs a second provider per batch and doubles spend.+ add_column :families, :categorization_shadow_rate, :decimal, precision: 3, scale: 2, default: 0, null: false++ add_check_constraint :families,+ "categorization_confidence_threshold >= 0 AND categorization_confidence_threshold <= 1",+ name: "chk_families_categorization_confidence_threshold"+ add_check_constraint :families,+ "categorization_shadow_rate >= 0 AND categorization_shadow_rate <= 1",+ name: "chk_families_categorization_shadow_rate"+ end+enddiff --git a/db/migrate/20260920160100_create_categorization_comparisons.rb b/db/migrate/20260920160100_create_categorization_comparisons.rbnew file mode 100644index 0000000000..ed337bfb98--- /dev/null+++ b/db/migrate/20260920160100_create_categorization_comparisons.rb@@ -0,0 +1,27 @@+class CreateCategorizationComparisons < ActiveRecord::Migration[8.1]+ def change+ create_table :categorization_comparisons, id: :uuid, default: -> { "gen_random_uuid()" } do |t|+ t.references :family, null: false, foreign_key: true, type: :uuid+ # Nullified rather than cascaded: a comparison stays meaningful for+ # analysis after the transaction it described is gone.+ t.references :transaction, null: true, foreign_key: { on_delete: :nullify }, type: :uuid++ t.string :applied_provider, null: false+ t.string :applied_category_name+ t.string :shadow_provider, null: false+ t.string :shadow_category_name+ # Null whenever the shadow provider reports no confidence — the LLM+ # providers never do.+ t.decimal :shadow_confidence, precision: 5, scale: 4+ t.jsonb :shadow_probabilities, default: {}, null: false++ t.boolean :agreed, null: false++ t.timestamps+ end++ # The analysis query is "show me where they disagreed, most recent first".+ add_index :categorization_comparisons, [ :family_id, :agreed, :created_at ],+ name: "index_categorization_comparisons_on_family_agreement"+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex ef1b0e3ddf..f18e132f1a 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -417,6 +417,23 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_22_230000) dot.index ["family_id"], name: "index_categories_on_family_id"end+ create_table "categorization_comparisons", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.boolean "agreed", null: false+ t.string "applied_category_name"+ t.string "applied_provider", null: false+ t.datetime "created_at", null: false+ t.uuid "family_id", null: false+ t.string "shadow_category_name"+ t.decimal "shadow_confidence", precision: 5, scale: 4+ t.jsonb "shadow_probabilities", default: {}, null: false+ t.string "shadow_provider", null: false+ t.uuid "transaction_id"+ t.datetime "updated_at", null: false+ t.index ["family_id", "agreed", "created_at"], name: "index_categorization_comparisons_on_family_agreement"+ t.index ["family_id"], name: "index_categorization_comparisons_on_family_id"+ t.index ["transaction_id"], name: "index_categorization_comparisons_on_transaction_id"+ end+create_table "chats", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|t.datetime "created_at", null: falset.jsonb "error"@@ -820,6 +837,9 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_22_230000) dot.string "assistant_type", default: "builtin", null: falset.boolean "auto_sync_on_login", default: true, null: falset.string "bills_feed_token"+ t.decimal "categorization_confidence_threshold", precision: 3, scale: 2, default: "0.7", null: false+ t.string "categorization_provider", default: "llm", null: false+ t.decimal "categorization_shadow_rate", precision: 3, scale: 2, default: "0.0", null: falset.string "country", default: "US"t.datetime "created_at", null: falset.string "currency", default: "USD"@@ -843,6 +863,9 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_22_230000) dot.datetime "updated_at", null: falset.string "vector_store_id"t.index ["bills_feed_token"], name: "index_families_on_bills_feed_token", unique: true+ t.check_constraint "categorization_confidence_threshold >= 0::numeric AND categorization_confidence_threshold <= 1::numeric", name: "chk_families_categorization_confidence_threshold"+ t.check_constraint "categorization_provider::text = ANY (ARRAY['llm'::character varying::text, 'jev'::character varying::text])", name: "chk_families_categorization_provider"+ t.check_constraint "categorization_shadow_rate >= 0::numeric AND categorization_shadow_rate <= 1::numeric", name: "chk_families_categorization_shadow_rate"t.check_constraint "default_account_sharing::text = ANY (ARRAY['shared'::character varying::text, 'private'::character varying::text])", name: "chk_families_default_account_sharing"t.check_constraint "month_start_day >= 1 AND month_start_day <= 28", name: "month_start_day_range"end@@ -2342,7 +2365,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_22_230000) dot.index ["account_id"], name: "index_simplefin_accounts_on_account_id"t.index ["simplefin_item_id", "account_id"], name: "idx_unique_sfa_per_item_and_upstream", unique: true, where: "(account_id IS NOT NULL)"t.index ["simplefin_item_id"], name: "index_simplefin_accounts_on_simplefin_item_id"- t.check_constraint "balance_sign_override::text = ANY (ARRAY['credit'::character varying, 'debt'::character varying]::text[])", name: "chk_simplefin_accounts_balance_sign_override"+ t.check_constraint "balance_sign_override::text = ANY (ARRAY['credit'::character varying::text, 'debt'::character varying::text])", name: "chk_simplefin_accounts_balance_sign_override"endcreate_table "simplefin_items", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|@@ -2911,6 +2934,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_22_230000) doadd_foreign_key "budgets", "families"add_foreign_key "budgets", "users", on_delete: :cascadeadd_foreign_key "categories", "families"+ add_foreign_key "categorization_comparisons", "families"+ add_foreign_key "categorization_comparisons", "transactions", on_delete: :nullifyadd_foreign_key "chats", "users"add_foreign_key "coinbase_accounts", "coinbase_items"add_foreign_key "coinbase_items", "families"diff --git a/docs/llm-guides/README.md b/docs/llm-guides/README.mdindex 4ab5320d2e..16d33f63f2 100644--- a/docs/llm-guides/README.md+++ b/docs/llm-guides/README.md@@ -13,6 +13,7 @@ being changed. These guides hold the detailed conventions and procedures.| Add or modify an API v1 endpoint | [API endpoint consistency](api-endpoint-consistency.md) || Change provider imports, pending/FX metadata or diagnostics | [Provider sync guidance](providers.md) || Add a securities price provider | [Provider walkthrough](adding-a-securities-provider.md) |+| Add a typed classification provider (Jev/TypeSafe) | [Classification provider walkthrough](adding-a-classification-provider.md) || Add a preview survey or usage event | [Feedback surveys](feedback-surveys.md) || Gate or release a preview feature | [Preview-feature gating](gating-a-preview-feature.md) || Change goals, pledges or reconciliation | [Goals](goals.md) |diff --git a/docs/llm-guides/adding-a-classification-provider.md b/docs/llm-guides/adding-a-classification-provider.mdnew file mode 100644index 0000000000..885f46c3eb--- /dev/null+++ b/docs/llm-guides/adding-a-classification-provider.md@@ -0,0 +1,260 @@+# Adding a Classification Provider++A classification provider answers *typed questions about a state* and returns+calibrated probabilities. It does not generate text. `Provider::Jev` (TypeSafe)+is the reference implementation.++If the provider you are adding produces prose — chat replies, summaries, a+merchant's website URL — it is an LLM provider, not a classification provider.+Read [provider sync guidance](providers.md) and `Provider::LlmConcept` instead.++## Why this is separate from `:llm`++`Provider::Registry.preferred_llm_provider` returns the first LLM provider that+holds credentials, and every caller assumes the result can do everything an LLM+does. A classification provider cannot satisfy `#chat_response` or+`#process_pdf` — not "has not implemented them yet", but *cannot*, because it+emits a choice rather than tokens.++Registering one under `:llm` would therefore let a Jev API key route **chat**+traffic to something physically unable to serve it. So classification providers+live under their own registry concept:++```ruby+# app/models/provider/registry.rb+CONCEPTS = %i[exchange_rates securities llm property_valuations classification]++when :classification+ %i[jev]+```++OpenAI and Anthropic stay under `:llm`. They can categorize, but they cannot+answer typed questions, so they do not belong to a concept whose contract is+`#decide`. The eval runner builds them by name when benchmarking.++## The contract: one `#decide`, many questions++`Provider::ClassificationConcept` defines a single primitive:++```ruby+def decide(state:, questions:, model: "", family: nil)+```++- `state` — String, Hash or Array describing the thing being decided about+- `questions` — a Hash of question key => question definition+- returns a `DecisionSet`++**There is deliberately no method per task.** The provider bills almost entirely+for shipping the state and the option lists, not for the questions asked about+them. Measured against Jev, **five questions cost 1.31× one question**. A+`classify` / `score` / `judge` trio would force three round trips and pay for+the state three times over.++So when you add a task, batch its questions into an existing `#decide` call+where one is already being made for that state, rather than adding a call.++## The three question types++| Type | Asks | Returns |+| --- | --- | --- |+| `choice` | pick one of these options | the selected key, full distribution, confidence |+| `score` | position on an ordered rubric | float against a `legend`, distribution, confidence |+| `noul` | is this statement true | probability 0.0–1.0 |++```ruby+provider.decide(+ state: { description: "SQ *BLUE BOTTLE COFFEE", amount: 6.75 },+ questions: {+ category: {+ type: "choice",+ instructions: "Which spending category best fits this bank transaction?",+ criteria: { "Groceries" => nil, "Coffee" => "Subcategory of Restaurants" }+ }+ }+)+```++Read answers off the `DecisionSet`:++```ruby+set[:category].value # => "Coffee"+set[:category].confidence # => 0.97+set[:category].probabilities # => { "Coffee" => 0.97, "Groceries" => 0.03 }+set.usage # => { "input_tokens" =>, "output_tokens" =>, "cost" => }+```++`noul` reports no separate confidence — the probability *is* the answer — so+`Provider::Jev` derives one from distance off the midpoint (0.5 is maximal+uncertainty).++### Always give Choice an opt-out++A `choice` question **always** returns one of the keys it was given. Offer only+real categories and a transaction matching none of them still gets one, because+the model has nowhere else to put it. Add an explicit sentinel and translate it+back to `nil` at the boundary:++```ruby+UNCATEGORIZED = "__uncategorized__"+criteria[UNCATEGORIZED] = "No listed category is a reasonable fit"+```++Verified behaviour: an opaque `ACH DEBIT 4471920 REF#88213` descriptor selects+the sentinel at probability 1.0. Without it, that row would have been assigned a+real category at low confidence.++The same applies to conditional questions. Asking "what kind of recurring charge+is this?" about a one-off coffee still returns an answer — so only *consume* it+for rows something else has already established are recurring.++## Structural compatibility with the LLM shapes++`CategoryDecision` responds to `#transaction_id` and `#category_name`, exactly+like `Provider::LlmConcept::AutoCategorization`. That is deliberate:+`Family::AutoCategorizer` and the eval runners consume either shape unchanged+and ignore the extra `confidence` / `probabilities` / `usage` fields.++Keep that property when adding types. A caller should not need to know which+kind of provider served it.++## You are second in a cascade++A classification provider does not see the transaction stream. `Family#auto_categorize_transactions`+runs `Family::BayesCategorizer` first — a pure-Ruby naive Bayes model trained on+the family's own categorized history, costing nothing and calling nobody — and+only the transactions it declines reach `Family::AutoCategorizer`, where your+provider sits:++```ruby+# app/models/family.rb+bayes_result = Family::BayesCategorizer.new(self).classify_and_apply(transaction_ids)+remaining_ids = Array(transaction_ids) - bayes_result.categorized_ids+# ... if remaining_ids is empty, no provider is called at all+llm_modified_count = AutoCategorizer.new(self, transaction_ids: remaining_ids).auto_categorize+```++Two consequences worth internalising before you benchmark anything.++**Your provider receives the hard tail.** Bayes takes the repeat merchants and+the obvious descriptors; what reaches you is what a model trained on this+family's own history could not place. Accuracy measured over a whole golden+dataset therefore *overstates* what your provider contributes in production,+because it credits you for rows you would never have been handed. The number+that matters is accuracy on the subset Bayes declines.++**Your confidence threshold is the second one in series.** `BayesCategorizer::CONFIDENCE_THRESHOLD`+is a hardcoded `0.7`; `families.categorization_confidence_threshold` also+defaults to `0.7`, derived independently from a golden-set sweep. That the two+coincide is a coincidence — different models over different distributions.+Do not extract them into a shared constant.++## Provider resolution++Categorization resolves through the family, not a global Setting — the choice+decides whose transaction descriptions leave the instance, the same reason+`assistant_type` lives on `Family`:++```ruby+# app/models/family.rb+def resolved_categorization_provider+ jev = configured_jev_provider if effective_categorization_provider == "jev"+ jev || Provider::Registry.preferred_llm_provider+end+```++Resolution must not raise. The registry builds a fresh provider on every+lookup, so a constructor that validates its configuration — as+`Provider::Jev` does with `endpoint_allowed?` — raises from inside a method+whose whole contract is to fall back. ENV is how that happens: `JEV_ENDPOINT`+never passes through the settings form that runs the identical check, so one+`http://` typo against a non-loopback host stopped categorization entirely and+500'd the rule confirmation screen. `configured_jev_provider` rescues+`Provider::Error` and treats it as "not configured", capturing a+`DebugLogEntry` so the operator can see why their chosen provider is not+running. Rescue the provider error narrowly; anything wider hides real bugs.++This is the same class of exposure the `CATEGORIZATION_CONFIDENCE_THRESHOLD`+and `CATEGORIZATION_SHADOW_RATE` overrides are clamped for. An ENV override+bypasses column validations, so every one of them needs its own guard at the+point of use.++Credentials alone never switch a classification provider on, and the preview+flag plays no part here — it gates whether the *selector* is offered (see+[preview-feature gating](gating-a-preview-feature.md)), never what runs. A+family that opted into preview and then chose the AI provider gets the AI+provider.++Anything that needs to name the provider — the rule confirmation screen's cost+estimate, for instance — must call this same method rather than resolving+separately, or the screen will quote a provider that will not run.++## Endpoints, gateways and disclosure++Default to the vendor's own API. Gateways (OpenRouter and similar) serve an+identical payload, so one class covers both, but routing a family's financial+data through an extra party is something an operator opts into:++```ruby+DEFAULT_ENDPOINT = "https://api.typesafe.ai/v1/systemone"+VENDOR_HOST = "api.typesafe.ai"+```++When an operator points `JEV_ENDPOINT` at a gateway, the settings disclosure has+to say so — `Provider::Jev.effective_proxied?` and `.effective_host` exist for+exactly that. Telling someone their bank descriptions go to TypeSafe is wrong+when they transit a proxy first.++Require an explicit key with no fallback to another provider's credentials. An+operator holding an unrelated `OPENROUTER_API_KEY` should not find+classification silently enabled and billing them.++## Concurrency++One state per request means a batch of transactions is a batch of requests.+They are independent and latency-bound, so they run on a bounded pool — matching+the fan-out idiom in `Security::Provided`:++```ruby+pool = Concurrent::FixedThreadPool.new([ @concurrency, items.size ].min)+items.map { |item| Concurrent::Promises.future_on(pool) { ... } }.map(&:value!)+```++Bounded, not `Promises.future` alone: this fans out per transaction, so an+unbounded pool would open a socket per row. `value!` re-raises a worker's+exception so a failed request surfaces through `with_provider_response` rather+than landing as a `nil`.++One Faraday gotcha: `faraday-retry` only retries `IDEMPOTENT_METHODS`, which+excludes POST, and `retry_statuses` is never consulted because `raise_error`+converts the status to an exception first. Both have to be overridden or the+backoff silently never runs.++## Evals++`Eval::ProviderFactory` builds the provider for a run, taking per-run overrides+the registry deliberately does not accept. Add a branch there — both+`Eval::Runners::Base` and `Eval::Langfuse::ExperimentRunner` go through it.++A classification provider spending one request per sample can attribute cost per+sample, which is what makes `cost_per_sample` meaningful. Carry `usage` on the+returned struct so the runner can record it.++```bash+JEV_API_KEY=... PROVIDER=jev bin/rails "evals:run[categorization_golden_v2,jev-latest]"+```++Check `error_rate` before believing an accuracy figure — a stale model slug+records every sample as incorrect and otherwise reads as a credible 0%.++## Checklist++- [ ] `include ClassificationConcept`, implement `#decide`+- [ ] Register under `:classification`, not `:llm`+- [ ] Explicit API key, no fallback to another provider's credentials+- [ ] Default endpoint is the vendor's own; disclosure names the configured host+- [ ] Provider resolution rescues construction failures and falls back, never raises+- [ ] Every Choice question has an opt-out sentinel, translated to `nil`+- [ ] Return types structurally compatible with the `LlmConcept` equivalents+- [ ] Per-request `usage` carried through for eval cost attribution+- [ ] Branch added to `Eval::ProviderFactory`+- [ ] Tests stub HTTP with WebMock — the suite blocks real connectionsdiff --git a/lib/tasks/evals.rake b/lib/tasks/evals.rakeindex f34afdce0a..0dbf5f42c5 100644--- a/lib/tasks/evals.rake+++ b/lib/tasks/evals.rake@@ -93,10 +93,11 @@ namespace :evals doprovider: provider,model: model,name: run_name,- status: "pending"+ status: "pending",+ provider_config: split_config)- runner = dataset.runner_class.new(eval_run)+ runner = runner_class_for(dataset, provider).new(eval_run)puts "Running evaluation..."start_time = Time.current@@ -200,10 +201,10 @@ namespace :evals dodesc "Generate report for specific runs"task :report, [ :run_ids ] => :environment do |_t, args|- run_ids = (args[:run_ids] || ENV["RUN_IDS"])&.split(",")+ run_ids = run_ids_from(args[:run_ids], args.extras, "RUN_IDS")runs = if run_ids.present?- Eval::Run.where(id: run_ids)+ runs_for!(run_ids)elseEval::Run.completed.order(created_at: :desc).limit(5)end@@ -233,6 +234,77 @@ namespace :evals doendend+ desc "Report the Bayes -> provider cascade (provider accuracy on the residual Bayes declines)"+ task :cascade, [ :bayes_run_id, :provider_run_ids ] => :environment do |_t, args|+ bayes_id = args[:bayes_run_id] || ENV["BAYES"]+ provider_ids = run_ids_from(args[:provider_run_ids], args.extras, "PROVIDERS")++ if bayes_id.blank? || provider_ids.blank?+ puts "Usage: rake evals:cascade[bayes_run_id,provider_run_id1,provider_run_id2]"+ puts " or: BAYES=<run_id> PROVIDERS=<id1>,<id2> rake evals:cascade"+ puts+ puts "Produce the runs first, all on the same split:"+ puts " PROVIDER=bayes SPLIT_ROLE=test rake 'evals:run[categorization_golden_v2,naive-bayes]'"+ puts " PROVIDER=jev SPLIT_ROLE=test rake 'evals:run[categorization_golden_v2,~typesafe/jev-latest]'"+ exit 1+ end++ bayes_run = runs_for!([ bayes_id ]).first+ provider_runs = runs_for!(provider_ids)++ puts Eval::Reporters::CascadeReport.new(bayes_run: bayes_run, provider_runs: provider_runs)+ end++ desc "Analyze a candidate run against a baseline (calibration, disagreement, verdict)"+ task :analyze, [ :baseline_run_id, :candidate_run_id ] => :environment do |_t, args|+ baseline_id = args[:baseline_run_id] || ENV["BASELINE"]+ candidate_id = args[:candidate_run_id] || ENV["CANDIDATE"]++ if baseline_id.blank? || candidate_id.blank?+ puts "Usage: rake evals:analyze[baseline_run_id,candidate_run_id]"+ puts " or: BASELINE=<run_id> CANDIDATE=<run_id> rake evals:analyze"+ puts+ puts "The candidate is the provider under evaluation; the baseline is what"+ puts "it would replace. Both runs must cover the same dataset."+ exit 1+ end++ baseline = Eval::Run.find(baseline_id)+ candidate = Eval::Run.find(candidate_id)++ puts "=" * 80+ puts "Candidate Analysis"+ puts "=" * 80+ puts " Dataset: #{candidate.dataset.name}"+ puts " Baseline: #{baseline.provider}:#{baseline.model}"+ puts " Candidate: #{candidate.provider}:#{candidate.model}"+ puts++ puts Eval::Reporters::ComparisonReporter.new([ baseline, candidate ]).to_table+ puts++ puts "-" * 80+ puts "Confidence calibration -- #{candidate.provider}:#{candidate.model}"+ puts "-" * 80+ puts Eval::Metrics::Calibration.new(candidate).to_table+ puts++ disagreement = Eval::Reporters::DisagreementReport.new(baseline, candidate)+ puts "-" * 80+ puts "Disagreement"+ puts "-" * 80+ puts disagreement.to_table+ puts++ puts "-" * 80+ puts Eval::Reporters::Recommendation.new(+ baseline: baseline,+ candidate: candidate,+ disagreement: disagreement+ ).to_table+ puts+ end+desc "Quick smoke test to verify provider configuration"task smoke_test: :environment doputs "Running smoke test..."@@ -748,14 +820,76 @@ namespace :evals doprivate+ # Bayes is trained per-family rather than called as a provider, so it needs+ # its own runner regardless of the dataset's eval_type.+ def runner_class_for(dataset, provider)+ return Eval::Runners::BayesRunner if provider.to_s == "bayes"++ dataset.runner_class+ end++ # A run restricted to one side of the train/test split. Only set when asked+ # for: an unsplit run still evaluates the whole dataset, which is what the+ # existing single-provider benchmarks do.+ # Rake binds only the arguments a task declares, so `rake 'x[a,b,c]'` on a+ # two-argument task puts "c" in `extras` rather than dropping it. Reading+ # both means the comma form works for any number of ids and the CLI needs+ # no second separator.+ def run_ids_from(value, extras, env_key)+ ids = value.present? ? [ value, *extras ] : ENV[env_key].to_s.split(",")++ ids.map(&:strip).reject(&:blank?)+ end++ # All-or-nothing: `where(id: ids)` returns whatever matched, so a single+ # mistyped id would quietly narrow the report rather than fail, and the+ # output gives no hint that a run is missing. Comparing like for like+ # against ids the caller asked for by name is the only way to tell the+ # difference between "this run scored badly" and "this run was never read".+ def runs_for!(ids)+ runs = Eval::Run.where(id: ids).to_a+ missing = ids - runs.map(&:id)++ if missing.any?+ puts "Error: no run found for #{missing.join(', ')}"+ exit 1+ end++ runs+ end++ def split_config+ role = ENV["SPLIT_ROLE"].presence+ return {} if role.blank?++ {+ "split_role" => role,+ "split_seed" => (ENV["SPLIT_SEED"].presence || Eval::Runners::SampleSplit::DEFAULT_SEED).to_i,+ "split_ratio" => (ENV["SPLIT_RATIO"].presence || Eval::Runners::SampleSplit::DEFAULT_TRAIN_RATIO).to_f+ }+ end+def format_metric_value(value)case value+ when nil+ # Distinguishes "the provider reported nothing" from a measured zero.+ # Printing a bare blank reads as a value of none, which for cost is the+ # difference between free and unmeasured.+ "not reported"when Float- value.round(4)+ format_metric_float(value)when BigDecimal- value.to_f.round(4)+ format_metric_float(value.to_f)elsevalueendend++ # Per-sample costs run around 1e-5, which 4 decimal places renders as 0.0 —+ # reporting a paid provider as free. Small magnitudes keep more places.+ def format_metric_float(value)+ return value.round(4) if value.zero? || value.abs >= 0.01++ value.round(8)+ endenddiff --git a/test/controllers/rules_controller_test.rb b/test/controllers/rules_controller_test.rbindex aaf5c9e00e..7e4b1d720a 100644--- a/test/controllers/rules_controller_test.rb+++ b/test/controllers/rules_controller_test.rb@@ -230,6 +230,36 @@ class RulesControllerTest < ActionDispatch::IntegrationTestassert_select "td", text: "10 / 7 / 4 / 3"end+ # The confirmation screen used to hardcode :openai, so it quoted a provider+ # that would not run — an Anthropic install saw the OpenAI model, and a family+ # on Jev saw whichever LLM model happened to be configured.+ test "confirm names the provider that will actually categorize" do+ rule = rules(:one)+ rule.actions.create!(action_type: "auto_categorize")+ @user.family.update!(categorization_provider: "jev")+ # The general stub catches the :openai lookup preferred_llm_provider makes;+ # the specific one wins for :jev.+ Provider::Registry.stubs(:get_provider).returns(nil)+ Provider::Registry.stubs(:get_provider).with(:jev).returns(Provider::Jev.allocate)+ Provider::Jev.stubs(:effective_model).returns("~typesafe/jev-latest")++ get confirm_rule_url(rule)++ assert_response :success+ assert_match "~typesafe/jev-latest", response.body+ end++ test "confirm does not name Jev when the family has not selected it" do+ rule = rules(:one)+ rule.actions.create!(action_type: "auto_categorize")+ assert_equal "llm", @user.family.categorization_provider++ get confirm_rule_url(rule)++ assert_response :success+ assert_no_match "~typesafe/jev-latest", response.body+ end+test "should get confirm_all" doget confirm_all_rules_urlassert_response :successdiff --git a/test/controllers/settings/hostings_controller_test.rb b/test/controllers/settings/hostings_controller_test.rbindex ad5186c404..aefdf22103 100644--- a/test/controllers/settings/hostings_controller_test.rb+++ b/test/controllers/settings/hostings_controller_test.rb@@ -27,7 +27,7 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTestteardown do# These tests persist global Setting.* values; reset them so state can't# leak into later (order-dependent) tests.- %i[anthropic_access_token anthropic_base_url anthropic_model llm_provider twelve_data_api_key openai_access_token openai_request_timeout ai_response_timeout external_assistant_token rentcast_api_key realie_api_key].each do |key|+ %i[anthropic_access_token anthropic_base_url anthropic_model jev_api_key jev_endpoint jev_model llm_provider twelve_data_api_key openai_access_token openai_request_timeout ai_response_timeout external_assistant_token rentcast_api_key realie_api_key].each do |key|Setting.public_send("#{key}=", nil)endend@@ -325,6 +325,133 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTestendend+ test "can update categorization tuning when opted into preview features" do+ with_self_hosting do+ enable_preview_features!++ patch settings_hosting_url, params: {+ family: { categorization_confidence_threshold: "0.7", categorization_shadow_rate: "0.25" }+ }++ @user.family.reload+ assert_in_delta 0.7, @user.family.categorization_confidence_threshold, 0.001+ assert_in_delta 0.25, @user.family.categorization_shadow_rate, 0.001+ end+ end++ test "rejects a categorization threshold outside 0 and 1" do+ with_self_hosting do+ enable_preview_features!+ # Compare against what was actually stored rather than a literal, so this+ # keeps testing "rejection leaves the value alone" if the default moves.+ before = @user.family.categorization_confidence_threshold++ patch settings_hosting_url, params: {+ family: { categorization_confidence_threshold: "1.5" }+ }++ assert_response :unprocessable_entity+ assert_match(/between 0 and 1/, flash[:alert])+ assert_in_delta before, @user.family.reload.categorization_confidence_threshold, 0.001+ end+ end++ test "rejects a non-numeric categorization shadow rate" do+ with_self_hosting do+ enable_preview_features!++ patch settings_hosting_url, params: { family: { categorization_shadow_rate: "lots" } }++ assert_response :unprocessable_entity+ assert_in_delta 0.0, @user.family.reload.categorization_shadow_rate, 0.001+ end+ end++ test "ignores categorization tuning from a user without preview features" do+ with_self_hosting do+ family = users(:family_admin).family+ assert_not family.preview_features_enabled?++ patch settings_hosting_url, params: { family: { categorization_shadow_rate: "0.5" } }++ assert_in_delta 0.0, family.reload.categorization_shadow_rate, 0.001+ end+ end++ test "can update jev api key when self hosting is enabled" do+ with_self_hosting do+ patch settings_hosting_url, params: { setting: { jev_api_key: "fake-jev-key-for-tests" } }++ assert_equal "fake-jev-key-for-tests", Setting.jev_api_key+ end+ end++ test "ignores redacted jev api key placeholder" do+ with_self_hosting do+ Setting.jev_api_key = "previous-key"++ patch settings_hosting_url, params: { setting: { jev_api_key: "********" } }++ assert_equal "previous-key", Setting.jev_api_key+ end+ end++ test "can clear jev api key by submitting a blank value" do+ with_self_hosting do+ Setting.jev_api_key = "previous-key"++ patch settings_hosting_url, params: { setting: { jev_api_key: "" } }++ assert_nil Setting.jev_api_key+ end+ end++ test "can update jev endpoint and model" do+ with_self_hosting do+ patch settings_hosting_url, params: { setting: { jev_endpoint: "https://api.typesafe.ai/v1/systemone", jev_model: "jev-latest" } }++ assert_equal "https://api.typesafe.ai/v1/systemone", Setting.jev_endpoint+ assert_equal "jev-latest", Setting.jev_model+ end+ end++ test "rejects non-URL jev endpoint" do+ with_self_hosting do+ Setting.jev_endpoint = nil++ patch settings_hosting_url, params: { setting: { jev_endpoint: "not-a-url" } }++ assert_response :unprocessable_entity+ assert_match(/Jev Endpoint must be an http/, flash[:alert])+ assert_nil Setting.jev_endpoint+ end+ end++ test "rejects a plaintext jev endpoint but allows loopback" do+ with_self_hosting do+ Setting.jev_endpoint = nil++ patch settings_hosting_url, params: { setting: { jev_endpoint: "http://api.typesafe.ai/v1/systemone" } }++ assert_response :unprocessable_entity+ assert_nil Setting.jev_endpoint++ patch settings_hosting_url, params: { setting: { jev_endpoint: "http://localhost:4000/v1/systemone" } }++ assert_equal "http://localhost:4000/v1/systemone", Setting.jev_endpoint+ end+ end++ test "clears jev endpoint when blank value submitted" do+ with_self_hosting do+ Setting.jev_endpoint = "https://api.typesafe.ai/v1/systemone"++ patch settings_hosting_url, params: { setting: { jev_endpoint: "" } }++ assert_nil Setting.jev_endpoint+ end+ end+test "can update llm_provider to anthropic" dowith_self_hosting dopatch settings_hosting_url, params: { setting: { llm_provider: "anthropic" } }@@ -835,4 +962,10 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTestSetting.securities_providers = ""Setting.tinkoff_invest_api_key = nilend++ private+ def enable_preview_features!+ @user = users(:family_admin)+ @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => true))+ endenddiff --git a/test/models/eval/langfuse/experiment_runner_test.rb b/test/models/eval/langfuse/experiment_runner_test.rbnew file mode 100644index 0000000000..a4cd018022--- /dev/null+++ b/test/models/eval/langfuse/experiment_runner_test.rb@@ -0,0 +1,112 @@+require "test_helper"++class Eval::Langfuse::ExperimentRunnerTest < ActiveSupport::TestCase+ setup do+ @dataset = Eval::Dataset.create!(+ name: "test_exp_#{SecureRandom.hex(4)}",+ eval_type: "categorization",+ version: "1.0"+ )+ @client = stub("langfuse_client")+ end++ def runner(provider:, model:, provider_config: {})+ Eval::Langfuse::ExperimentRunner.new(+ @dataset,+ model: model,+ provider: provider,+ client: @client,+ provider_config: provider_config+ )+ end++ test "reads provider config written with string keys" do+ # Regression: this class read provider_config with symbol keys while every+ # other spelling of the same config is string-keyed (Eval::Run#provider_config+ # is jsonb). A string-keyed caller silently fell through to ENV/Setting.+ Provider::Openai.expects(:new).with(+ "string-key-token",+ uri_base: "https://example.test/v1",+ model: "gpt-4.1"+ )++ runner(+ provider: "openai",+ model: "gpt-4.1",+ provider_config: { "access_token" => "string-key-token", "uri_base" => "https://example.test/v1" }+ ).send(:build_provider)+ end++ test "still reads provider config written with symbol keys" do+ Provider::Openai.expects(:new).with(+ "symbol-key-token",+ uri_base: nil,+ model: "gpt-4.1"+ )++ runner(+ provider: "openai",+ model: "gpt-4.1",+ provider_config: { access_token: "symbol-key-token", uri_base: nil }+ ).send(:build_provider)+ end++ test "builds a jev provider" do+ built = runner(+ provider: "jev",+ model: "~typesafe/jev-latest",+ provider_config: { "api_key" => "test-key" }+ ).send(:build_provider)++ assert_instance_of Provider::Jev, built+ end++ test "passes jev endpoint and concurrency through from provider config" do+ Provider::Jev.expects(:new).with(+ "test-key",+ endpoint: "https://api.typesafe.ai/v1/systemone",+ model: "jev-latest",+ concurrency: 4+ )++ runner(+ provider: "jev",+ model: "jev-latest",+ provider_config: {+ "api_key" => "test-key",+ "endpoint" => "https://api.typesafe.ai/v1/systemone",+ "concurrency" => 4+ }+ ).send(:build_provider)+ end++ test "raises when jev has no api key configured" do+ Provider::Jev.stubs(:api_key).returns(nil)++ error = assert_raises(Eval::ProviderFactory::Error) do+ runner(provider: "jev", model: "jev-latest").send(:build_provider)+ end++ assert_match(/Jev API key not configured/, error.message)+ end++ test "rejects an unknown provider" do+ error = assert_raises(Eval::ProviderFactory::Error) do+ runner(provider: "nonesuch", model: "x").send(:build_provider)+ end++ assert_match(/Unsupported provider: nonesuch/, error.message)+ end++ test "honors a json_mode written with string keys" do+ items = [ { "expectedOutput" => { "category_name" => "Food & Drink" } } ]++ effective = runner(+ provider: "openai",+ model: "gpt-4.1",+ provider_config: { "json_mode" => "strict" }+ ).send(:json_mode_for_batch, items)++ assert_equal "strict", effective+ end+enddiff --git a/test/models/eval/metrics/base_test.rb b/test/models/eval/metrics/base_test.rbnew file mode 100644index 0000000000..fcd9df703d--- /dev/null+++ b/test/models/eval/metrics/base_test.rb@@ -0,0 +1,89 @@+require "test_helper"++class Eval::Metrics::BaseTest < ActiveSupport::TestCase+ setup do+ @dataset = Eval::Dataset.create!(+ name: "test_cost_#{SecureRandom.hex(4)}",+ eval_type: "categorization",+ version: "1.0"+ )+ @run = Eval::Run.create!(+ dataset: @dataset, provider: "jev", model: "jev-latest",+ name: "cost", status: "running"+ )+ end++ # costs: array of cost-or-nil, one per sample+ def record(costs)+ costs.each_with_index do |cost, index|+ sample = @dataset.samples.create!(+ input_data: { "description" => "txn #{index}" },+ expected_output: { "category_name" => "Coffee" },+ difficulty: "easy"+ )+ @run.results.create!(+ sample: sample,+ actual_output: { "category_name" => "Coffee" },+ correct: true,+ cost: cost+ )+ end+ end++ def metrics+ Eval::Metrics::CategorizationMetrics.new(@run)+ end++ test "reports no cost when the provider priced nothing" do+ record([ nil, nil, nil ])++ # TypeSafe's native API returns token counts without a settled price, and+ # the OpenAI path never populates cost at all. `sum` returns 0 over+ # all-NULL, which would report a paid provider as free.+ calculated = metrics.calculate++ assert_nil calculated[:total_cost]+ assert_nil calculated[:cost_per_sample]+ end++ test "reports a measured zero as zero" do+ record([ 0.0, 0.0 ])++ # A genuinely free run is a different claim from an unmeasured one, and+ # must survive the guard that suppresses the latter.+ calculated = metrics.calculate++ assert_equal 0.0, calculated[:total_cost]+ assert_equal 0.0, calculated[:cost_per_sample]+ end++ test "totals cost when only some samples are priced" do+ record([ 0.002, nil, 0.004 ])++ # Partial instrumentation is still a real figure, but it is a floor rather+ # than a total — averaged over every sample, not only the priced ones.+ calculated = metrics.calculate++ assert_in_delta 0.006, calculated[:total_cost], 0.000001+ assert_in_delta 0.002, calculated[:cost_per_sample], 0.000001+ end++ test "stores nil rather than zero on a run that priced nothing" do+ record([ nil, nil ])++ @run.complete!(metrics.calculate)++ # Eval::Reporters::ComparisonReporter picks the cheapest run with+ # `total_cost || Float::INFINITY`, so a stored 0 would beat every+ # instrumented run and crown whichever provider measures cost least.+ assert_nil @run.reload.total_cost+ end++ test "stores the total on a run that priced its calls" do+ record([ 0.001, 0.003 ])++ @run.complete!(metrics.calculate)++ assert_in_delta 0.004, @run.reload.total_cost.to_f, 0.000001+ end+enddiff --git a/test/models/eval/metrics/calibration_test.rb b/test/models/eval/metrics/calibration_test.rbnew file mode 100644index 0000000000..01016b3669--- /dev/null+++ b/test/models/eval/metrics/calibration_test.rb@@ -0,0 +1,103 @@+require "test_helper"++class Eval::Metrics::CalibrationTest < ActiveSupport::TestCase+ setup do+ @dataset = Eval::Dataset.create!(+ name: "test_calib_#{SecureRandom.hex(4)}",+ eval_type: "categorization",+ version: "1.0"+ )+ @run = Eval::Run.create!(+ dataset: @dataset, provider: "jev", model: "jev-latest",+ name: "calib", status: "completed"+ )+ end++ # confidences: array of [confidence_or_nil, correct]+ def record(pairs)+ pairs.each_with_index do |(confidence, correct), index|+ sample = @dataset.samples.create!(+ input_data: { "description" => "txn #{index}" },+ expected_output: { "category_name" => "Coffee" },+ difficulty: "easy"+ )+ metadata = confidence.nil? ? {} : { "confidence" => confidence }+ @run.results.create!(+ sample: sample,+ actual_output: { "category_name" => correct ? "Coffee" : "Rent" },+ correct: correct,+ metadata: metadata+ )+ end+ end++ test "reports unsupported when the provider states no confidence" do+ record([ [ nil, true ], [ nil, false ] ])++ calibration = Eval::Metrics::Calibration.new(@run)++ # A provider that reports nothing is unmeasurable, not badly calibrated —+ # the two must not be conflated.+ assert_not calibration.supported?+ assert_equal({ supported: false }, calibration.to_h)+ assert_nil calibration.expected_calibration_error+ assert_not calibration.overconfident?+ assert_match(/cannot be measured/, calibration.to_table)+ end++ test "a perfectly calibrated provider has no calibration error" do+ # Claims 0.9 in one bucket and is right 90% of the time there.+ record(Array.new(9) { [ 0.9, true ] } + [ [ 0.9, false ] ])++ calibration = Eval::Metrics::Calibration.new(@run)++ assert calibration.supported?+ assert_equal 10, calibration.sample_count+ assert_in_delta 0.0, calibration.expected_calibration_error, 0.0001+ assert_not calibration.overconfident?+ end++ test "flags a provider whose confidence outruns its accuracy" do+ # Claims 0.95 while being right half the time — the dangerous direction,+ # because this is what would auto-apply a wrong category.+ record(Array.new(5) { [ 0.95, true ] } + Array.new(5) { [ 0.95, false ] })++ calibration = Eval::Metrics::Calibration.new(@run)++ assert calibration.overconfident?+ assert_in_delta 0.45, calibration.expected_calibration_error, 0.0001++ bucket = calibration.curve.sole+ assert_equal "0.9-1.0", bucket[:range]+ assert_in_delta 0.5, bucket[:accuracy], 0.0001+ assert_in_delta(-0.45, bucket[:gap], 0.0001)+ end++ test "underconfidence is measured but not flagged as dangerous" do+ record(Array.new(10) { [ 0.5, true ] })++ calibration = Eval::Metrics::Calibration.new(@run)++ assert_in_delta 0.5, calibration.expected_calibration_error, 0.0001+ assert_not calibration.overconfident?, "being right more often than claimed is safe"+ end++ test "buckets predictions by stated confidence" do+ record([ [ 0.15, false ], [ 0.55, true ], [ 0.95, true ], [ 1.0, true ] ])++ ranges = Eval::Metrics::Calibration.new(@run).curve.map { |b| b[:range] }++ # 1.0 belongs in the top bucket rather than falling off the end.+ assert_equal [ "0.1-0.2", "0.5-0.6", "0.9-1.0" ], ranges+ assert_equal 2, Eval::Metrics::Calibration.new(@run).curve.last[:count]+ end++ test "ignores samples with no confidence alongside those that have one" do+ record([ [ 0.9, true ], [ nil, false ], [ 0.9, true ] ])++ calibration = Eval::Metrics::Calibration.new(@run)++ assert_equal 2, calibration.sample_count+ assert_in_delta 1.0, calibration.curve.sole[:accuracy], 0.0001+ end+enddiff --git a/test/models/eval/reporters/cascade_report_test.rb b/test/models/eval/reporters/cascade_report_test.rbnew file mode 100644index 0000000000..c4c2ac0950--- /dev/null+++ b/test/models/eval/reporters/cascade_report_test.rb@@ -0,0 +1,139 @@+require "test_helper"++class Eval::Reporters::CascadeReportTest < ActiveSupport::TestCase+ setup do+ @dataset = Eval::Dataset.create!(+ name: "cascade_test_#{SecureRandom.hex(4)}",+ eval_type: "categorization",+ version: "1.0"+ )+ # 4 samples: Bayes will cover the first two and decline the last two.+ @samples = 4.times.map { |i| build_sample("s#{i}") }+ end++ test "scores the provider on the residual, not the whole test set" do+ bayes = bayes_run(covered: { 0 => true, 1 => true }, declined: [ 2, 3 ])+ # Provider is right on both easy rows it would never see, and wrong on both+ # residual rows. Full-set accuracy 50%, residual accuracy 0% — the whole+ # point of the report is that those are different numbers.+ provider = provider_run("jev", correct_indexes: [ 0, 1 ])++ summary = Eval::Reporters::CascadeReport.new(bayes_run: bayes, provider_runs: [ provider ]).summary+ jev = summary[:providers]["jev:~typesafe/jev-latest"]++ assert_equal 50.0, jev[:full_accuracy]+ assert_equal 0.0, jev[:residual_accuracy], "must score only the rows Bayes declined"+ assert_equal 2, jev[:residual_scored]+ end++ test "declining is never scored as a correct answer" do+ # Sample 3 is null-expected. Bayes declining it is correct cascade+ # behaviour, but it is not Bayes answering "no category" — the provider+ # stage still has to resolve it.+ @samples[3].update!(expected_output: { "category_name" => nil })+ bayes = bayes_run(covered: { 0 => true, 1 => true }, declined: [ 2, 3 ])++ summary = Eval::Reporters::CascadeReport.new(bayes_run: bayes, provider_runs: []).summary++ assert_equal 2, summary[:bayes][:covered]+ assert_equal 2, summary[:bayes][:declined]+ assert_equal 100.0, summary[:bayes][:accuracy_on_covered]+ assert_equal 50.0, summary[:bayes][:coverage]+ end++ test "warns when a provider ran on a different split" do+ bayes = bayes_run(covered: { 0 => true }, declined: [ 1, 2, 3 ])+ provider = provider_run("jev", correct_indexes: [ 1 ])+ provider.update!(provider_config: { "split_role" => "test", "split_seed" => 999, "split_ratio" => 0.5 })++ output = Eval::Reporters::CascadeReport.new(bayes_run: bayes, provider_runs: [ provider ]).to_s++ assert_match(/WARNING/, output)+ assert_match(/different split/, output)+ end++ test "states the dataset-shape limitation in the output" do+ bayes = bayes_run(covered: { 0 => true }, declined: [ 1, 2, 3 ])++ output = Eval::Reporters::CascadeReport.new(bayes_run: bayes, provider_runs: []).to_s++ # A reader quoting the Bayes number needs to see why it is a lower bound.+ assert_match(/worst case/, output)+ assert_match(/understates/, output)+ end++ test "flags zero coverage as unmeasured rather than as a result" do+ # Measured on categorization_golden_v2: Bayes covers nothing, because a+ # golden set has ~one transaction per merchant and so no vocabulary to+ # generalize from. A reader must not carry that away as "Bayes classified+ # nothing".+ bayes = bayes_run(covered: {}, declined: [ 0, 1, 2, 3 ])+ report = Eval::Reporters::CascadeReport.new(bayes_run: bayes, provider_runs: [])++ assert report.degenerate_bayes?+ output = report.to_s+ assert_match(/DOES NOT MEASURE BAYES/, output)+ assert_match(/not as zero/, output)+ assert_no_match(/worst case/, output, "the softer caveat should be replaced, not appended")+ end++ test "reports cascade totals across both stages" do+ bayes = bayes_run(covered: { 0 => true, 1 => false }, declined: [ 2, 3 ])+ provider = provider_run("jev", correct_indexes: [ 2 ])++ output = Eval::Reporters::CascadeReport.new(bayes_run: bayes, provider_runs: [ provider ]).to_s++ # 1 correct from Bayes + 1 correct from the provider on the residual = 2/4.+ assert_match(%r{bayes \+ jev.*2 / 4}, output)+ end++ private+ def build_sample(hint)+ @dataset.samples.create!(+ difficulty: "medium",+ input_data: { "id" => hint, "description" => "TXN #{hint}", "amount" => 10 },+ expected_output: { "category_name" => "Groceries" },+ context_data: { "categories" => [ { "id" => "groceries", "name" => "Groceries" } ] }+ )+ end++ def bayes_run(covered:, declined:)+ run = Eval::Run.create!(+ dataset: @dataset, provider: "bayes", model: "naive-bayes", status: "pending",+ provider_config: { "split_role" => "test", "split_seed" => 42, "split_ratio" => 0.5 }+ )++ covered.each do |index, correct|+ run.results.create!(+ sample: @samples[index], actual_output: { "category_name" => "Groceries" },+ correct: correct, metadata: { "declined" => false, "confidence" => 0.9 }+ )+ end++ declined.each do |index|+ run.results.create!(+ sample: @samples[index], actual_output: { "category_name" => nil },+ correct: false, null_expected: @samples[index].expected_category_name.nil?,+ metadata: { "declined" => true }+ )+ end++ run+ end++ def provider_run(provider, correct_indexes:)+ run = Eval::Run.create!(+ dataset: @dataset, provider: provider, model: "~typesafe/jev-latest", status: "pending",+ provider_config: { "split_role" => "test", "split_seed" => 42, "split_ratio" => 0.5 }+ )++ @samples.each_with_index do |sample, index|+ run.results.create!(+ sample: sample, actual_output: { "category_name" => "Groceries" },+ correct: correct_indexes.include?(index)+ )+ end++ run+ end+enddiff --git a/test/models/eval/reporters/comparison_reporter_test.rb b/test/models/eval/reporters/comparison_reporter_test.rbnew file mode 100644index 0000000000..0493484f07--- /dev/null+++ b/test/models/eval/reporters/comparison_reporter_test.rb@@ -0,0 +1,115 @@+require "test_helper"+require "csv"++class Eval::Reporters::ComparisonReporterTest < ActiveSupport::TestCase+ setup do+ @dataset = Eval::Dataset.create!(+ name: "test_cmp_#{SecureRandom.hex(4)}",+ eval_type: "categorization",+ version: "1.0"+ )+ end++ def completed_run(provider:, model:, accuracy:, latency:, cost: 0.0)+ Eval::Run.create!(+ dataset: @dataset,+ provider: provider,+ model: model,+ name: "#{provider}_#{model}",+ status: "completed",+ metrics: { "accuracy" => accuracy, "avg_latency_ms" => latency },+ total_cost: cost,+ started_at: 1.minute.ago,+ completed_at: Time.current+ )+ end++ def jev_and_openai_runs+ [+ completed_run(provider: "jev", model: "~typesafe/jev-latest", accuracy: 96.0, latency: 71, cost: 0.0016),+ completed_run(provider: "openai", model: "gpt-4o-mini", accuracy: 91.0, latency: 240, cost: 0.0092)+ ]+ end++ test "the terminal table names the provider of each run" do+ table = Eval::Reporters::ComparisonReporter.new(jev_and_openai_runs).to_table++ assert_match(/Provider/, table)+ assert_match(/jev/, table)+ assert_match(/openai/, table)+ end++ test "distinguishes two providers serving the same model name" do+ runs = [+ completed_run(provider: "jev", model: "shared-model", accuracy: 96.0, latency: 71),+ completed_run(provider: "openai", model: "shared-model", accuracy: 80.0, latency: 240)+ ]++ summary = Eval::Reporters::ComparisonReporter.new(runs).summary++ # Keyed on model alone these two collide — the label is what tells them apart.+ assert_equal "jev:shared-model", summary[:best_accuracy][:label]+ assert_equal "jev", summary[:best_accuracy][:provider]+ assert_equal "shared-model", summary[:best_accuracy][:model]+ end++ test "summary carries provider alongside model for each category" do+ summary = Eval::Reporters::ComparisonReporter.new(jev_and_openai_runs).summary++ assert_equal "jev", summary[:best_accuracy][:provider]+ assert_equal "jev", summary[:lowest_cost][:provider]+ assert_equal "jev", summary[:fastest][:provider]+ assert_equal "jev:~typesafe/jev-latest", summary[:fastest][:label]+ end++ test "recommendation prose identifies a run by provider and model" do+ summary = Eval::Reporters::ComparisonReporter.new(jev_and_openai_runs).summary++ assert_match(/jev:~typesafe\/jev-latest/, summary[:recommendation])+ end++ test "pairwise comparisons carry provider-qualified labels" do+ comparison = Eval::Reporters::ComparisonReporter.new(jev_and_openai_runs).detailed_comparison+ pair = comparison[:comparison].sole++ assert_equal [ "jev:~typesafe/jev-latest", "openai:gpt-4o-mini" ], pair[:labels]+ assert_equal [ "~typesafe/jev-latest", "gpt-4o-mini" ], pair[:models]+ end++ test "runs are ordered by provider then model" do+ runs = [+ completed_run(provider: "openai", model: "gpt-4o-mini", accuracy: 91.0, latency: 240),+ completed_run(provider: "jev", model: "~typesafe/jev-latest", accuracy: 96.0, latency: 71)+ ]++ reporter = Eval::Reporters::ComparisonReporter.new(runs)++ assert_equal %w[jev openai], reporter.runs.map(&:provider)+ end++ test "csv output keeps its existing column set" do+ reporter = Eval::Reporters::ComparisonReporter.new(jev_and_openai_runs)++ Tempfile.create([ "comparison", ".csv" ]) do |file|+ reporter.to_csv(file.path)+ rows = CSV.read(file.path)++ assert_equal [+ "Run ID", "Model", "Provider", "Dataset", "Status",+ "Accuracy", "Precision", "Recall", "F1 Score",+ "Null Accuracy", "Hierarchical Accuracy",+ "Avg Latency (ms)", "Total Cost", "Cost Per Sample",+ "Samples Processed", "Samples Correct",+ "Duration (s)", "Run Date"+ ], rows.first+ assert_equal 3, rows.size+ end+ end++ test "returns an empty summary when nothing completed" do+ reporter = Eval::Reporters::ComparisonReporter.new([])++ assert_equal({}, reporter.summary)+ assert_equal "No runs to compare", reporter.to_table+ end+enddiff --git a/test/models/eval/reporters/disagreement_report_test.rb b/test/models/eval/reporters/disagreement_report_test.rbnew file mode 100644index 0000000000..5fba33a981--- /dev/null+++ b/test/models/eval/reporters/disagreement_report_test.rb@@ -0,0 +1,128 @@+require "test_helper"++class Eval::Reporters::DisagreementReportTest < ActiveSupport::TestCase+ setup do+ @dataset = Eval::Dataset.create!(+ name: "test_disagree_#{SecureRandom.hex(4)}",+ eval_type: "categorization",+ version: "1.0"+ )+ @baseline = run_for("openai", "gpt-4o")+ @candidate = run_for("jev", "jev-latest")+ @samples = []+ end++ def run_for(provider, model)+ Eval::Run.create!(+ dataset: @dataset, provider: provider, model: model,+ name: "#{provider}_#{model}", status: "completed"+ )+ end++ def sample!(description = "txn #{@samples.size}")+ @samples << @dataset.samples.create!(+ input_data: { "description" => description },+ expected_output: { "category_name" => "Coffee" },+ difficulty: "easy"+ )+ @samples.last+ end++ def answer(run, sample, category)+ run.results.create!(+ sample: sample,+ actual_output: { "category_name" => category },+ correct: category == "Coffee"+ )+ end++ # baseline answer, candidate answer — "Coffee" is correct+ def scenario(pairs)+ pairs.each do |base_answer, cand_answer|+ s = sample!+ answer(@baseline, s, base_answer)+ answer(@candidate, s, cand_answer)+ end+ Eval::Reporters::DisagreementReport.new(@baseline, @candidate)+ end++ test "splits paired results into wins, losses and shared failures" do+ report = scenario([+ [ "Coffee", "Coffee" ], # both correct+ [ "Rent", "Coffee" ], # candidate wins+ [ "Coffee", "Rent" ], # candidate loses+ [ "Rent", "Rent" ], # both wrong, same answer+ [ "Rent", "Travel" ] # both wrong, different answers+ ])++ assert report.comparable?+ assert_equal 5, report.paired_count+ assert_equal 1, report.both_correct.size+ assert_equal 1, report.candidate_wins.size+ assert_equal 1, report.candidate_losses.size+ assert_equal 1, report.both_wrong_same_answer.size+ assert_equal 1, report.both_wrong_different_answers.size+ end++ test "identical accuracy can still hide completely different error profiles" do+ # Both score 50%, but they fail on disjoint samples — the exact case two+ # accuracy percentages cannot distinguish.+ report = scenario([+ [ "Coffee", "Rent" ],+ [ "Rent", "Coffee" ]+ ])++ assert_equal 1, report.candidate_wins.size+ assert_equal 1, report.candidate_losses.size+ assert_equal 0, report.both_correct.size+ assert_equal 0.0, report.agreement_rate+ end++ test "agreement rate counts identical answers regardless of correctness" do+ report = scenario([+ [ "Coffee", "Coffee" ],+ [ "Rent", "Rent" ],+ [ "Rent", "Travel" ]+ ])++ assert_in_delta 66.67, report.agreement_rate, 0.01+ end++ test "surfaces the regressions a switch would buy" do+ report = scenario([ [ "Coffee", "Rent" ] ])++ example = report.to_h[:examples][:losses].sole+ assert_equal "txn 0", example[:sample]+ assert_equal({ "category_name" => "Coffee" }, example[:expected])+ assert_equal({ "category_name" => "Rent" }, example[:candidate])+ assert_match(/Regressions a switch would buy/, report.to_table)+ end++ test "runs over different datasets are not comparable" do+ other = Eval::Dataset.create!(+ name: "other_#{SecureRandom.hex(4)}", eval_type: "categorization", version: "1.0"+ )+ foreign = Eval::Run.create!(+ dataset: other, provider: "jev", model: "jev-latest", name: "foreign", status: "completed"+ )++ report = Eval::Reporters::DisagreementReport.new(@baseline, foreign)++ assert_not report.comparable?+ assert_equal({ comparable: false }, report.to_h)+ assert_match(/not comparable/, report.to_table)+ end++ test "only pairs samples both runs actually answered" do+ shared = sample!+ answer(@baseline, shared, "Coffee")+ answer(@candidate, shared, "Coffee")++ baseline_only = sample!+ answer(@baseline, baseline_only, "Coffee")++ report = Eval::Reporters::DisagreementReport.new(@baseline, @candidate)++ assert_equal 1, report.paired_count+ end+enddiff --git a/test/models/eval/reporters/recommendation_test.rb b/test/models/eval/reporters/recommendation_test.rbnew file mode 100644index 0000000000..20cd4cccaa--- /dev/null+++ b/test/models/eval/reporters/recommendation_test.rb@@ -0,0 +1,173 @@+require "test_helper"++class Eval::Reporters::RecommendationTest < ActiveSupport::TestCase+ setup do+ @dataset = Eval::Dataset.create!(+ name: "test_rec_#{SecureRandom.hex(4)}",+ eval_type: "categorization",+ version: "1.0"+ )+ @sample_count = 0+ end++ def run_for(provider, model, metrics: {}, status: "completed")+ Eval::Run.create!(+ dataset: @dataset, provider: provider, model: model,+ name: "#{provider}_#{model}_#{SecureRandom.hex(2)}",+ status: status, metrics: metrics+ )+ end++ # Builds `wins` samples the candidate alone got right, `losses` the baseline+ # alone got right, and `agreed` both got right.+ def outcome(baseline, candidate, wins:, losses:, agreed:)+ add = lambda do |base_ok, cand_ok, count|+ count.times do+ sample = @dataset.samples.create!(+ input_data: { "description" => "txn #{@sample_count += 1}" },+ expected_output: { "category_name" => "Coffee" },+ difficulty: "easy"+ )+ baseline.results.create!(sample: sample, correct: base_ok,+ actual_output: { "category_name" => base_ok ? "Coffee" : "Rent" })+ candidate.results.create!(sample: sample, correct: cand_ok,+ actual_output: { "category_name" => cand_ok ? "Coffee" : "Travel" })+ end+ end++ add.call(false, true, wins)+ add.call(true, false, losses)+ add.call(true, true, agreed)+ end++ def recommend(baseline, candidate)+ Eval::Reporters::Recommendation.new(baseline: baseline, candidate: candidate)+ end++ test "a two-sample accuracy edge over 200 samples is reported as a tie" do+ # The real measurement: Jev 192/200, claude-sonnet-5 190/200. Calling that a+ # win would be actively misleading, so the verdict must not be "replace".+ baseline = run_for("openai", "claude-sonnet-5", metrics: { "avg_latency_ms" => 1241 })+ candidate = run_for("jev", "jev-latest", metrics: { "avg_latency_ms" => 78 })+ outcome(baseline, candidate, wins: 6, losses: 4, agreed: 186)++ result = recommend(baseline, candidate).to_h++ assert_not_equal "replace", result[:verdict]+ assert result[:p_value] > 0.05, "6 wins against 4 losses is noise, not signal"+ assert_match(/statistically indistinguishable/, result[:reasons].join(" "))+ end++ test "a tie plus a large speed advantage is worth shadowing" do+ baseline = run_for("openai", "claude-sonnet-5", metrics: { "avg_latency_ms" => 1241 })+ candidate = run_for("jev", "jev-latest", metrics: { "avg_latency_ms" => 78 })+ outcome(baseline, candidate, wins: 6, losses: 4, agreed: 186)++ result = recommend(baseline, candidate).to_h++ assert_equal "shadow", result[:verdict]+ assert_match(/15\.9x faster/, result[:reasons].join(" "))+ end++ test "a tie with no other advantage is not worth switching to" do+ baseline = run_for("openai", "gpt-4o", metrics: { "avg_latency_ms" => 100 })+ candidate = run_for("jev", "jev-latest", metrics: { "avg_latency_ms" => 95 })+ outcome(baseline, candidate, wins: 5, losses: 5, agreed: 90)++ result = recommend(baseline, candidate).to_h++ assert_equal "skip", result[:verdict]+ assert_match(/no measurable advantage/, result[:reasons].join(" "))+ end++ test "replace requires strong evidence and enough samples" do+ baseline = run_for("openai", "gpt-4o", metrics: { "avg_latency_ms" => 300 })+ candidate = run_for("jev", "jev-latest", metrics: { "avg_latency_ms" => 80 })+ outcome(baseline, candidate, wins: 20, losses: 2, agreed: 78)++ result = recommend(baseline, candidate).to_h++ assert_equal "replace", result[:verdict]+ assert result[:p_value] < 0.01+ end++ test "the same strong advantage on a small sample only earns a shadow" do+ baseline = run_for("openai", "gpt-4o", metrics: { "avg_latency_ms" => 300 })+ candidate = run_for("jev", "jev-latest", metrics: { "avg_latency_ms" => 80 })+ outcome(baseline, candidate, wins: 20, losses: 2, agreed: 38)++ result = recommend(baseline, candidate).to_h++ assert_equal "shadow", result[:verdict]+ assert_match(/thin/, result[:reasons].join(" "))+ end++ test "a significantly worse candidate is skipped" do+ baseline = run_for("openai", "gpt-4o", metrics: { "avg_latency_ms" => 300 })+ candidate = run_for("jev", "jev-latest", metrics: { "avg_latency_ms" => 80 })+ outcome(baseline, candidate, wins: 2, losses: 20, agreed: 78)++ result = recommend(baseline, candidate).to_h++ assert_equal "skip", result[:verdict]+ assert_match(/significantly worse/, result[:reasons].join(" "))+ end++ test "an errored run is rejected rather than scored" do+ # A dead model slug records every sample as incorrect, which would otherwise+ # read as a real 0% rather than a broken measurement.+ baseline = run_for("openai", "gpt-4o")+ candidate = run_for("jev", "jev-latest", metrics: { "samples_errored" => 50 })+ outcome(baseline, candidate, wins: 0, losses: 50, agreed: 50)++ result = recommend(baseline, candidate).to_h++ assert_equal "skip", result[:verdict]+ assert_match(/errored/, result[:reasons].join(" "))+ end++ test "too few samples yields shadow rather than a verdict either way" do+ baseline = run_for("openai", "gpt-4o")+ candidate = run_for("jev", "jev-latest")+ outcome(baseline, candidate, wins: 5, losses: 0, agreed: 5)++ result = recommend(baseline, candidate).to_h++ assert_equal "shadow", result[:verdict]+ assert_match(/too few to judge/, result[:reasons].join(" "))+ end++ test "one-sided cost instrumentation is stated, never read as free" do+ baseline = run_for("openai", "gpt-4o", metrics: { "avg_latency_ms" => 100 })+ candidate = run_for("jev", "jev-latest", metrics: { "avg_latency_ms" => 95 })+ outcome(baseline, candidate, wins: 5, losses: 5, agreed: 90)+ candidate.results.update_all(cost: 0.000031)++ reasons = recommend(baseline, candidate).to_h[:reasons].join(" ")++ assert_match(/cost comparison unavailable/, reasons)+ assert_match(/baseline records none/, reasons)+ end++ test "an incomplete run is not scored" do+ baseline = run_for("openai", "gpt-4o")+ candidate = run_for("jev", "jev-latest", status: "failed")+ outcome(baseline, candidate, wins: 5, losses: 5, agreed: 90)++ result = recommend(baseline, candidate).to_h++ assert_equal "skip", result[:verdict]+ assert_match(/did not complete/, result[:reasons].join(" "))+ end++ test "identical answers throughout produce no signal" do+ baseline = run_for("openai", "gpt-4o", metrics: { "avg_latency_ms" => 100 })+ candidate = run_for("jev", "jev-latest", metrics: { "avg_latency_ms" => 100 })+ outcome(baseline, candidate, wins: 0, losses: 0, agreed: 100)++ result = recommend(baseline, candidate).to_h++ assert_equal 1.0, result[:p_value]+ assert_equal "skip", result[:verdict]+ end+enddiff --git a/test/models/eval/runners/sample_split_test.rb b/test/models/eval/runners/sample_split_test.rbnew file mode 100644index 0000000000..f61b95bb38--- /dev/null+++ b/test/models/eval/runners/sample_split_test.rb@@ -0,0 +1,98 @@+require "test_helper"++class Eval::Runners::SampleSplitTest < ActiveSupport::TestCase+ setup do+ @dataset = Eval::Dataset.create!(+ name: "split_test_#{SecureRandom.hex(4)}",+ eval_type: "categorization",+ version: "1.0"+ )+ end++ test "keeps every null-expected sample out of training" do+ 4.times { |i| sample(difficulty: "easy", category: "Groceries", id_hint: "e#{i}") }+ 3.times { |i| sample(difficulty: "edge_case", category: nil, id_hint: "n#{i}") }++ split = Eval::Runners::SampleSplit.new(@dataset.samples)++ assert split.train.all? { |s| s.expected_category_name.present? },+ "Bayes trains on categorized transactions only, so a null-expected sample cannot train"+ assert_equal 3, split.test.count { |s| s.expected_category_name.nil? }+ end++ test "stratifies the categorized samples by difficulty" do+ 6.times { |i| sample(difficulty: "easy", category: "Groceries", id_hint: "e#{i}") }+ 6.times { |i| sample(difficulty: "hard", category: "Shopping", id_hint: "h#{i}") }++ split = Eval::Runners::SampleSplit.new(@dataset.samples, train_ratio: 0.5)++ # Without stratification a seeded shuffle could hand training every easy+ # sample and leave a uniformly hard test set.+ assert_equal 3, split.train.count { |s| s.difficulty == "easy" }+ assert_equal 3, split.train.count { |s| s.difficulty == "hard" }+ end++ test "is deterministic for a given seed and differs across seeds" do+ 10.times { |i| sample(difficulty: "easy", category: "Groceries", id_hint: "e#{i}") }++ first = Eval::Runners::SampleSplit.new(@dataset.samples, seed: 42).train.map(&:id)+ again = Eval::Runners::SampleSplit.new(@dataset.samples, seed: 42).train.map(&:id)+ other = Eval::Runners::SampleSplit.new(@dataset.samples, seed: 7).train.map(&:id)++ assert_equal first, again, "same seed must reproduce the split so legs stay comparable"+ assert_not_equal first, other+ end++ test "train and test partition the dataset without overlap" do+ 8.times { |i| sample(difficulty: "medium", category: "Groceries", id_hint: "m#{i}") }+ 2.times { |i| sample(difficulty: "edge_case", category: nil, id_hint: "n#{i}") }++ split = Eval::Runners::SampleSplit.new(@dataset.samples)++ assert_empty split.train.map(&:id) & split.test.map(&:id)+ assert_equal @dataset.samples.count, split.train.size + split.test.size+ end++ test "describe reports the composition the test set actually has" do+ 6.times { |i| sample(difficulty: "easy", category: "Groceries", id_hint: "e#{i}") }+ 4.times { |i| sample(difficulty: "edge_case", category: nil, id_hint: "n#{i}") }++ describe = Eval::Runners::SampleSplit.new(@dataset.samples, train_ratio: 0.5).describe++ assert_equal 3, describe["train_size"]+ assert_equal 7, describe["test_size"]+ assert_equal 4, describe["test_null_expected"]+ end++ test "rejects an unknown role" do+ assert_raises(ArgumentError) { Eval::Runners::SampleSplit.new(@dataset.samples).for_role("holdout") }+ end++ # Guards against String#hash, which Ruby seeds per process: the split has to+ # be identical in the Bayes leg and the provider leg of a cascade run, and+ # those are separate `rake evals:run` processes. A single-process test cannot+ # observe that drift, and the selection itself cannot be pinned because the+ # shuffle orders by sample id, which is a random UUID per run. So the pin goes+ # on the offset — hardcoded values a per-process hash could never reproduce.+ test "derives the difficulty offset from a stable digest" do+ split = Eval::Runners::SampleSplit.new(@dataset.samples)++ assert_equal 3981731257, split.send(:difficulty_offset, "hard")+ assert_equal 2546011902, split.send(:difficulty_offset, "easy")+ assert_equal 3229762922, split.send(:difficulty_offset, "medium")+ assert_equal 3334581, split.send(:difficulty_offset, "edge_case")+ # Samples with no difficulty still have to land somewhere deterministic.+ assert_equal 3820012610, split.send(:difficulty_offset, nil)+ end+++ private+ def sample(difficulty:, category:, id_hint:)+ @dataset.samples.create!(+ difficulty: difficulty,+ input_data: { "id" => id_hint, "description" => "TXN #{id_hint}", "amount" => 10 },+ expected_output: { "category_name" => category },+ context_data: { "categories" => [ { "id" => "groceries", "name" => "Groceries" } ] }+ )+ end+enddiff --git a/test/models/family/auto_categorizer_test.rb b/test/models/family/auto_categorizer_test.rbindex ce6314828e..915dcd206f 100644--- a/test/models/family/auto_categorizer_test.rb+++ b/test/models/family/auto_categorizer_test.rb@@ -155,6 +155,365 @@ class Family::AutoCategorizerTest < ActiveSupport::TestCaseassert_equal [ llm_txn.id ], ai_entry.metadata["categorized_transaction_ids"]end+ # Jev runs only when the family has chosen it AND credentials are configured.+ # The choice is a family column, not the preview flag: preview gates whether+ # the selector is offered (see docs/llm-guides/gating-a-preview-feature.md),+ # never what gets used. Every other install keeps the LLM path.++ test "uses the LLM provider by default" do+ txn = create_transaction(account: @account, name: "Coffee shop").transaction+ category = @family.categories.create!(name: "Coffee")++ assert_equal "llm", @family.categorization_provider+ # Not even looked up: the choice short-circuits before the registry.+ Provider::Registry.expects(:get_provider).with(:jev).never+ @llm_provider.expects(:auto_categorize).returns(provider_success_response([+ AutoCategorization.new(transaction_id: txn.id, category_name: category.name)+ ])).once++ Family::AutoCategorizer.new(@family, transaction_ids: [ txn.id ]).auto_categorize++ assert_equal category, txn.reload.category+ end++ test "uses Jev when the family selects it and it is configured" do+ @family.update!(categorization_provider: "jev")+ txn = create_transaction(account: @account, name: "Blue Bottle Coffee").transaction+ category = @family.categories.create!(name: "Coffee")++ # A real instance, not a bare mock: DebugLogEntry derives provider_key from+ # the class name, so a Mocha::Mock would log "mock".+ jev = Provider::Jev.allocate+ Provider::Registry.stubs(:get_provider).with(:jev).returns(jev)+ @llm_provider.expects(:auto_categorize).never+ jev.expects(:auto_categorize).returns(provider_success_response([+ CategoryDecision.new(+ transaction_id: txn.id,+ category_name: category.name,+ confidence: 0.97,+ probabilities: { category.name => 0.97 },+ usage: { "cost" => 0.000032 }+ )+ ])).once++ Family::AutoCategorizer.new(@family, transaction_ids: [ txn.id ]).auto_categorize++ # The richer struct maps back through the same loop as the LLM shape.+ assert_equal category, txn.reload.category+ assert_equal "jev", DebugLogEntry.order(:created_at).last.provider_key+ end++ test "falls back to the LLM provider when Jev is selected but has no credentials" do+ @family.update!(categorization_provider: "jev")+ txn = create_transaction(account: @account, name: "Coffee shop").transaction+ category = @family.categories.create!(name: "Coffee")++ Provider::Registry.stubs(:get_provider).with(:jev).returns(nil)+ @llm_provider.expects(:auto_categorize).returns(provider_success_response([+ AutoCategorization.new(transaction_id: txn.id, category_name: category.name)+ ])).once++ Family::AutoCategorizer.new(@family, transaction_ids: [ txn.id ]).auto_categorize++ assert_equal category, txn.reload.category+ end++ test "logs the rejected Jev endpoint only when categorization actually runs" do+ @family.update!(categorization_provider: "jev")+ txn = create_transaction(account: @account, name: "Coffee shop").transaction+ category = @family.categories.create!(name: "Coffee")++ @llm_provider.expects(:auto_categorize).returns(provider_success_response([+ AutoCategorization.new(transaction_id: txn.id, category_name: category.name)+ ])).once++ with_env_overrides(+ "JEV_API_KEY" => "test_api_key",+ "JEV_ENDPOINT" => "http://someone:[email protected]/v1?api_key=QUERYSECRET#frag" # pipelock:ignore Credential in URL+ ) do+ assert_difference "DebugLogEntry.count", 2 do+ Family::AutoCategorizer.new(@family, transaction_ids: [ txn.id ]).auto_categorize+ end+ end++ entry = DebugLogEntry.where(message: "Jev is misconfigured; falling back to the LLM provider").sole+ assert_equal "auto_categorization", entry.category+ assert_equal "error", entry.level+ assert_equal "jev", entry.provider_key+ assert_equal @family, entry.family+ assert_equal "http://gw.example.com/v1", entry.metadata["endpoint"]+ assert_equal "Provider::Jev::Error", entry.metadata["error_class"]++ # error_message embeds the endpoint the constructor rejected, so it leaks+ # just as readily as the endpoint field if it is not redacted at the raise.+ serialized = entry.metadata.to_json+ assert_not_includes serialized, "s3cret"+ assert_not_includes serialized, "QUERYSECRET"+ assert_not_includes serialized, "frag"+ end++ # Confidence has to change behaviour, not just appear in logs. Below the+ # threshold the answer is withheld and the transaction is left unlocked, so a+ # later run can still correct it.++ test "withholds a classification answer that carries no confidence at all" do+ # Previously the gate returned false on a nil confidence, which was there to+ # avoid gating the LLM providers. That also let a malformed classification+ # answer through — the one case where withholding matters most, since we+ # have no idea how good it is.+ @family.update!(categorization_confidence_threshold: 0.7)+ txn = create_transaction(account: @account, name: "Ambiguous thing").transaction+ category = @family.categories.create!(name: "Coffee")++ jev_returning(txn, category, confidence: nil)++ Family::AutoCategorizer.new(@family, transaction_ids: [ txn.id ]).auto_categorize++ assert_nil txn.reload.category+ assert_includes @account.transactions.reload.enrichable(:category_id), txn+ end++ test "applies every answer when the threshold is zero" do+ # Set explicitly rather than leaning on the column default, which is 0.7 —+ # this test is about the zero-threshold behaviour, not about what ships.+ @family.update!(categorization_confidence_threshold: 0)+ txn = create_transaction(account: @account, name: "Ambiguous thing").transaction+ category = @family.categories.create!(name: "Coffee")++ assert_equal 0.0, @family.effective_categorization_confidence_threshold+ jev_returning(txn, category, confidence: 0.12)++ Family::AutoCategorizer.new(@family, transaction_ids: [ txn.id ]).auto_categorize++ assert_equal category, txn.reload.category+ end++ test "withholds an answer below the confidence threshold and leaves it retryable" do+ @family.update!(categorization_confidence_threshold: 0.7)+ txn = create_transaction(account: @account, name: "Ambiguous thing").transaction+ category = @family.categories.create!(name: "Coffee")++ jev_returning(txn, category, confidence: 0.52)++ assert_no_difference "DataEnrichment.count" do+ Family::AutoCategorizer.new(@family, transaction_ids: [ txn.id ]).auto_categorize+ end++ assert_nil txn.reload.category+ # Unlocked, so it stays eligible for a later attempt.+ assert_includes @account.transactions.reload.enrichable(:category_id), txn++ entry = DebugLogEntry.order(:created_at).last+ withheld = entry.metadata["withheld_low_confidence"].sole+ assert_equal txn.id, withheld["transaction_id"]+ assert_in_delta 0.52, withheld["confidence"], 0.001+ end++ test "applies an answer at or above the confidence threshold" do+ @family.update!(categorization_confidence_threshold: 0.7)+ txn = create_transaction(account: @account, name: "Blue Bottle Coffee").transaction+ category = @family.categories.create!(name: "Coffee")++ jev_returning(txn, category, confidence: 0.97)++ Family::AutoCategorizer.new(@family, transaction_ids: [ txn.id ]).auto_categorize++ assert_equal category, txn.reload.category+ end++ test "a threshold never suppresses a provider that reports no confidence" do+ # The LLM providers return a bare category name. Gating them on a confidence+ # they cannot produce would silently stop categorizing altogether.+ @family.update!(categorization_confidence_threshold: 0.9)+ txn = create_transaction(account: @account, name: "Coffee shop").transaction+ category = @family.categories.create!(name: "Coffee")++ @llm_provider.expects(:auto_categorize).returns(provider_success_response([+ AutoCategorization.new(transaction_id: txn.id, category_name: category.name)+ ])).once++ Family::AutoCategorizer.new(@family, transaction_ids: [ txn.id ]).auto_categorize++ assert_equal category, txn.reload.category+ end++ # Shadow mode runs the provider that is NOT in use and records the comparison+ # without applying any of its answers.++ test "does not run a shadow provider by default" do+ txn = create_transaction(account: @account, name: "Coffee shop").transaction+ category = @family.categories.create!(name: "Coffee")++ assert_equal 0.0, @family.effective_categorization_shadow_rate+ Provider::Registry.expects(:get_provider).with(:jev).never+ @llm_provider.expects(:auto_categorize).returns(provider_success_response([+ AutoCategorization.new(transaction_id: txn.id, category_name: category.name)+ ])).once++ assert_no_difference "CategorizationComparison.count" do+ Family::AutoCategorizer.new(@family, transaction_ids: [ txn.id ]).auto_categorize+ end+ end++ test "records a disagreement without applying the shadow answer" do+ @family.update!(categorization_shadow_rate: 1.0)+ txn = create_transaction(account: @account, name: "Blue Bottle Coffee").transaction+ applied = @family.categories.create!(name: "Coffee")+ shadowed = @family.categories.create!(name: "Groceries")++ # Real instances, not bare mocks: the comparison records each provider by+ # its class name, and a Mocha::Mock would be stored as "mock".+ openai = Provider::Openai.allocate+ Provider::Registry.stubs(:preferred_llm_provider).returns(openai)+ openai.expects(:auto_categorize).returns(provider_success_response([+ AutoCategorization.new(transaction_id: txn.id, category_name: applied.name)+ ])).once++ jev = Provider::Jev.allocate+ Provider::Registry.stubs(:get_provider).with(:jev).returns(jev)+ jev.expects(:auto_categorize).returns(provider_success_response([+ CategoryDecision.new(+ transaction_id: txn.id,+ category_name: shadowed.name,+ confidence: 0.88,+ probabilities: { shadowed.name => 0.88 },+ usage: { "cost" => 0.000032 }+ )+ ])).once++ assert_difference "CategorizationComparison.count", 1 do+ Family::AutoCategorizer.new(@family, transaction_ids: [ txn.id ]).auto_categorize+ end++ # The incumbent's answer is the one that lands.+ assert_equal applied, txn.reload.category++ comparison = CategorizationComparison.order(:created_at).last+ assert_not comparison.agreed+ assert_equal "openai", comparison.applied_provider+ assert_equal "jev", comparison.shadow_provider+ assert_equal applied.name, comparison.applied_category_name+ assert_equal shadowed.name, comparison.shadow_category_name+ assert_in_delta 0.88, comparison.shadow_confidence, 0.001+ end++ test "does not score a missing shadow answer as agreement" do+ # The comparison rows come from the union of both providers' decisions, so+ # one side can be absent entirely. When the other side abstained, both+ # category names are nil — and comparing them directly recorded that as+ # agreement, inflating the rate with rows where nobody agreed on anything.+ @family.update!(categorization_shadow_rate: 1.0)+ txn = create_transaction(account: @account, name: "ACH DEBIT 4471920").transaction+ @family.categories.create!(name: "Coffee")++ openai = Provider::Openai.allocate+ Provider::Registry.stubs(:preferred_llm_provider).returns(openai)+ # Answered, but declined to pick a category.+ openai.expects(:auto_categorize).returns(provider_success_response([+ AutoCategorization.new(transaction_id: txn.id, category_name: nil)+ ])).once++ jev = Provider::Jev.allocate+ Provider::Registry.stubs(:get_provider).with(:jev).returns(jev)+ # Returned no decision for this transaction at all.+ jev.expects(:auto_categorize).returns(provider_success_response([])).once++ assert_difference "CategorizationComparison.count", 1 do+ Family::AutoCategorizer.new(@family, transaction_ids: [ txn.id ]).auto_categorize+ end++ comparison = CategorizationComparison.order(:created_at).last+ assert_not comparison.agreed+ assert_nil comparison.shadow_category_name+ end++ test "counts a shared abstention as agreement" do+ # The other half of the rule: both providers answering "no category" is a+ # real agreement, and must not be swept up by the fix above.+ @family.update!(categorization_shadow_rate: 1.0)+ txn = create_transaction(account: @account, name: "ACH DEBIT 4471920").transaction+ @family.categories.create!(name: "Coffee")++ openai = Provider::Openai.allocate+ Provider::Registry.stubs(:preferred_llm_provider).returns(openai)+ openai.expects(:auto_categorize).returns(provider_success_response([+ AutoCategorization.new(transaction_id: txn.id, category_name: nil)+ ])).once++ jev = Provider::Jev.allocate+ Provider::Registry.stubs(:get_provider).with(:jev).returns(jev)+ jev.expects(:auto_categorize).returns(provider_success_response([+ CategoryDecision.new(+ transaction_id: txn.id,+ category_name: nil,+ confidence: 0.94,+ probabilities: {},+ usage: {}+ )+ ])).once++ Family::AutoCategorizer.new(@family, transaction_ids: [ txn.id ]).auto_categorize++ assert CategorizationComparison.order(:created_at).last.agreed+ end++ test "a failing shadow provider does not break the run it observes" do+ @family.update!(categorization_shadow_rate: 1.0)+ txn = create_transaction(account: @account, name: "Coffee shop").transaction+ category = @family.categories.create!(name: "Coffee")++ @llm_provider.expects(:auto_categorize).returns(provider_success_response([+ AutoCategorization.new(transaction_id: txn.id, category_name: category.name)+ ])).once++ jev = Provider::Jev.allocate+ Provider::Registry.stubs(:get_provider).with(:jev).returns(jev)+ jev.expects(:auto_categorize).raises(Provider::Jev::Error.new("upstream down"))++ assert_nothing_raised do+ Family::AutoCategorizer.new(@family, transaction_ids: [ txn.id ]).auto_categorize+ end++ assert_equal category, txn.reload.category+ assert_equal 0, CategorizationComparison.count+ end++ test "logs a rejected Jev endpoint when it was due to shadow the run" do+ @family.update!(categorization_provider: "llm", categorization_shadow_rate: 1.0)+ txn = create_transaction(account: @account, name: "Coffee shop").transaction+ category = @family.categories.create!(name: "Coffee")++ @llm_provider.expects(:auto_categorize).returns(provider_success_response([+ AutoCategorization.new(transaction_id: txn.id, category_name: category.name)+ ])).once++ with_env_overrides("JEV_API_KEY" => "test_api_key", "JEV_ENDPOINT" => "http://gw.example.com/v1") do+ Family::AutoCategorizer.new(@family, transaction_ids: [ txn.id ]).auto_categorize+ end++ entry = DebugLogEntry.where(message: "Jev is misconfigured; skipping the shadow comparison").sole+ assert_equal "Provider::Jev::Error", entry.metadata["error_class"]+ assert_equal category, txn.reload.category+ end+privateAutoCategorization = Provider::LlmConcept::AutoCategorization+ CategoryDecision = Provider::ClassificationConcept::CategoryDecision++ # Puts the family on Jev and has it return one decision at a given confidence.+ def jev_returning(transaction, category, confidence:)+ @family.update!(categorization_provider: "jev")+ jev = Provider::Jev.allocate+ Provider::Registry.stubs(:get_provider).with(:jev).returns(jev)+ jev.expects(:auto_categorize).returns(provider_success_response([+ CategoryDecision.new(+ transaction_id: transaction.id,+ category_name: category.name,+ confidence: confidence,+ probabilities: { category.name => confidence },+ usage: { "cost" => 0.000032 }+ )+ ])).once+ jev+ endenddiff --git a/test/models/family_test.rb b/test/models/family_test.rbindex bfe6b8df2b..06766f047b 100644--- a/test/models/family_test.rb+++ b/test/models/family_test.rb@@ -509,6 +509,109 @@ class FamilyTest < ActiveSupport::TestCaseassert_nil family.request_plaid_transactions_refreshes_later(source: "TestSync")end+ # A non-loopback http:// endpoint is the misconfiguration these guard: the+ # settings form rejects it, but JEV_ENDPOINT never passes through the form.+ # Marked for the secret scanner: a redaction test has to hold the shape it+ # redacts. The host and secrets are fake.+ CREDENTIALED_JEV_ENDPOINT = "http://someone:[email protected]/v1?api_key=QUERYSECRET#frag" # pipelock:ignore Credential in URL++ REJECTED_JEV_ENV = {+ "JEV_API_KEY" => "test_api_key",+ "JEV_ENDPOINT" => "http://internal-gateway.example.com/v1/systemone"+ }.freeze++ test "resolved_categorization_provider builds Jev when the endpoint is allowed" do+ family = families(:dylan_family)+ family.update!(categorization_provider: "jev")++ with_env_overrides("JEV_API_KEY" => "test_api_key", "JEV_ENDPOINT" => "https://api.typesafe.ai/v1/systemone") do+ assert_instance_of Provider::Jev, family.resolved_categorization_provider+ end+ end++ test "categorization_model_name names the Jev model when Jev will categorize" do+ family = families(:dylan_family)+ family.stubs(:resolved_categorization_provider).returns(Provider::Jev.allocate)+ Provider::Jev.stubs(:effective_model).returns("~typesafe/jev-latest")++ assert_equal "~typesafe/jev-latest", family.categorization_model_name+ end++ test "categorization_model_name names the Anthropic model when Anthropic will categorize" do+ family = families(:dylan_family)+ family.stubs(:resolved_categorization_provider).returns(Provider::Anthropic.allocate)+ Provider::Anthropic.stubs(:effective_model).returns("claude-sonnet-test")++ assert_equal "claude-sonnet-test", family.categorization_model_name+ end++ test "resolved_categorization_provider falls back to the LLM provider when the endpoint is rejected" do+ family = families(:dylan_family)+ family.update!(categorization_provider: "jev")+ llm = Provider::Openai.allocate+ Provider::Registry.stubs(:preferred_llm_provider).returns(llm)++ with_env_overrides(REJECTED_JEV_ENV) do+ assert_same llm, family.resolved_categorization_provider+ end+ end++ test "resolved_categorization_provider does not write diagnostics from view-time callers" do+ family = families(:dylan_family)+ family.update!(categorization_provider: "jev")+ Provider::Registry.stubs(:preferred_llm_provider).returns(nil)++ assert_no_difference "DebugLogEntry.count" do+ with_env_overrides(REJECTED_JEV_ENV) do+ assert_nil family.resolved_categorization_provider+ end+ end+ end++ test "categorization_model_name does not write diagnostics from view-time callers" do+ family = families(:dylan_family)+ family.update!(categorization_provider: "jev")+ Provider::Registry.stubs(:preferred_llm_provider).returns(nil)++ assert_no_difference "DebugLogEntry.count" do+ with_env_overrides(REJECTED_JEV_ENV) do+ assert_nil family.categorization_model_name+ end+ end+ end++ test "shadow_categorization_provider returns nil when the Jev endpoint is rejected" do+ family = families(:dylan_family)+ family.update!(categorization_provider: "llm")++ with_env_overrides(REJECTED_JEV_ENV) do+ assert_nil family.shadow_categorization_provider+ end+ end++ test "resolved_categorization_provider hands the construction error to a caller that asks" do+ family = families(:dylan_family)+ family.update!(categorization_provider: "jev")+ Provider::Registry.stubs(:preferred_llm_provider).returns(nil)+ errors = []++ with_env_overrides(REJECTED_JEV_ENV) do+ assert_nil family.resolved_categorization_provider { |error| errors << error }+ end++ assert_equal [ Provider::Jev::Error ], errors.map(&:class)+ end++ # The rescue is deliberately narrow, so a registry bug still surfaces rather+ # than being reported to the operator as a Jev misconfiguration.+ test "resolved_categorization_provider does not swallow non-provider errors" do+ family = families(:dylan_family)+ family.update!(categorization_provider: "jev")+ Provider::Registry.stubs(:get_provider).with(:jev).raises(ArgumentError, "boom")++ assert_raises(ArgumentError) { family.resolved_categorization_provider }+ end+privatedef set_preview_features(user, enabled)user.update!(preferences: (user.preferences || {}).merge("preview_features_enabled" => enabled))diff --git a/test/models/provider/jev_test.rb b/test/models/provider/jev_test.rbnew file mode 100644index 0000000000..0a0a5bdf4e--- /dev/null+++ b/test/models/provider/jev_test.rb@@ -0,0 +1,444 @@+require "test_helper"++class Provider::JevTest < ActiveSupport::TestCase+ ENDPOINT = "https://api.typesafe.ai/v1/systemone".freeze++ setup do+ @provider = Provider::Jev.new("test_api_key")+ end++ def choice_body(choice:, confidence: 0.9, probabilities: nil, key: "category")+ {+ "model" => "typesafe/jev-1.13-20260917",+ "answers" => {+ key => {+ "type" => "choice",+ "choice" => choice,+ "probabilities" => probabilities || { choice => confidence },+ "confidence" => confidence+ }+ },+ "usage" => { "input_tokens" => 400, "output_tokens" => 60, "cost" => 0.00002 }+ }.to_json+ end++ def categories+ [+ { id: "1", name: "Groceries", parent_id: nil },+ { id: "2", name: "Restaurants & Bars", parent_id: nil },+ { id: "3", name: "Coffee", parent_id: "2" }+ ]+ end++ def transaction(id: "t1", description: "SQ *BLUE BOTTLE COFFEE", merchant: nil)+ { id: id, description: description, amount: 6.75, classification: "expense", merchant: merchant }+ end++ # Fake gateway URLs carrying a secret in userinfo and in the query. Marked for+ # the secret scanner because a redaction test cannot avoid holding the shape+ # it redacts.+ CREDENTIALED = "https://someone:[email protected]/v1?api_key=QUERYSECRET#frag" # pipelock:ignore Credential in URL+ CREDENTIALED_HTTP = "http://someone:[email protected]/v1?api_key=QUERYSECRET" # pipelock:ignore Credential in URL+ USERINFO_ONLY = "https://[email protected]/v1" # pipelock:ignore Credential in URL++ test "redacted_endpoint strips userinfo, query and fragment" do+ assert_equal "https://gw.example.com/v1", Provider::Jev.redacted_endpoint(CREDENTIALED)+ assert_equal "https://gw.example.com/v1", Provider::Jev.redacted_endpoint(USERINFO_ONLY)+ assert_equal ENDPOINT, Provider::Jev.redacted_endpoint(ENDPOINT)+ end++ test "redacted_endpoint does not raise on an unparseable endpoint" do+ assert_equal "[unparseable endpoint]", Provider::Jev.redacted_endpoint("not a url")+ assert_equal "", Provider::Jev.redacted_endpoint(nil)+ end++ # The constructor's message reaches Rails logs and DebugLogEntry, so the+ # endpoint it names must already be redacted.+ test "the rejected-endpoint error names the endpoint without its credentials" do+ error = assert_raises(Provider::Jev::Error) do+ Provider::Jev.new("test_api_key", endpoint: CREDENTIALED_HTTP)+ end++ assert_includes error.message, "http://gw.example.com/v1"+ assert_not_includes error.message, "s3cret"+ assert_not_includes error.message, "QUERYSECRET"+ end++ test "categorizes a transaction and carries the reported confidence" do+ stub_request(:post, ENDPOINT).to_return(+ status: 200,+ body: choice_body(choice: "Coffee", confidence: 0.97),+ headers: { "Content-Type" => "application/json" }+ )++ response = @provider.auto_categorize(transactions: [ transaction ], user_categories: categories)++ assert response.success?+ decision = response.data.sole+ assert_equal "t1", decision.transaction_id+ assert_equal "Coffee", decision.category_name+ assert_in_delta 0.97, decision.confidence, 0.001+ end++ test "attributes per-request usage to each categorized transaction" do+ stub_request(:post, ENDPOINT).to_return(+ status: 200,+ body: choice_body(choice: "Groceries"),+ headers: { "Content-Type" => "application/json" }+ )++ response = @provider.auto_categorize(transactions: [ transaction ], user_categories: categories)++ # One request per transaction means cost is attributable per sample, which+ # is what lets the eval report a real cost-per-sample figure.+ usage = response.data.sole.usage+ assert_equal 0.00002, usage["cost"]+ assert_equal 400, usage["input_tokens"]+ assert_equal 60, usage["output_tokens"]+ end++ test "maps the opt-out sentinel back to a nil category" do+ stub_request(:post, ENDPOINT).to_return(+ status: 200,+ body: choice_body(choice: Provider::Jev::UNCATEGORIZED, confidence: 0.71),+ headers: { "Content-Type" => "application/json" }+ )++ response = @provider.auto_categorize(+ transactions: [ transaction(description: "ACH DEBIT 4471920 REF#88213") ],+ user_categories: categories+ )++ assert response.success?+ assert_nil response.data.sole.category_name+ end++ test "offers every category plus an explicit opt-out as choice criteria" do+ stub = stub_request(:post, ENDPOINT)+ .with do |request|+ criteria = JSON.parse(request.body).dig("questions", "category", "criteria")+ assert_equal %w[Groceries Restaurants\ &\ Bars Coffee] + [ Provider::Jev::UNCATEGORIZED ], criteria.keys+ # Categories have no description column, so the hint comes from the hierarchy.+ assert_equal "Subcategory of Restaurants & Bars", criteria["Coffee"]+ assert_nil criteria["Groceries"]+ true+ end+ .to_return(status: 200, body: choice_body(choice: "Coffee"), headers: { "Content-Type" => "application/json" })++ @provider.auto_categorize(transactions: [ transaction ], user_categories: categories)++ assert_requested stub+ end++ test "sends one request per transaction" do+ stub = stub_request(:post, ENDPOINT).to_return(+ status: 200,+ body: choice_body(choice: "Groceries"),+ headers: { "Content-Type" => "application/json" }+ )++ transactions = 3.times.map { |i| transaction(id: "t#{i}") }+ response = @provider.auto_categorize(transactions: transactions, user_categories: categories)++ assert response.success?+ assert_equal 3, response.data.size+ assert_requested stub, times: 3+ end++ test "fails when no categories are available" do+ response = @provider.auto_categorize(transactions: [ transaction ], user_categories: [])++ assert_not response.success?+ assert_match(/No categories available/, response.error.message)+ end++ test "parses every answer type from a single multi-question call" do+ stub_request(:post, ENDPOINT).to_return(+ status: 200,+ body: {+ "model" => "typesafe/jev-1.13-20260917",+ "answers" => {+ "is_recurring" => { "type" => "noul", "noul" => 0.91 },+ "bill_type" => { "type" => "choice", "choice" => "subscription",+ "probabilities" => { "subscription" => 1.0, "bill" => 0.0 }, "confidence" => 1.0 },+ "clarity" => { "type" => "score", "score" => 1.92,+ "legend" => { "0" => "Opaque", "1" => "Partial", "2" => "Clear" },+ "probabilities" => { "0" => 0.01, "1" => 0.07, "2" => 0.92 }, "confidence" => 0.87 }+ },+ "usage" => { "input_tokens" => 625, "output_tokens" => 162, "cost" => 0.00002625 }+ }.to_json,+ headers: { "Content-Type" => "application/json" }+ )++ response = @provider.decide(+ state: { description: "NETFLIX.COM" },+ questions: {+ is_recurring: { type: "noul", instructions: "Recurring?", criteria: { true: "yes", false: "no" } },+ bill_type: { type: "choice", instructions: "Kind?", criteria: { subscription: "a", bill: "b" } },+ clarity: { type: "score", instructions: "Clear?", criteria: [ "Opaque", "Partial", "Clear" ] }+ }+ )++ assert response.success?+ set = response.data++ assert_in_delta 0.91, set.value_of(:is_recurring), 0.001+ assert_equal "subscription", set.value_of(:bill_type)+ assert_in_delta 1.92, set.value_of(:clarity), 0.001+ assert_equal({ "input_tokens" => 625, "output_tokens" => 162, "total_tokens" => 787, "cost" => 0.00002625 }, set.usage)+ end++ test "treats a choice with no reported confidence as maximally unconfident" do+ # A malformed answer must read as 0 rather than nil: nil would look like a+ # provider that does not report confidence at all, and sail through a+ # downstream threshold instead of being withheld.+ stub_request(:post, ENDPOINT).to_return(+ status: 200,+ body: { "answers" => { "category" => { "type" => "choice", "choice" => "Coffee" } } }.to_json,+ headers: { "Content-Type" => "application/json" }+ )++ response = @provider.auto_categorize(transactions: [ transaction ], user_categories: categories)++ assert response.success?+ assert_equal 0.0, response.data.sole.confidence+ end++ test "does not apply noul arithmetic to a score missing its confidence" do+ # (value - 0.5).abs * 2 is only meaningful for a noul. A score of 1.92 would+ # yield 2.84 — a confidence outside 0..1.+ stub_request(:post, ENDPOINT).to_return(+ status: 200,+ body: { "answers" => { "q" => { "type" => "score", "score" => 1.92 } } }.to_json,+ headers: { "Content-Type" => "application/json" }+ )++ response = @provider.decide(+ state: "x",+ questions: { q: { type: "score", instructions: "?", criteria: [ "a", "b", "c" ] } }+ )++ assert_equal 0.0, response.data[:q].confidence+ end++ test "clamps a reported confidence into 0..1" do+ # The threshold that consumes this is constrained to 0..1, so a reported+ # 1.5 would clear every setting and be applied and locked — the exact+ # outcome the withholding gate exists to prevent. A malformed answer has to+ # fail closed, not sail through.+ { 1.5 => 1.0, -0.4 => 0.0 }.each do |reported, expected|+ stub_request(:post, ENDPOINT).to_return(+ status: 200,+ body: choice_body(choice: "Coffee", confidence: reported),+ headers: { "Content-Type" => "application/json" }+ )++ response = @provider.auto_categorize(transactions: [ transaction ], user_categories: categories)++ assert_equal expected, response.data.sole.confidence+ end+ end++ test "survives a noul answer whose probability is not a number" do+ # The bound belongs next to the arithmetic that can exceed 1, not in the+ # caller: clamping the caller's result would raise on this path, which is+ # the one input worth sanitizing.+ stub_request(:post, ENDPOINT).to_return(+ status: 200,+ body: { "answers" => { "q" => { "type" => "noul", "noul" => "not-a-number" } } }.to_json,+ headers: { "Content-Type" => "application/json" }+ )++ response = @provider.decide(state: "x", questions: { q: { type: "noul", instructions: "?" } })++ assert response.success?+ assert_nil response.data[:q].confidence+ end++ test "derives confidence for noul answers from distance off the midpoint" do+ stub_request(:post, ENDPOINT).to_return(+ status: 200,+ body: { "answers" => { "q" => { "type" => "noul", "noul" => 0.5 } } }.to_json,+ headers: { "Content-Type" => "application/json" }+ )++ response = @provider.decide(+ state: "x",+ questions: { q: { type: "noul", instructions: "?", criteria: { true: "a", false: "b" } } }+ )++ # 0.5 is maximal uncertainty for a noul, so it maps to zero confidence.+ assert_in_delta 0.0, response.data[:q].confidence, 0.001+ end++ test "rejects an unknown question type before making a request" do+ response = @provider.decide(state: "x", questions: { q: { type: "bogus", instructions: "?", criteria: {} } })++ assert_not response.success?+ assert_match(/unknown type/, response.error.message)+ assert_not_requested :post, ENDPOINT+ end++ test "rejects a score rubric outside the documented level range" do+ response = @provider.decide(state: "x", questions: { q: { type: "score", instructions: "?", criteria: [ "only one" ] } })++ assert_not response.success?+ assert_match(/rubric levels/, response.error.message)+ assert_not_requested :post, ENDPOINT+ end++ test "rejects more categories than one choice question can hold" do+ too_many = (Provider::Jev::MAX_CHOICE_OPTIONS + 1).times.map { |i| { id: i.to_s, name: "Category #{i}", parent_id: nil } }++ response = @provider.auto_categorize(transactions: [ transaction ], user_categories: too_many)++ assert_not response.success?+ assert_match(/Too many categories/, response.error.message)+ end++ test "retries a throttled request" do+ # faraday-retry skips POST unless it is opted in explicitly, so without the+ # methods: [:post] option this backoff never runs and a 429 fails outright.+ stub = stub_request(:post, ENDPOINT)+ .to_return(status: 429, body: "")+ .then.to_return(status: 200, body: choice_body(choice: "Groceries"), headers: { "Content-Type" => "application/json" })++ response = @provider.auto_categorize(transactions: [ transaction ], user_categories: categories)++ assert response.success?+ assert_equal "Groceries", response.data.sole.category_name+ assert_requested stub, times: 2+ end++ test "surfaces a failed request from inside the parallel fan-out" do+ # The fan-out collects futures with value!, so a worker's exception has to+ # propagate rather than leaving a nil in the results array.+ stub_request(:post, ENDPOINT).to_return(status: 500, body: "upstream exploded")++ response = @provider.auto_categorize(+ transactions: [ transaction(id: "t1"), transaction(id: "t2") ],+ user_categories: categories+ )++ assert_not response.success?+ assert_kind_of Provider::Jev::Error, response.error+ end++ test "surfaces a malformed response as a provider error" do+ stub_request(:post, ENDPOINT).to_return(+ status: 200,+ body: { "model" => "jev" }.to_json,+ headers: { "Content-Type" => "application/json" }+ )++ response = @provider.decide(+ state: "x",+ questions: { q: { type: "choice", instructions: "?", criteria: { a: "a", b: "b" } } }+ )++ assert_not response.success?+ assert_match(/missing 'answers'/, response.error.message)+ end++ test "authenticates with a bearer token" do+ stub = stub_request(:post, ENDPOINT)+ .with(headers: { "Authorization" => "Bearer test_api_key" })+ .to_return(status: 200, body: choice_body(choice: "Groceries"), headers: { "Content-Type" => "application/json" })++ @provider.auto_categorize(transactions: [ transaction ], user_categories: categories)++ assert_requested stub+ end++ test "does not implement pdf processing" do+ # Jev cannot see a file. Extraction stays with a provider that can.+ assert_not @provider.respond_to?(:process_pdf)+ end++ test "requires an explicit Jev key rather than borrowing an OpenRouter one" do+ ENV.stubs(:[]).returns(nil)+ ENV.stubs(:[]).with("JEV_API_KEY").returns(nil)+ ENV.stubs(:[]).with("OPENROUTER_API_KEY").returns("sk-or-unrelated")+ Setting.stubs(:jev_api_key).returns(nil)++ # A self-hoster using OpenRouter for something else must not find Jev+ # silently switched on.+ assert_nil Provider::Jev.api_key+ assert_not Provider::Jev.configured?+ end++ test "uses the Jev key when one is explicitly set" do+ # Pairs with the test above: proves that assertion fails for the right+ # reason (the fallback is gone) rather than because nothing resolves.+ ENV.stubs(:[]).returns(nil)+ ENV.stubs(:[]).with("JEV_API_KEY").returns("jev_key")++ assert_equal "jev_key", Provider::Jev.api_key+ assert Provider::Jev.configured?+ end++ test "goes straight to the vendor by default" do+ # Routing a family's transaction descriptions through a gateway should be an+ # explicit choice, not inherited from a default.+ assert_equal "https://api.typesafe.ai/v1/systemone", Provider::Jev::DEFAULT_ENDPOINT+ assert_equal "jev-latest", Provider::Jev::DEFAULT_MODEL+ assert_not @provider.proxied?+ assert_equal "Jev", @provider.provider_name+ end++ test "refuses a plaintext endpoint" do+ error = assert_raises(Provider::Jev::Error) do+ Provider::Jev.new("test_api_key", endpoint: "http://api.typesafe.ai/v1/systemone")+ end++ assert_match(/https/, error.message)++ assert_not Provider::Jev.endpoint_allowed?("http://api.typesafe.ai/v1/systemone")+ assert_not Provider::Jev.endpoint_allowed?("ftp://api.typesafe.ai/x")+ assert_not Provider::Jev.endpoint_allowed?("not-a-url")+ assert_not Provider::Jev.endpoint_allowed?(nil)+ end++ test "allows plaintext only on loopback" do+ assert Provider::Jev.endpoint_allowed?("http://localhost:4000/v1/systemone")+ assert Provider::Jev.endpoint_allowed?("http://127.0.0.1:4000/v1/systemone")+ assert Provider::Jev.endpoint_allowed?("http://[::1]:4000/v1/systemone")+ assert Provider::Jev.endpoint_allowed?("http://LocalHost:4000/v1/systemone")+ assert Provider::Jev.endpoint_allowed?("https://api.typesafe.ai/v1/systemone")++ assert_nothing_raised do+ Provider::Jev.new("test_api_key", endpoint: "http://localhost:4000/v1/systemone")+ end+ end++ test "reports the host the current configuration will actually send to" do+ # The settings disclosure reads these: naming TypeSafe while a gateway is in+ # front of it would understate who sees the transaction descriptions.+ assert_equal "api.typesafe.ai", Provider::Jev.effective_host+ assert_not Provider::Jev.effective_proxied?++ Setting.jev_endpoint = "https://openrouter.ai/api/alpha/decisions"++ assert_equal "openrouter.ai", Provider::Jev.effective_host+ assert Provider::Jev.effective_proxied?+ ensure+ Setting.jev_endpoint = nil+ end++ test "reaches Jev through a gateway when pointed at one" do+ openrouter = "https://openrouter.ai/api/alpha/decisions"+ provider = Provider::Jev.new("test_api_key", endpoint: openrouter, model: "~typesafe/jev-latest")++ stub = stub_request(:post, openrouter)+ .with { |request| JSON.parse(request.body)["model"] == "~typesafe/jev-latest" }+ .to_return(status: 200, body: choice_body(choice: "Groceries"), headers: { "Content-Type" => "application/json" })++ provider.auto_categorize(transactions: [ transaction ], user_categories: categories)++ assert_requested stub+ # The disclosure has to name this host: descriptions transit it too.+ assert provider.proxied?+ assert_equal "openrouter.ai", provider.endpoint_host+ assert_equal "Jev via openrouter.ai", provider.provider_name+ end+enddiff --git a/test/models/rule/action_executor/auto_categorize_test.rb b/test/models/rule/action_executor/auto_categorize_test.rbindex 53b5e44a30..37da233625 100644--- a/test/models/rule/action_executor/auto_categorize_test.rb+++ b/test/models/rule/action_executor/auto_categorize_test.rb@@ -15,6 +15,26 @@ class Rule::ActionExecutor::AutoCategorizeTest < ActiveSupport::TestCase@executor = Rule::ActionExecutor::AutoCategorize.new(@rule)end+ test "self-hosted label estimates against the resolved categorization model" do+ @family.stubs(:self_hoster?).returns(true)+ @family.stubs(:categorization_model_name).returns("~typesafe/jev-latest")+ LlmUsage.expects(:estimate_auto_categorize_cost).with(+ transaction_count: 20,+ category_count: @family.categories.count,+ model: "~typesafe/jev-latest"+ ).returns(nil)++ assert_equal "Auto-categorize transactions with AI (cost: N/A)", @executor.label+ end++ test "self-hosted label reports missing categorization provider" do+ @family.stubs(:self_hoster?).returns(true)+ @family.stubs(:categorization_model_name).returns(nil)+ LlmUsage.expects(:estimate_auto_categorize_cost).never++ assert_equal "Auto-categorize transactions with AI (no categorization provider configured)", @executor.label+ end+test "logs when categorization is blocked by category enrichment protection" dotransaction = create_transaction(account: @account, name: "Protected transaction").transactiontransaction.lock_attr!(:category_id)diff --git a/test/models/rule/registry/transaction_resource_test.rb b/test/models/rule/registry/transaction_resource_test.rbnew file mode 100644index 0000000000..f1a4b209e1--- /dev/null+++ b/test/models/rule/registry/transaction_resource_test.rb@@ -0,0 +1,61 @@+require "test_helper"++class Rule::Registry::TransactionResourceTest < ActiveSupport::TestCase+ setup do+ @family = families(:empty)+ end++ test "auto categorization is available when Jev is the only categorization provider" do+ rule = build_rule(action_type: "auto_categorize")+ @family.stubs(:resolved_categorization_provider).returns(Provider::Jev.allocate)+ Provider::Registry.stubs(:preferred_llm_provider).returns(nil)++ keys = rule.registry.action_executors.map(&:key)++ assert_includes keys, "auto_categorize"+ assert_not_includes keys, "auto_detect_merchants"+ assert_instance_of Rule::ActionExecutor::AutoCategorize, rule.actions.first.executor+ end++ test "existing auto categorization actions stay displayable when no provider is configured" do+ rule = build_rule(action_type: "auto_categorize")+ @family.stubs(:resolved_categorization_provider).returns(nil)+ Provider::Registry.stubs(:preferred_llm_provider).returns(nil)++ keys = rule.registry.action_executors.map(&:key)++ assert_includes keys, "auto_categorize"+ assert_instance_of Rule::ActionExecutor::AutoCategorize, rule.actions.first.executor+ end++ test "new auto categorization actions are hidden when no provider is configured" do+ rule = build_rule(action_type: "exclude_transaction")+ @family.stubs(:resolved_categorization_provider).returns(nil)+ Provider::Registry.stubs(:preferred_llm_provider).returns(nil)++ keys = rule.registry.action_executors.map(&:key)++ assert_not_includes keys, "auto_categorize"+ end++ test "auto merchant detection is available when an LLM provider is configured" do+ rule = build_rule(action_type: "exclude_transaction")+ @family.stubs(:resolved_categorization_provider).returns(nil)+ Provider::Registry.stubs(:preferred_llm_provider).returns(Provider::Anthropic.allocate)++ keys = rule.registry.action_executors.map(&:key)++ assert_not_includes keys, "auto_categorize"+ assert_includes keys, "auto_detect_merchants"+ end++ private+ def build_rule(action_type:)+ @family.rules.create!(+ name: "Transaction registry test",+ resource_type: "transaction",+ effective_date: 1.day.ago.to_date,+ actions: [ Rule::Action.new(action_type: action_type) ]+ )+ end+enddiff --git a/test/system/settings/categorization_provider_test.rb b/test/system/settings/categorization_provider_test.rbnew file mode 100644index 0000000000..47003214cc--- /dev/null+++ b/test/system/settings/categorization_provider_test.rb@@ -0,0 +1,123 @@+require "application_system_test_case"++class Settings::CategorizationProviderTest < ApplicationSystemTestCase+ setup do+ sign_in @user = users(:family_admin)+ @family = @user.family+ # The settings page is guarded by self_hosted?, and the panel itself is+ # behind the preview gate.+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)+ end++ teardown do+ @family.update!(categorization_provider: "llm")+ end++ test "the panel is hidden until a user opts into preview features" do+ set_preview_features(false)++ visit settings_hosting_path++ assert_no_text "Transaction Categorization"+ end++ test "an opted-in user switches the family onto Jev and back" do+ set_preview_features(true)++ visit settings_hosting_path++ assert_text "Transaction Categorization"+ assert_equal "llm", @family.reload.categorization_provider++ # The select auto-submits on change, so choosing an option is the whole+ # interaction — there is no save button to press.+ select "Jev (TypeSafe)", from: "Categorization provider"+ assert_text "Data sharing"+ assert_equal "jev", @family.reload.categorization_provider++ select "AI provider (OpenAI or Anthropic)", from: "Categorization provider"+ assert_no_text "Data sharing"+ assert_equal "llm", @family.reload.categorization_provider+ end++ test "shadow results say there is no data rather than showing zero agreement" do+ # An empty table or a bare 0% reads as "the providers never agree", which is+ # the opposite of "nothing has been sampled yet".+ set_preview_features(true)++ visit settings_hosting_path++ assert_text "No comparisons recorded yet"+ assert_no_text "% agreement across"+ end++ test "shadow results summarise recorded comparisons" do+ set_preview_features(true)+ @family.categorization_comparisons.create!(+ applied_provider: "openai", applied_category_name: "Groceries",+ shadow_provider: "jev", shadow_category_name: "Restaurants & Bars",+ shadow_confidence: 0.52, agreed: false+ )+ @family.categorization_comparisons.create!(+ applied_provider: "openai", applied_category_name: "Coffee",+ shadow_provider: "jev", shadow_category_name: "Coffee",+ shadow_confidence: 0.97, agreed: true+ )++ visit settings_hosting_path++ assert_text "50.0% agreement across 2 sampled transactions"+ assert_text "openai chose Groceries; jev chose Restaurants & Bars"+ assert_text "confidence 0.52"+ end++ test "the tuning controls state what they cost" do+ set_preview_features(true)++ visit settings_hosting_path++ # Shadow mode doubles spend; that must be on the page, not buried in docs.+ assert_text "doubles the API spend"+ assert_field "family[categorization_shadow_rate]"++ # The threshold only means something for a provider that reports confidence.+ assert_no_field "family[categorization_confidence_threshold]"+ select "Jev (TypeSafe)", from: "Categorization provider"+ assert_field "family[categorization_confidence_threshold]"+ assert_text "left uncategorized, so a later run can try again"+ end++ test "credentials appear inside the panel only once Jev is selected" do+ # The key field used to live in a separate panel below, so an operator could+ # enter a key and have nothing happen. Selecting the provider and giving it+ # a key are one task and belong in one place.+ set_preview_features(true)++ visit settings_hosting_path++ # Matched by field name, not label: the Anthropic panel on the same page+ # also labels its token "API Key".+ assert_no_field "setting[jev_api_key]"++ select "Jev (TypeSafe)", from: "Categorization provider"++ assert_field "setting[jev_api_key]"+ assert_field "setting[jev_endpoint]"+ assert_field "setting[jev_model]"+ end++ test "selecting Jev without an API key warns that categorization will not switch" do+ set_preview_features(true)+ Provider::Jev.stubs(:configured?).returns(false)++ visit settings_hosting_path+ select "Jev (TypeSafe)", from: "Categorization provider"++ assert_text "Jev is selected but has no API key configured"+ end++ private+ def set_preview_features(enabled)+ @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => enabled))+ end+end