Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add a tunable, self-testing Bayes classifier (#4310)

Josh Sandersd07e61b924ec
diff --git a/app/controllers/settings/classifiers_controller.rb b/app/controllers/settings/classifiers_controller.rb
new file mode 100644
index 0000000000..a1c76b38b8
--- /dev/null
+++ b/app/controllers/settings/classifiers_controller.rb
@@ -0,0 +1,130 @@
+class Settings::ClassifiersController < ApplicationController
+ layout "settings"
+
+ before_action :require_admin!
+
+ def show
+ @breadcrumbs = [
+ [ t("breadcrumbs.home"), root_path ],
+ [ t("breadcrumbs.classifier"), nil ]
+ ]
+ @settings = Current.family.bayes_settings_object
+ @categories = Current.family.categories.alphabetically_by_hierarchy
+ @evaluation = Family::BayesEvaluation.cached(Current.family)
+ @evaluation_running = Family::BayesEvaluation.running?(Current.family)
+ @weight = Family::BayesEvaluation.weight(Current.family)
+ @rules_active = Family::CLASSIFIER_ACTION_TYPES.index_with { |action_type| Current.family.classifier_rule_active?(action_type) }
+ @add_rule = params[:add_rule].presence_in(Family::CLASSIFIER_ACTION_TYPES)
+ @add_rule = nil if @add_rule && Current.family.classifier_rules(@add_rule).exists?
+ end
+
+ # Each section of the page is its own auto-submitting form, so only that
+ # section's fields arrive; the rest of the stored settings are kept.
+ def update
+ if params[:reset].present?
+ Current.family.update!(bayes_settings: {})
+ return start_evaluation("reset")
+ end
+
+ changes = settings_params.to_h
+ changes[:excluded_category_ids] = excluded_category_ids if params.key?(:category_filter)
+ Current.family.update_bayes_settings!(changes) if changes.any?
+
+ redirect_to settings_classifier_path
+ rescue ActiveRecord::RecordInvalid => e
+ redirect_to settings_classifier_path, alert: e.record.errors.full_messages.to_sentence
+ end
+
+ # The matcher's or Bayes' switch, in step with its rule on the Rules page.
+ # Turning on one whose rule was deleted asks whether to add it again.
+ def rule
+ action_type = classifier_action_type
+ active = params[:active] == "1"
+ if active && !Current.family.classifier_rules(action_type).exists?
+ return redirect_to settings_classifier_path(add_rule: action_type)
+ end
+
+ Current.family.set_classifier_rule_active!(action_type, active)
+ redirect_to settings_classifier_path
+ end
+
+ def add_rule
+ action_type = classifier_action_type
+ Current.family.add_classifier_rule!(action_type)
+ redirect_to settings_classifier_path, notice: t(".success", name: Family.classifier_rule_name(action_type))
+ end
+
+ def run
+ BayesCategorizeJob.perform_later(Current.family)
+ redirect_to settings_classifier_path, notice: t(".success")
+ end
+
+ def clear_locks
+ ClearBayesLocksJob.perform_later(Current.family)
+ redirect_to settings_classifier_path, notice: t(".success")
+ end
+
+ def evaluate
+ start_evaluation("test")
+ end
+
+ def find_best
+ start_evaluation("find_best")
+ end
+
+ # The cost of a mistake saves as it changes, picking the bold rows shown
+ # and applied, so a reload (e.g. after Apply) keeps it.
+ def remember_weight
+ Family::BayesEvaluation.remember_weight!(Current.family, params[:weight])
+
+ redirect_to settings_classifier_path(anchor: "classifier_evaluation")
+ end
+
+ # Saves what "Find best settings" found, at the threshold for the chosen
+ # cost of a mistake, and the matcher's best cutoff, number agreeing and
+ # similarity for that cost, and tests them; unless the settings changed since.
+ def apply_best
+ family = Current.family
+ evaluation = Family::BayesEvaluation.cached(family)
+ settings = family.bayes_settings_object
+ unless evaluation&.dig("best") && evaluation["digest"] == settings.digest
+ return redirect_to settings_classifier_path(anchor: "classifier_evaluation")
+ end
+
+ weight = Family::BayesEvaluation.weight(family)
+ changes = Family::BayesEvaluation.apply_changes(evaluation, settings, weight)
+ return redirect_to settings_classifier_path(anchor: "classifier_evaluation") if changes.empty?
+
+ family.update_bayes_settings!(changes)
+ start_evaluation("test")
+ end
+
+ private
+ # One run at a time: a second would overwrite the first's result.
+ def start_evaluation(action)
+ if Family::BayesEvaluation.start_running!(Current.family)
+ BayesEvaluationJob.perform_later(Current.family, action: action)
+ end
+
+ redirect_to settings_classifier_path(anchor: "classifier_evaluation")
+ end
+
+ def classifier_action_type
+ params.require(:action_type).presence_in(Family::CLASSIFIER_ACTION_TYPES) || raise(ActionController::BadRequest)
+ end
+
+ def settings_params
+ scalar_keys = Family::BayesSettings::DEFAULTS.reject { |_, default| default.is_a?(Array) }.keys
+ params.fetch(:bayes_settings, {}).permit(*scalar_keys)
+ end
+
+ # The checklist submits what stays checked. Its cascade submits a parent
+ # only while every subcategory is checked, so a parent with some children
+ # checked isn't excluded itself; its unchecked children are.
+ def excluded_category_ids
+ included = Array(params[:included_category_ids]).map(&:to_s)
+ categories = Current.family.categories.pluck(:id, :parent_id).map { |id, parent_id| [ id.to_s, parent_id&.to_s ] }
+ partly_checked_parents = categories.filter_map { |id, parent_id| parent_id if included.include?(id) }
+ categories.map(&:first) - included - partly_checked_parents
+ end
+end
diff --git a/app/helpers/settings/classifiers_helper.rb b/app/helpers/settings/classifiers_helper.rb
new file mode 100644
index 0000000000..996391100c
--- /dev/null
+++ b/app/helpers/settings/classifiers_helper.rb
@@ -0,0 +1,11 @@
+module Settings::ClassifiersHelper
+ # One auto-submitting form per Settings → Classifier section: only its
+ # fields are sent, and the controller merges them into the stored settings.
+ # A helper, not a layout partial, so t(".key") inside still resolves
+ # against the section's own partial. Its builder names fields
+ # bayes_settings[...], for DS::Select.
+ def classifier_section_form(&block)
+ form_with url: settings_classifier_path, method: :patch, scope: :bayes_settings, class: "space-y-4",
+ data: { controller: "auto-submit-form", auto_submit_form_trigger_event_value: "change" }, &block
+ end
+end
diff --git a/app/helpers/settings_helper.rb b/app/helpers/settings_helper.rb
index 9e392d76b7..d5c1eca239 100644
--- a/app/helpers/settings_helper.rb
+++ b/app/helpers/settings_helper.rb
@@ -17,6 +17,7 @@ module SettingsHelper
{ name: -> { t("settings.settings_nav.statement_vault_label") }, path: :account_statements_path, condition: :admin_user? },
# Advanced section
{ name: -> { t("settings.settings_nav.ai_prompts_label") }, path: :settings_ai_prompts_path, condition: :admin_user? },
+ { name: -> { t("settings.settings_nav.classifier_label") }, path: :settings_classifier_path, condition: :admin_user? },
{ name: -> { t("settings.settings_nav.llm_usage_label") }, path: :settings_llm_usage_path, condition: :admin_user? },
{ name: -> { t("settings.settings_nav.api_key_label") }, path: :settings_api_keys_path, condition: :admin_user? },
{ name: -> { t("settings.settings_nav.self_hosting_label") }, path: :settings_hosting_path, condition: :self_hosted_and_admin? },
diff --git a/app/jobs/bayes_categorize_job.rb b/app/jobs/bayes_categorize_job.rb
new file mode 100644
index 0000000000..ce58a7eb0f
--- /dev/null
+++ b/app/jobs/bayes_categorize_job.rb
@@ -0,0 +1,11 @@
+# Settings → Classifier's Run: the matcher (when its rule is on), then Bayes,
+# over the uncategorized transactions, outside the rule order. After a sync
+# they run as rules (Merchant matcher, Category classifier).
+class BayesCategorizeJob < ApplicationJob
+ queue_as :medium_priority
+
+ def perform(family)
+ family.fill_similar_merchants if family.classifier_rule_active?("fill_similar_merchants")
+ family.bayes_categorize_uncategorized
+ end
+end
diff --git a/app/jobs/bayes_evaluation_job.rb b/app/jobs/bayes_evaluation_job.rb
new file mode 100644
index 0000000000..697424d811
--- /dev/null
+++ b/app/jobs/bayes_evaluation_job.rb
@@ -0,0 +1,37 @@
+# Runs Settings → Classifier's "Test my settings", "Find best settings"
+# (which shows each change it tries) or the test after "Reset to defaults":
+# action is one of Family::BayesEvaluation::ACTIONS. Not on an ai_* queue:
+# it needs no provider, so the chat reservation shouldn't hold it back.
+class BayesEvaluationJob < ApplicationJob
+ queue_as :low_priority
+
+ def perform(family, action: "test")
+ settings = family.bayes_settings_object
+ evaluation = begin
+ Family::BayesEvaluation.new(family, settings: settings).run!(action: action) do |changes|
+ Family::BayesEvaluation.mark_running!(family)
+ trying = I18n.t("settings.classifiers.evaluation.trying", changes: changes.map { |key, value|
+ I18n.t("settings.classifiers.evaluation.change", setting: I18n.t("settings.classifiers.#{Family::BayesEvaluation.section_for(key)}.#{key}"),
+ value: Family::BayesEvaluation.value_label(key, value))
+ }.join("; "))
+ Turbo::StreamsChannel.broadcast_update_to(family, target: "classifier_evaluation_progress", html: ERB::Util.html_escape(trying))
+ end
+ rescue
+ # Back to the last result, so the page isn't left on "Testing…".
+ broadcast_panel(family, Family::BayesEvaluation.cached(family), settings)
+ raise
+ end
+
+ broadcast_panel(family, evaluation, settings)
+ end
+
+ private
+ def broadcast_panel(family, evaluation, settings)
+ Turbo::StreamsChannel.broadcast_replace_to(
+ family,
+ target: "classifier_evaluation",
+ partial: "settings/classifiers/evaluation",
+ locals: { evaluation: evaluation, settings: settings, running: false, weight: Family::BayesEvaluation.weight(family) }
+ )
+ end
+end
diff --git a/app/jobs/clear_bayes_locks_job.rb b/app/jobs/clear_bayes_locks_job.rb
new file mode 100644
index 0000000000..1b5da2b6fa
--- /dev/null
+++ b/app/jobs/clear_bayes_locks_job.rb
@@ -0,0 +1,16 @@
+class ClearBayesLocksJob < ApplicationJob
+ queue_as :low_priority
+
+ def perform(family)
+ count = family.clear_bayes_locks!
+
+ DebugLogEntry.capture(
+ category: "auto_categorization",
+ level: "info",
+ message: "Cleared #{count} Bayes #{'lock'.pluralize(count)}",
+ source: self.class.name,
+ family: family,
+ metadata: { unlocked_count: count }
+ )
+ end
+end
diff --git a/app/models/data_enrichment.rb b/app/models/data_enrichment.rb
index 4c2005b59f..45fbb12dbe 100644
--- a/app/models/data_enrichment.rb
+++ b/app/models/data_enrichment.rb
@@ -22,6 +22,7 @@ class DataEnrichment < ApplicationRecord
redbark: "redbark",
trade_republic: "trade_republic",
bayes: "bayes",
+ similar: "similar",
fio: "fio"
}
end
diff --git a/app/models/family.rb b/app/models/family.rb
index 4ec45ba836..84da056d65 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -259,6 +259,7 @@ class Family < ApplicationRecord
validate :timezone_must_be_a_known_zone, if: :timezone_changed?
before_validation :normalize_enabled_currencies!
+ after_create_commit :add_classifier_rules
def primary_currency_code
self.class.normalize_currency_code(currency) || "USD"
@@ -478,34 +479,110 @@ class Family < ApplicationRecord
Merchant.where(id: (assigned_ids + recently_unlinked_ids + family_merchant_ids).uniq)
end
+ def bayes_settings_object
+ Family::BayesSettings.new(bayes_settings)
+ end
+
+ # Merges changes into the stored classifier settings; a blank number goes
+ # back to its default.
+ def update_bayes_settings!(changes)
+ update!(bayes_settings: bayes_settings_object.merge(changes).to_stored)
+ end
+
def auto_categorize_transactions_later(transactions, rule_run_id: nil)
AutoCategorizeJob.perform_later(self, transaction_ids: transactions.pluck(:id), rule_run_id: rule_run_id)
end
+ # The LLM only: Bayes is its own rule (Category classifier), so what it
+ # categorized is no longer uncategorized here.
def auto_categorize_transactions(transaction_ids)
- bayes_result = Family::BayesCategorizer.new(self).classify_and_apply(transaction_ids)
- remaining_ids = Array(transaction_ids) - bayes_result.categorized_ids
-
- # Bayes handled everything with sufficient confidence — skip the LLM
- # categorizer entirely (including its no-provider error contract).
- if bayes_result.categorized_ids.any? && remaining_ids.empty?
- DebugLogEntry.capture(
- category: "auto_categorization",
- level: "info",
- message: "Bayesian categorization handled all transactions; skipped LLM categorization",
- source: self.class.name,
- family: self,
- metadata: {
- requested_transaction_ids: Array(transaction_ids),
- categorized_transaction_ids: bayes_result.categorized_ids,
- modified_count: bayes_result.modified_count
- }
- )
- return bayes_result.modified_count
+ AutoCategorizer.new(self, transaction_ids: transaction_ids).auto_categorize
+ end
+
+ # Runs Bayes over the uncategorized transactions in scope the user hasn't
+ # locked, transfer legs aside (they never belong in Uncategorized); those
+ # it isn't sure about are tried again with a better model next time.
+ # Returns the modified count.
+ def bayes_categorize_uncategorized(scope = categorizable_transactions)
+ scope = scope.where(category_id: nil).where.not(kind: Transaction::UNCATEGORIZED_EXCLUDED_KINDS).enrichable(:category_id)
+ requested = scope.count
+ return 0 if requested.zero?
+
+ result = Family::BayesCategorizer.new(self, settings: bayes_settings_object).classify_and_apply(scope.select(:id))
+ DebugLogEntry.capture(
+ category: "auto_categorization",
+ level: "info",
+ message: "Bayesian categorization categorized #{result.categorized_ids.size} of #{requested} transactions",
+ source: self.class.name,
+ family: self,
+ metadata: { requested_count: requested, categorized_count: result.categorized_ids.size, modified_count: result.modified_count }
+ )
+ result.modified_count
+ end
+
+ # Copies near-duplicates' merchant to every transaction in scope without
+ # one the user hasn't locked, transfers aside. Returns how many got one.
+ def fill_similar_merchants(scope = categorizable_transactions)
+ ids = scope.where(merchant_id: nil).where.not(kind: Transaction::TRANSFER_KINDS).enrichable(:merchant_id).pluck(:id)
+ return 0 if ids.empty?
+
+ filled = Family::SimilarMerchantFiller.new(self).fill(ids)
+ DebugLogEntry.capture(
+ category: "auto_categorization",
+ level: "info",
+ message: "Near-duplicate merchant fill gave #{filled} of #{ids.size} transactions a merchant",
+ source: self.class.name,
+ family: self,
+ metadata: { requested_count: ids.size, filled_count: filled }
+ )
+ filled
+ end
+
+ # The matcher and Bayes are rules (Merchant matcher, Category classifier),
+ # so they run in the family's rule order; whether one is on is whether a
+ # rule with its action is. Settings → Classifier switches them.
+ CLASSIFIER_ACTION_TYPES = %w[fill_similar_merchants bayes_categorize].freeze
+
+ def self.classifier_rule_name(action_type)
+ action_type == "bayes_categorize" ? I18n.t("rules.classifier_rules.category_classifier") : I18n.t("rules.classifier_rules.merchant_matcher")
+ end
+
+ def classifier_rules(action_type)
+ rules.where(id: Rule::Action.where(action_type: action_type).select(:rule_id))
+ end
+
+ def classifier_rule_active?(action_type)
+ classifier_rules(action_type).exists?(active: true)
+ end
+
+ def set_classifier_rule_active!(action_type, active)
+ classifier_rules(action_type).find_each { |rule| rule.update!(active: active) }
+ end
+
+ # A rule with no conditions at the top of the order, the others moving
+ # down one.
+ def add_classifier_rule!(action_type, active: true)
+ Rule.transaction do
+ Rule.lock_positions!(self)
+ rules.update_all("position = position + 1")
+ rules.create!(name: self.class.classifier_rule_name(action_type), resource_type: "transaction", active: active, position: 1,
+ actions_attributes: [ { action_type: action_type } ])
end
+ end
- llm_modified_count = AutoCategorizer.new(self, transaction_ids: remaining_ids).auto_categorize
- bayes_result.modified_count + llm_modified_count
+ # Unlocks the categories Bayes locked itself (lock_results) and the
+ # merchants the matcher did (lock_similar_merchants) that are still what
+ # they set, so rules and AI may change them again. The values stay. All or
+ # none; returns how many were unlocked.
+ def clear_bayes_locks!
+ locked_by_bayes = transactions.where("transactions.locked_attributes ? 'category_id'")
+ .category_from("bayes", metadata: { locked_by_bayes: true })
+ locked_by_matcher = transactions.where("transactions.locked_attributes ? 'merchant_id'")
+ .where(Transaction.enriched_from_sql("merchant_id", "similar", metadata: { locked_by_similar: true }))
+ Transaction.transaction do
+ unlock_own_locks(locked_by_bayes, "category_id", "bayes", "locked_by_bayes") +
+ unlock_own_locks(locked_by_matcher, "merchant_id", "similar", "locked_by_similar")
+ end
end
def auto_detect_transaction_merchants_later(transactions, rule_run_id: nil)
@@ -783,6 +860,30 @@ class Family < ApplicationRecord
end
private
+ # Bayes first, so the matcher lands above it.
+ def add_classifier_rules
+ CLASSIFIER_ACTION_TYPES.reverse_each { |action_type| add_classifier_rule!(action_type) }
+ end
+
+ def categorizable_transactions
+ transactions.visible.with_entry.merge(Entry.excluding_split_parents)
+ end
+
+ # In batches, like Transaction.reassign_category!. update_all skips the
+ # touch a save carries to the entry (Family#entries_cache_version), so the
+ # entries are touched too.
+ def unlock_own_locks(scope, attribute, source, flag)
+ ids = scope.lock("FOR UPDATE OF transactions").pluck(:id)
+ ids.each_slice(Transaction::REASSIGN_TOUCH_BATCH_SIZE) do |batch|
+ Transaction.where(id: batch).update_all([ "locked_attributes = locked_attributes - ?, updated_at = ?", attribute, Time.current ])
+ # Without the flag, a lock the user sets later counts as confirming it.
+ DataEnrichment.where(enrichable_type: "Transaction", enrichable_id: batch, attribute_name: attribute, source: source)
+ .update_all([ "metadata = metadata - ?", flag ])
+ Entry.where(entryable_type: "Transaction", entryable_id: batch).touch_all
+ end
+ ids.size
+ end
+
# Mirrors the inline `investment_ids` / `crypto_ids` SQL blocks in
# `tax_advantaged_account_ids`. Joins `depositories` and filters by
# `Depository::TAX_ADVANTAGED_SUBTYPES` (currently `%w[hsa]`). Extracted
diff --git a/app/models/family/bayes_categorizer.rb b/app/models/family/bayes_categorizer.rb
index 1bc416df57..e2d3b469c5 100644
--- a/app/models/family/bayes_categorizer.rb
+++ b/app/models/family/bayes_categorizer.rb
@@ -1,134 +1,365 @@
# Naive-Bayes transaction categorizer.
#
-# Trains a multinomial naive-Bayes model (Laplace add-1 smoothing) on the
-# family's already-categorized transactions, then classifies uncategorized
-# ones from the same token signals the LLM categorizer uses
-# (entry name + notes + merchant name). Unlike AutoCategorizer it needs no
-# provider — pure Ruby, trained on the fly and memoized per instance.
+# Trains a naive-Bayes model on the family's already-categorized transactions
+# and classifies uncategorized ones. By default it is the original model:
+# multinomial NB over the words of name, notes and merchant name, add-1
+# smoothing, uniform prior. Every choice is tunable per family
+# (Family::BayesSettings, Settings → Classifier), up to complement NB (Rennie
+# et al. 2003, Lidstone smoothing) scoring each transaction as
+# P(c) × P(words | c) × P(merchant | c) × P(account | c)
+# × P(direction | c) × N(log10|amount| ; c, direction, currency)
+# with every factor its own distribution, so a long description doesn't
+# outweigh the merchant, account or amount. Unlike AutoCategorizer it
+# needs no provider — pure Ruby, trained on the fly and memoized per instance.
class Family::BayesCategorizer
- CONFIDENCE_THRESHOLD = 0.7
+ DIRECTIONS = %w[in out].freeze
+ # The original guard: no classifying until there's a real signal to train on.
MIN_TRAINING_TRANSACTIONS = 20
MIN_CATEGORIES = 2
- # The whole training set is held in memory, so cap it rather than loading a
- # long-lived family's entire history on every categorization run. The most
- # recent transactions are also the most representative of current spending.
- MAX_TRAINING_TRANSACTIONS = 5_000
+ # Distance from a mean counts up to this many standard deviations, so a
+ # one-off amount can tip a close call but not outvote the merchant.
+ AMOUNT_MAX_Z = 3.0
+ # A category's amount spread is shrunk towards the overall spread as if it
+ # had this many extra observations of it.
+ AMOUNT_VARIANCE_SHRINK = 2.0
+ # Floor for an amount spread (log10 units squared), so a category whose
+ # amounts are all the same doesn't get a zero-width curve.
+ AMOUNT_MIN_VARIANCE = 0.001
+ # Stored with each label beside the settings digest, so labels from
+ # different code can be told apart; the digest identifies the tuning.
+ MODEL_VERSION = "bayes-2"
+
+ # Letter/digit runs joined by single symbols stay one token: "mcdonald's",
+ # "s/o", "m&s"; leading and trailing symbols ("*netflix") are still stripped.
+ KEEP_SYMBOLS = /[\p{L}\p{N}]+(?:[^\p{L}\p{N}\s][\p{L}\p{N}]+)*/
+ # Letters mixed with 2+ digits: reference codes like "2k4l19"; keeps "7eleven", "o2".
+ CODE = /\A(?=.*\p{L})(?=(?:.*\p{N}){2})/
# categorized_ids: transaction ids the model labeled at/above threshold
# (regardless of whether the write actually changed anything).
# modified_count: how many of those writes changed the category.
Result = Data.define(:categorized_ids, :modified_count)
- def initialize(family)
+ attr_reader :settings
+
+ # as_of: train only on transactions dated on or before it (the time-split
+ # evaluation passes the day before each month); without it, on all of them,
+ # as the original does.
+ def initialize(family, settings: nil, as_of: nil)
@family = family
+ @settings = settings || family.bayes_settings_object
+ @as_of = as_of
end
# Guard: refuse to classify until there's a real signal to train on.
def enough_training_data?
- training_transactions.size >= MIN_TRAINING_TRANSACTIONS &&
- training_transactions.map(&:category_id).uniq.size >= MIN_CATEGORIES
+ return @enough_training_data if defined?(@enough_training_data)
+
+ @enough_training_data = training_transactions.size >= MIN_TRAINING_TRANSACTIONS &&
+ class_models.size >= MIN_CATEGORIES
end
# Returns [category_id, confidence] for the argmax category, or nil when
# the model isn't trained yet or no category clears the confidence
# threshold (below threshold = no confident answer).
def classify(transaction)
- return nil unless enough_training_data?
+ category_id, confidence = probabilities(transaction).max_by { |_, probability| probability }
+ return nil if category_id.nil? || confidence < settings.threshold
+
+ [ category_id, confidence ]
+ end
- log_scores = log_scores_for(tokens_for(transaction))
- return nil if log_scores.empty?
+ # { category_id => softmax score } over every trained category; empty when
+ # the model isn't trained yet or nothing about the transaction is known.
+ def probabilities(transaction)
+ return {} unless enough_training_data?
- category_id, _score = log_scores.max_by { |_, score| score }
- confidence = softmax(log_scores.values).max
- return nil if confidence < CONFIDENCE_THRESHOLD
+ log_scores = log_scores_for(transaction)
+ log_scores.keys.zip(softmax(log_scores.values)).to_h
+ end
- [ category_id, confidence ]
+ # The categories it can answer with; none until trained.
+ def category_ids
+ enough_training_data? ? class_models.keys : []
end
# Labels every uncategorized, enrichable transaction in transaction_ids
- # whose argmax confidence clears the threshold. No-op (empty Result) when
- # the training guard fails.
+ # whose argmax confidence clears the threshold.
+ # No-op (empty Result) when the training guard fails.
def classify_and_apply(transaction_ids)
return Result.new(categorized_ids: [], modified_count: 0) unless enough_training_data?
categorized_ids = []
modified_count = 0
- family.transactions
- .where(id: transaction_ids, category_id: nil)
- .enrichable(:category_id)
- .includes(:category, :merchant, :entry)
- .find_each do |transaction|
- category_id, _confidence = classify(transaction)
+ scope = family.transactions.where(id: transaction_ids, category_id: nil).enrichable(:category_id)
+ scope.includes(*preloads).find_each do |transaction|
+ category_id, confidence = classify(transaction)
next if category_id.nil?
categorized_ids << transaction.id
- was_modified = transaction.enrich_attribute(:category_id, category_id, source: "bayes")
+ # Kept on the enrichment so the threshold can be audited against what
+ # users later changed. A ranking score, not a probability.
+ metadata = { confidence: confidence.round(3), model: MODEL_VERSION, settings: settings.digest }
+ metadata[:locked_by_bayes] = true if settings.lock_results
+ was_modified = transaction.enrich_attribute(:category_id, category_id, source: "bayes", metadata: metadata)
+ transaction.lock_attr!(:category_id) if settings.lock_results
modified_count += 1 if was_modified
end
Result.new(categorized_ids: categorized_ids, modified_count: modified_count)
end
+ # An excluded parent takes its subcategories with it.
+ def excluded_category_ids
+ @excluded_category_ids ||= begin
+ ids = settings.excluded_category_ids
+ ids.any? ? ids | family.categories.where(parent_id: ids).pluck(:id).map(&:to_s) : ids
+ end
+ end
+
private
- attr_reader :family
+ attr_reader :family, :as_of
+
+ def preloads
+ settings.merchant_name_words ? %i[entry merchant] : %i[entry]
+ end
- # Same signal composition as AutoCategorizer#transactions_input, so the
- # two categorizers agree on what text a transaction speaks.
+ # Words from the entry (and optionally merchant name), the merchant by id
+ # and the account. Binary counts each token once per transaction.
def tokens_for(transaction)
- [ transaction.entry&.name, transaction.entry&.notes, transaction.merchant&.name ]
- .compact
- .join(" ")
- .downcase
- .scan(/[a-z0-9]+/)
+ tokens = word_tokens(transaction)
+ tokens << "merchant:#{transaction.merchant_id}" if settings.merchant_field && transaction.merchant_id
+ tokens << "account:#{transaction.entry.account_id}" if settings.account_field
+ settings.binary ? tokens.uniq : tokens
end
+ def word_tokens(transaction)
+ entry = transaction.entry
+ parts = [ entry.name ]
+ parts << entry.notes if settings.include_notes
+ parts << transaction.merchant&.name if settings.merchant_name_words
+ text = parts.compact.join(" ").downcase
+
+ tokens = case settings.word_split
+ when "symbols" then text.scan(KEEP_SYMBOLS)
+ when "unicode" then text.scan(/[\p{L}\p{N}]+/)
+ else text.scan(/[a-z0-9]+/)
+ end
+ if settings.drop_numbers
+ # With symbols kept, "12.50" or "16/10/2026" aren't all-digit: drop
+ # any token without a letter instead.
+ tokens = tokens.reject { |token| settings.word_split == "symbols" ? !token.match?(/\p{L}/) : token.match?(/\A\p{N}+\z/) }
+ end
+ tokens = tokens.reject { |token| token.length < 2 } unless settings.keep_single_chars
+ tokens = tokens.reject { |token| token.match?(CODE) } if settings.drop_codes
+ tokens += tokens.each_cons(2).map { |a, b| "#{a} #{b}" } if settings.bigrams
+ tokens
+ end
+
+ # Only "merchant:" and "account:" tokens carry these prefixes; a word can
+ # contain ":" only when split with symbols, and never starts this way in practice.
+ def field_for(token)
+ return :all unless settings.separate_fields
+
+ if token.start_with?("merchant:") then :merchant
+ elsif token.start_with?("account:") then :account
+ else :words
+ end
+ end
+
+ def direction_for(transaction)
+ transaction.entry.amount.negative? ? "in" : "out"
+ end
+
+ def log_amount(transaction)
+ Math.log10([ transaction.entry.amount.abs.to_f, 0.01 ].max)
+ end
+
+ # The newest categorized transactions by creation (as the original), dated on
+ # or before as_of if given, minus excluded categories, and
+ # optionally minus Bayes' own labels still waiting to be confirmed, so a
+ # wrong guess isn't fed back in and reinforced. A label trains once
+ # someone changes or locks it, or after its grace period.
def training_transactions
- @training_transactions ||= family.transactions
- .where.not(category_id: nil)
- .includes(:category, :merchant, :entry)
- .order(created_at: :desc)
- .limit(MAX_TRAINING_TRANSACTIONS)
- .to_a
+ @training_transactions ||= begin
+ scope = family.transactions.where.not(category_id: nil).joins(:entry)
+ scope = scope.where(entries: { date: ..as_of }) if as_of
+ scope = scope.where.not(category_id: excluded_category_ids) if excluded_category_ids.any?
+ scope = scope.where.not(kind: Transaction::TRANSFER_KINDS) if settings.exclude_transfers
+ scope = scope.where.not(unconfirmed_self_label_sql) if settings.skip_self_labels
+ scope.preload(*preloads)
+ .order("transactions.created_at DESC, transactions.id DESC")
+ .limit(settings.max_training_transactions)
+ .to_a
+ end
end
- # Per-category token-count models: { category_id => { total:, counts: } }.
+ # The category is still Bayes' recent guess. A lock the user set confirms
+ # it; one Bayes set itself (lock_results) doesn't.
+ def unconfirmed_self_label_sql
+ "#{Transaction.category_from_sql("bayes", since: settings.self_label_grace_days.days.ago)} " \
+ "AND (NOT (transactions.locked_attributes ? 'category_id') " \
+ "OR #{Transaction.category_from_sql("bayes", metadata: { locked_by_bayes: true })})"
+ end
+
+ # { category_id => { counts: { token => n }, field_totals: { field => n }, docs: n, total: n } }
def class_models
@class_models ||= training_transactions.group_by(&:category_id).transform_values do |txns|
counts = Hash.new(0)
txns.each { |txn| tokens_for(txn).each { |token| counts[token] += 1 } }
- { total: counts.values.sum, counts: counts }
+ field_totals = Hash.new(0)
+ counts.each { |token, count| field_totals[field_for(token)] += count }
+ { counts: counts, field_totals: field_totals, docs: txns.size, total: counts.values.sum }
end
end
- def vocabulary
- @vocabulary ||= Set.new(class_models.values.flat_map { |model| model[:counts].keys })
+ # P(c): the category's share of the training transactions, so a close
+ # call leans towards the category used more often; or uniform.
+ def log_prior(category_id)
+ return Math.log(1.0 / class_models.size) unless settings.prior
+
+ Math.log(class_models.fetch(category_id)[:docs].to_f / training_transactions.size)
end
- # Multinomial NB log-score per category with Laplace add-1 smoothing and
- # a uniform prior (constant across classes, so it drops out of softmax).
- # log(P(c)) + Σ_tokens log((count_t + 1) / (total + |V|))
- def log_scores_for(tokens)
- # Score only tokens the model has actually seen. An unknown token's
- # smoothed likelihood is 1/(total_c + |V|), which varies with the class's
- # own token count, so keeping them would let a wholly novel description
- # accumulate confidence for whichever category simply has the smallest
- # corpus. Dropping them leaves nothing to score, which is the honest
- # answer: no known signal, no classification, fall through to the LLM.
- known_tokens = tokens.select { |token| vocabulary.include?(token) }
- return {} if known_tokens.empty? || class_models.empty?
+ # Token counts over every category, for the complements; its keys are the
+ # vocabulary.
+ def all_counts
+ @all_counts ||= class_models.values.each_with_object(Hash.new(0)) do |model, sums|
+ model[:counts].each { |token, count| sums[token] += count }
+ end
+ end
+
+ def all_field_totals
+ @all_field_totals ||= class_models.values.each_with_object(Hash.new(0)) do |model, sums|
+ model[:field_totals].each { |field, count| sums[field] += count }
+ end
+ end
+
+ def field_vocabulary_sizes
+ @field_vocabulary_sizes ||= all_counts.keys.each_with_object(Hash.new(0)) { |token, sizes| sizes[field_for(token)] += 1 }
+ end
+
+ # Known tokens that can count as evidence. With the spread filter, a word
+ # (or merchant) used at much the same rate by every category is ignored:
+ # it counts only if one category's share of its rate is at least
+ # 1/K + spread_margin (from Bishop/Reverend). Accounts are exempt.
+ def usable_tokens
+ @usable_tokens ||= if settings.spread_filter
+ even = 1.0 / class_models.size
+ all_counts.keys.select do |token|
+ next true if token.start_with?("account:")
+
+ rates = class_models.values.map { |model| model[:total].zero? ? 0.0 : model[:counts][token].to_f / model[:total] }
+ rates.max / rates.sum >= even + settings.spread_margin
+ end.to_set
+ else
+ all_counts.keys.to_set
+ end
+ end
+
+ # Complement NB (default): each category is scored by how badly the
+ # transaction fits every *other* category, negated, plus the prior. Per
+ # token field f:
+ # log P(c) - Σ_tokens log((count_t(¬c) + α) / (total_f(¬c) + α|V_f|)) - log P(amount | ¬c)
+ # With two categories it equals multinomial NB, which the complement
+ # setting switches to: log P(c) + Σ log P(t | c) + log P(amount | c).
+ def log_scores_for(transaction)
+ # Unknown tokens carry no signal and are skipped; a transaction needs
+ # at least one known word or merchant, as the original, or it's left
+ # uncategorized: the account and amount never decide alone.
+ known_tokens = tokens_for(transaction).select { |token| usable_tokens.include?(token) }
+ return {} if known_tokens.none? { |token| !token.start_with?("account:") }
- denominator = vocabulary.size
class_models.each_with_object({}) do |(category_id, model), scores|
- score = Math.log(1.0 / class_models.size)
- score += known_tokens.sum do |token|
- count = model[:counts][token] || 0
- Math.log((count + 1).to_f / (model[:total] + denominator))
+ token_log_likelihood = known_tokens.sum { |token| token_log_likelihood(token, model) }
+ amount_log_likelihood = settings.amount_field ? amount_log_likelihood(category_id, transaction) : 0.0
+ scores[category_id] = if settings.complement
+ log_prior(category_id) - token_log_likelihood - amount_log_likelihood
+ else
+ log_prior(category_id) + token_log_likelihood + amount_log_likelihood
+ end
+ end
+ end
+
+ def token_log_likelihood(token, model)
+ field = field_for(token)
+ count = model[:counts][token]
+ total = model[:field_totals][field]
+ if settings.complement
+ count = all_counts[token] - count
+ total = all_field_totals[field] - total
+ end
+ Math.log((count + settings.smoothing) / (total + settings.smoothing * field_vocabulary_sizes[field]))
+ end
+
+ def direction_key(transaction)
+ settings.amount_by_direction ? direction_for(transaction) : "all"
+ end
+
+ # Sufficient statistics [n, Σx, Σx²] of x = log10|amount|, per
+ # [category_id, direction] and per direction for P(direction), and the
+ # same within each currency for the Gaussian, so ¥5,000 and $5,000 don't
+ # share a scale ("all" when that split is off).
+ def amount_stats
+ @amount_stats ||= training_transactions.each_with_object({}) do |txn, stats|
+ x = log_amount(txn)
+ direction = direction_key(txn)
+ currency = txn.entry.currency
+ keys = [ [ txn.category_id, direction ], direction, [ txn.category_id, direction, currency ], [ direction, currency ] ]
+ keys.each do |key|
+ sums = (stats[key] ||= [ 0, 0.0, 0.0 ])
+ sums[0] += 1
+ sums[1] += x
+ sums[2] += x * x
end
- scores[category_id] = score
end
end
+ def seen_directions
+ @seen_directions ||= DIRECTIONS.count { |direction| amount_stats.key?(direction) }
+ end
+
+ # log of P(direction | side) × N(log10|amount| ; side, direction,
+ # currency), where side is every *other* category for complement NB and
+ # the category itself otherwise. Per-direction Gaussians keep refunds and
+ # purchases at the same shop apart, and nearby amounts share evidence. 0
+ # for a direction never seen in training; no Gaussian for a currency never
+ # seen in it. Distance is capped at AMOUNT_MAX_Z standard deviations.
+ def amount_log_likelihood(category_id, transaction)
+ direction = direction_key(transaction)
+ return 0.0 unless amount_stats.key?(direction)
+
+ log_likelihood = 0.0
+ if settings.amount_by_direction
+ own_count = amount_stats.fetch([ category_id, direction ], [ 0 ])[0]
+ own_size = class_models[category_id][:docs]
+ count, size = if settings.complement
+ [ amount_stats[direction][0] - own_count, training_transactions.size - own_size ]
+ else
+ [ own_count, own_size ]
+ end
+ log_likelihood = Math.log((count + settings.smoothing) / (size + settings.smoothing * seen_directions))
+ end
+
+ currency = transaction.entry.currency
+ all = amount_stats[[ direction, currency ]]
+ return log_likelihood unless all
+
+ own = amount_stats.fetch([ category_id, direction, currency ], [ 0, 0.0, 0.0 ])
+ side = settings.complement ? all.zip(own).map { |a, o| a - o } : own
+ n = side[0]
+ return log_likelihood if n <= 0 || all[0] < 2
+
+ overall_variance = [ all[2] / all[0] - (all[1] / all[0])**2, AMOUNT_MIN_VARIANCE ].max
+ mean = side[1] / n
+ variance = [ side[2] / n - mean**2, 0.0 ].max
+ variance = (n * variance + AMOUNT_VARIANCE_SHRINK * overall_variance) / (n + AMOUNT_VARIANCE_SHRINK)
+ variance = [ variance, AMOUNT_MIN_VARIANCE ].max
+ z = ((log_amount(transaction) - mean) / Math.sqrt(variance)).clamp(-AMOUNT_MAX_Z, AMOUNT_MAX_Z)
+ log_likelihood - 0.5 * Math.log(2 * Math::PI * variance) - 0.5 * z**2
+ end
+
# Numerically stable softmax over the log-scores.
def softmax(scores)
max = scores.max
diff --git a/app/models/family/bayes_evaluation.rb b/app/models/family/bayes_evaluation.rb
new file mode 100644
index 0000000000..f92d150001
--- /dev/null
+++ b/app/models/family/bayes_evaluation.rb
@@ -0,0 +1,480 @@
+# Monthly time-split evaluation of Family::BayesCategorizer on the family's
+# own history, for Settings → Classifier. For each month it trains on what
+# came before (as of the day before the month starts) and classifies that
+# month's categorized transactions whose category isn't an automatic (Bayes
+# or AI) guess, comparing with what they're categorized as. It only reads:
+# classify never writes. The page scores the newest HOLDOUT_MONTHS of the
+# last MONTHS; "Find best settings" searches the months before them, so the
+# best found is scored on months it never saw (see search). The latest
+# result is cached, with the defaults alongside for comparison and the
+# digest of the settings it tested. The defaults keep the chosen categories,
+# so every column scores the same transactions. Each run also
+# scores the matcher (Family::SimilarMerchantFiller) on the same months, at
+# every cutoff, similarity and number agreeing it offers (matcher_report).
+class Family::BayesEvaluation
+ MONTHS = 6
+ HOLDOUT_MONTHS = 2
+ THRESHOLDS = [ 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 ].freeze
+ CACHE_TTL = 30.days
+ RUNNING_TTL = 15.minutes
+ TOP_CONFUSIONS = 3
+ # Picks the threshold Apply sets: a wrong answer costs this many right ones.
+ WEIGHTS = 1..3
+ DEFAULT_WEIGHT = 1
+ # What ran: Test my settings, Find best settings, or Reset to defaults
+ # (which tests the defaults).
+ ACTIONS = %w[test find_best reset].freeze
+ # Bumped when the cached result's shape changes, so an older one is ignored.
+ RESULT_VERSION = 9
+ # The matcher's settings: not searched; picked on the page from its own
+ # table (matcher_changes).
+ MATCHER_KEYS = %i[similar_threshold similar_min_neighbours similar_common_share].freeze
+ # The settings it tunes, by page section (for their labels): the on/off
+ # ones, and the word split and smoothing at SEARCH_STEPS. Not grace days:
+ # they're measured from today, not each month, so the evaluation can't
+ # judge them.
+ SEARCH_KEYS = {
+ category_training: %i[exclude_transfers skip_self_labels],
+ words: %i[include_notes spread_filter word_split
+ drop_numbers keep_single_chars drop_codes binary bigrams],
+ merchant: %i[merchant_name_words merchant_field],
+ amount: %i[amount_field amount_by_direction],
+ account: %i[account_field],
+ scoring: %i[complement smoothing separate_fields prior]
+ }.freeze
+ # Step 1 of search: each set tried in every on/off combination, in turn,
+ # and then fixed: the fields; whether the merchant and account score apart
+ # from the words; what's read as words.
+ FEATURE_SETS = [
+ %i[merchant_field amount_field account_field],
+ %i[separate_fields],
+ %i[merchant_name_words include_notes]
+ ].freeze
+ # The values tried for a choice or a number, its default among them.
+ SEARCH_STEPS = {
+ word_split: Family::BayesSettings::CHOICES[:word_split],
+ smoothing: [ 0.03, 0.1, 0.3, 1.0 ]
+ }.freeze
+ # A setting that does nothing unless this holds isn't tried.
+ SEARCH_ONLY_IF = {
+ amount_by_direction: :amount_field.to_proc,
+ separate_fields: ->(settings) { settings.merchant_field || settings.account_field }
+ }.freeze
+
+ # The latest result; when its "digest" differs from the current settings'
+ # the page says they've changed since.
+ def self.cached(family)
+ result = Rails.cache.read(cache_key(family))
+ result if result&.dig("version") == RESULT_VERSION
+ end
+
+ def self.running?(family)
+ Rails.cache.read(running_key(family)).present?
+ end
+
+ def self.mark_running!(family)
+ Rails.cache.write(running_key(family), true, expires_in: RUNNING_TTL)
+ end
+
+ # Marks a run as started unless one already is; false if one is.
+ def self.start_running!(family)
+ Rails.cache.write(running_key(family), true, expires_in: RUNNING_TTL, unless_exist: true)
+ end
+
+ # The chosen cost of a mistake, kept across runs and reloads.
+ def self.weight(family)
+ Rails.cache.read(weight_key(family)) || DEFAULT_WEIGHT
+ end
+
+ def self.remember_weight!(family, weight)
+ Rails.cache.write(weight_key(family), weight.to_i.clamp(WEIGHTS), expires_in: CACHE_TTL)
+ end
+
+ def self.weight_key(family)
+ [ "bayes-evaluation-weight", family.id ]
+ end
+
+ # The matcher's best cell for weight, over every cutoff: [cutoff, number
+ # agreeing, similarity] where right − weight × wrong is highest; on a tie,
+ # the most agreeing, then the highest similarity, then the highest cutoff
+ # (the fewest words ignored). nil without a matcher result, or when it
+ # scored no transactions. The page shows the table at its cutoff.
+ def self.best_matcher(result, weight)
+ return if result.dig("matcher", "n")&.zero?
+
+ cells = result.dig("matcher", "cutoffs").to_h.flat_map do |cutoff, sweeps|
+ sweeps.flat_map { |agreeing, sweep| sweep.map { |row| [ cutoff, agreeing, row ] } }
+ end
+ cutoff, agreeing, row = cells.max_by { |cutoff, agreeing, row| [ row["right"] - weight * row["wrong"], agreeing, row["threshold"], cutoff ] }
+ [ cutoff, agreeing, row["threshold"] ] if row
+ end
+
+ # The merchant matcher table's columns, like the category one's: yours,
+ # the best found for weight (only after Find best settings, as for the
+ # categories) and the defaults, each a cutoff and number agreeing;
+ # [[column, cutoff, agreeing, sweep (empty if it wasn't scored, e.g. a
+ # cutoff typed in)]]. nil without a matcher result.
+ def self.matcher_columns(result, settings, weight)
+ best_cutoff, best_agreeing, = best_matcher(result, weight)
+ return unless best_cutoff
+
+ defaults = Family::BayesSettings::DEFAULTS
+ columns = [ [ "current", settings.similar_common_share, settings.similar_min_neighbours ] ]
+ columns << [ "best", best_cutoff, best_agreeing ] if result["best"]
+ columns << [ "defaults", defaults[:similar_common_share], defaults[:similar_min_neighbours] ]
+ columns.map { |column, cutoff, agreeing| [ column, cutoff, agreeing, result.dig("matcher", "cutoffs", cutoff, agreeing) || [] ] }
+ end
+
+ # The matcher column whose mistakes the page lists, for the button
+ # pressed last, as for the categories (mistakes), at its own similarity
+ # (Best found's best one): [column, similarity, sweep row]. nil without a
+ # matcher result, or when that similarity or cutoff wasn't scored.
+ def self.matcher_mistakes(result, settings, weight)
+ column = { "find_best" => "best", "reset" => "defaults" }.fetch(result["action"], "current")
+ _, cutoff, _, sweep = matcher_columns(result, settings, weight)&.find { |name, *| name == column }
+ return unless cutoff
+
+ similarity = case column
+ when "best" then best_matcher(result, weight).last
+ when "defaults" then Family::BayesSettings::DEFAULTS[:similar_threshold]
+ else settings.similar_threshold
+ end
+ row = sweep.find { |r| r["threshold"] == similarity }
+ [ column, similarity, row ] if row
+ end
+
+ # Everything Apply saves: best_changes and matcher_changes; {} before
+ # Find best settings. Too little history holds back only the categories':
+ # the matcher is scored on the months shown, never searched.
+ def self.apply_changes(result, settings, weight)
+ return {} unless result["best"]
+
+ (result["short_history"] ? {} : best_changes(result, weight)).merge(matcher_changes(result, settings, weight))
+ end
+
+ # What Apply saves for the matcher: the best cell's cutoff, number
+ # agreeing and similarity, where they differ from settings.
+ def self.matcher_changes(result, settings, weight)
+ cutoff, agreeing, similarity = best_matcher(result, weight)
+ return {} unless cutoff
+
+ { "similar_common_share" => cutoff, "similar_min_neighbours" => agreeing, "similar_threshold" => similarity }
+ .reject { |key, value| settings.public_send(key) == value }
+ end
+
+ # The threshold scoring most right − weight × wrong in a sweep, the
+ # highest on a tie.
+ def self.best_threshold(sweep, weight)
+ sweep.max_by { |row| [ row["right"] - weight * row["wrong"], row["threshold"] ] }["threshold"]
+ end
+
+ # What Apply saves: the best found's changes, and the threshold scoring
+ # best for weight on the months shown. Only the threshold is fitted to
+ # them; the settings were searched without them.
+ def self.best_changes(result, weight)
+ best = result["best"]
+ threshold = best_threshold(best.dig("report", "sweep"), weight)
+ threshold == result.dig("current", "threshold") ? best["changes"] : best["changes"].merge("threshold" => threshold)
+ end
+
+ # The column whose mistakes the page lists, for the button pressed last,
+ # and the threshold they're at: [column, report, threshold].
+ def self.mistakes(result, weight)
+ case result["action"]
+ when "find_best" then [ "best", result.dig("best", "report"), best_changes(result, weight).fetch("threshold", result.dig("current", "threshold")) ]
+ when "reset" then [ "defaults", result["defaults"], result.dig("defaults", "threshold") ]
+ else [ "current", result["current"], result.dig("current", "threshold") ]
+ end
+ end
+
+ def self.cache_key(family)
+ [ "bayes-evaluation", family.id ]
+ end
+
+ def self.running_key(family)
+ [ "bayes-evaluation-running", family.id ]
+ end
+
+ def initialize(family, settings: family.bayes_settings_object, today: Date.current, months: MONTHS)
+ @family = family
+ @settings = settings
+ @today = today
+ @months = months
+ end
+
+ # Runs, caches and returns the result (plain hashes, so it caches as is):
+ # these settings and the defaults scored on the newest HOLDOUT_MONTHS, and
+ # for find_best, "best": the search over the months before, scored there
+ # too. The block sees each change it tries.
+ def run!(action: "test", &progress)
+ holdout = self.class.new(family, settings: settings, today: today, months: HOLDOUT_MONTHS)
+ current = holdout.report
+ defaults = Family::BayesSettings.new(excluded_category_ids: settings.excluded_category_ids)
+ result = {
+ "version" => RESULT_VERSION,
+ "action" => action,
+ "digest" => settings.digest,
+ "ran_at" => Time.current.iso8601,
+ "months" => holdout.month_labels,
+ "current" => current,
+ "defaults" => defaults.digest == settings.digest ? current : holdout.report(defaults),
+ "matcher" => holdout.matcher_report,
+ # Too little to tune the categories on (apply_changes).
+ "short_history" => current["n"].zero?
+ }
+ if action == "find_best"
+ tuning = self.class.new(family, settings: settings, today: today << HOLDOUT_MONTHS, months: months - HOLDOUT_MONTHS)
+ best, = tuning.search(&progress)
+ result["best"] = {
+ "changes" => best.values.reject { |key, value| settings.values[key] == value }.transform_keys(&:to_s),
+ "report" => best.digest == settings.digest ? current : holdout.report(best)
+ }
+ # The search keeps a change only when it's better in all but one month
+ # (better), so with fewer months it can test it can't keep any.
+ result["short_history"] ||= tuning.months_with_history < months - HOLDOUT_MONTHS - 1
+ end
+ Rails.cache.write(self.class.cache_key(family), result, expires_in: CACHE_TTL)
+ result
+ ensure
+ Rails.cache.delete(self.class.running_key(family))
+ end
+
+ # The page section whose strings label key.
+ def self.section_for(key)
+ key = key.to_sym
+ return :matcher if key == :similar_threshold
+ return :matcher_tuning if MATCHER_KEYS.include?(key)
+
+ SEARCH_KEYS.find { |_, keys| keys.include?(key) }&.first || :classifier
+ end
+
+ # How a value reads on the page: on/off, a choice's label, or the number.
+ def self.value_label(key, value)
+ case value
+ when true, false then I18n.t("settings.classifiers.evaluation.#{value ? "on" : "off"}")
+ when String then I18n.t("settings.classifiers.#{section_for(key)}.#{key}_#{value}")
+ else value
+ end
+ end
+
+ def month_labels
+ month_starts.map { |start| start.strftime("%Y-%m") }
+ end
+
+ # One settings' scores, uncached (bin/rails runner scripts compare many):
+ # { "n", "threshold", "auc", "month_aucs" => [auc of each month alone],
+ # "sweep" => [{ "threshold", "right", "wrong" }],
+ # "confusions" => { threshold => [[actual, predicted, count]] },
+ # "uncategorized" => { threshold => [[actual, count]] }: left unanswered }
+ def report(settings = self.settings)
+ by_month = month_starts.map { |start| month_results(settings, start) }
+ results = by_month.flatten(1)
+ sweep = (THRESHOLDS | [ settings.threshold ]).sort.map do |threshold|
+ answered = results.select { |confidence, _, _, _| confidence && confidence >= threshold }
+ right = answered.count { |_, correct, _, _| correct }
+ { "threshold" => threshold, "right" => right, "wrong" => answered.size - right }
+ end
+ confusions = sweep.to_h do |row|
+ mistakes = results.select { |confidence, correct, _, _| confidence && confidence >= row["threshold"] && !correct }
+ .group_by { |_, _, actual, predicted| [ actual, predicted ] }
+ .map { |(actual, predicted), rows| [ category_names[actual], category_names[predicted], rows.size ] }
+ .sort_by { |_, _, count| -count }
+ .first(TOP_CONFUSIONS)
+ [ row["threshold"], mistakes ]
+ end
+ uncategorized = sweep.to_h do |row|
+ left = results.reject { |confidence, _, _, _| confidence && confidence >= row["threshold"] }
+ .group_by { |_, _, actual, _| actual }
+ .map { |actual, rows| [ category_names[actual], rows.size ] }
+ .sort_by { |_, count| -count }
+ .first(TOP_CONFUSIONS)
+ [ row["threshold"], left ]
+ end
+ auc = ->(rows) { self.class.roc_auc(rows.map { |_, _, actual, _, probabilities| [ actual, probabilities ] })&.round(4) }
+ { "n" => results.size, "threshold" => settings.threshold, "auc" => auc.call(results), "month_aucs" => by_month.map(&auc),
+ "sweep" => sweep, "confusions" => confusions, "uncategorized" => uncategorized }
+ end
+
+ # The matcher on these months: each month's transactions with a merchant
+ # it could copy from, the merchant hidden and matched against the history
+ # before the month; { "n", "cutoffs" => { cutoff => { agreeing =>
+ # [{ "threshold" (the similarity), "right", "wrong", "confusions" =>
+ # [[actual, copied, count]], "unfilled" => [[actual, count]] }] } } }, at
+ # each cutoff, similarity and agreeing it offers, by merchant name. Right
+ # is the merchant they have.
+ def matcher_report
+ thresholds = Family::BayesSettings::STEPS[:similar_threshold]
+ cutoffs = Family::BayesSettings::STEPS[:similar_common_share]
+ # Each month's pool and test transactions, loaded once for every cutoff.
+ months = month_starts.map do |start|
+ filler = Family::SimilarMerchantFiller.new(family, settings: settings, as_of: start - 1.day)
+ [ filler.pool, filler.confirmed.where(entries: { date: start...(start >> 1) }).preload(:entry).to_a ]
+ end
+ names = Merchant.where(id: months.flat_map { |pool, tested| (pool + tested).map(&:merchant_id) }.uniq).pluck(:id, :name).to_h
+ by_cutoff = cutoffs.index_with do |cutoff|
+ rows = months.flat_map do |pool, tested|
+ matcher = Family::SimilarMatcher.new(pool, threshold: thresholds.min, min_neighbours: 1, common_share: cutoff)
+ tested.map { |transaction| [ matcher.neighbours(transaction).map { |neighbour, similarity| [ neighbour.merchant_id, similarity ] }, transaction.merchant_id ] }
+ end
+ matcher_sweeps(rows, thresholds, names)
+ end
+ { "n" => months.sum { |_, tested| tested.size }, "cutoffs" => by_cutoff }
+ end
+
+ # One-vs-rest ROC-AUC over [[actual category id, { category id => score }]],
+ # each category weighted by how many rows are in it (its own AUC is noisy
+ # when it has only a few); a missing score is 0, ties count half. nil when
+ # no category has rows both in and out of it. Needs no threshold: it asks
+ # how well the scores rank each category's rows above the rest.
+ def self.roc_auc(rows)
+ aucs = rows.map(&:first).tally.filter_map do |category_id, positives|
+ negatives = rows.size - positives
+ next if negatives.zero?
+
+ scores = rows.map { |actual, scores| [ scores.fetch(category_id, 0.0), actual == category_id ] }.sort_by(&:first)
+ rank_sum = 0.0
+ scores.chunk_while { |a, b| a.first == b.first }.inject(0) do |before, tied|
+ rank_sum += tied.count(&:last) * (before + (tied.size + 1) / 2.0)
+ before + tied.size
+ end
+ [ (rank_sum - positives * (positives + 1) / 2.0) / (positives * negatives), positives ]
+ end
+ return nil if aucs.empty?
+
+ aucs.sum { |auc, weight| auc * weight } / aucs.sum(&:last)
+ end
+
+ # [settings, report]: the best settings, starting from these, in two
+ # steps, each fixing what it picks, by ROC-AUC, which needs no threshold;
+ # a change is kept only when it's higher over all the months and in all
+ # but one of them alone, so a gain in a month or two that's just noise
+ # isn't taken. The threshold is picked afterwards (best_threshold), for
+ # the chosen cost of a mistake.
+ # 1. Features: each of FEATURE_SETS in every combination.
+ # 2. Parameters, greedily: try flipping each on/off setting and each other
+ # step of a number, keep the best change while it raises the AUC,
+ # repeat. First everything else, then Scoring.
+ # The block sees each change tried, as { key => value }.
+ def search(&progress)
+ best, best_report = settings, report(settings)
+ FEATURE_SETS.each { |keys| best, best_report = every_combination(best, best_report, keys, &progress) }
+ features = FEATURE_SETS.flatten
+ best, best_report = greedy(best, best_report, SEARCH_KEYS.except(:scoring).values.flatten - features, &progress)
+ greedy(best, best_report, SEARCH_KEYS[:scoring] - features, &progress)
+ end
+
+ # How many of these months have transactions to test and history before
+ # them to train on.
+ def months_with_history
+ month_starts.count do |start|
+ tested_scope.where(entries: { date: start...(start >> 1) }).exists? && tested_scope.where(entries: { date: ...start }).exists?
+ end
+ end
+
+ private
+ attr_reader :family, :settings, :today, :months
+
+ # { agreeing => [{ "threshold", "right", "wrong", "confusions",
+ # "unfilled" }] } for rows of [[[merchant id, similarity] of each
+ # neighbour], actual merchant id]; names: { merchant id => name }.
+ def matcher_sweeps(rows, thresholds, names)
+ Family::BayesSettings::STEPS[:similar_min_neighbours].index_with do |min|
+ thresholds.map do |threshold|
+ # [actual, copied], copied nil where it doesn't copy.
+ answers = rows.map do |neighbours, actual|
+ [ actual, Family::SimilarMatcher.agreed(neighbours.filter_map { |merchant_id, similarity| merchant_id if similarity >= threshold }, min) ]
+ end
+ wrong = answers.select { |actual, copied| copied && copied != actual }
+ top = ->(pairs) { pairs.tally.sort_by { |_, count| -count }.first(TOP_CONFUSIONS) }
+ { "threshold" => threshold, "right" => answers.count { |actual, copied| copied == actual }, "wrong" => wrong.size,
+ "confusions" => top.call(wrong).map { |(actual, copied), count| [ names[actual], names[copied], count ] },
+ "unfilled" => top.call(answers.filter_map { |actual, copied| actual unless copied }).map { |actual, count| [ names[actual], count ] } }
+ end
+ end
+ end
+
+ # [settings, report] with the on/off keys (those that do something) set
+ # to their best combination; on a tie, the fewest changes from best.
+ def every_combination(best, best_report, keys, &progress)
+ keys = searchable(best, keys)
+ start = best
+ combinations = [ true, false ].repeated_permutation(keys.size).map do |values|
+ keys.zip(values).to_h.reject { |key, value| start.public_send(key) == value }
+ end
+ combinations.reject(&:empty?).sort_by.with_index { |changes, i| [ changes.size, i ] }.each do |changes|
+ best, best_report = better(best, best_report, start.merge(changes), changes, &progress)
+ end
+ [ best, best_report ]
+ end
+
+ # [settings, report] after greedily changing keys, starting from best.
+ def greedy(best, best_report, keys, &progress)
+ loop do
+ changes = searchable(best, keys).flat_map do |key|
+ current_value = best.public_send(key)
+ (SEARCH_STEPS.fetch(key) { [ !current_value ] } - [ current_value ]).map { |value| { key => value } }
+ end
+ top, top_report = best, best_report
+ changes.each do |change|
+ top, top_report = better(top, top_report, best.merge(change), change, &progress)
+ end
+ return [ best, best_report ] if top.equal?(best)
+
+ best, best_report = top, top_report
+ end
+ end
+
+ def searchable(settings, keys)
+ keys.select { |key| SEARCH_ONLY_IF.fetch(key, ->(_) { true }).call(settings) }
+ end
+
+ # [settings, report]: candidate's when its ROC-AUC is higher over all the
+ # months and in all but one of them alone, else best's. Yields changes
+ # first, as it's tried.
+ def better(best, best_report, candidate, changes)
+ yield changes if block_given?
+ candidate_report = report(candidate)
+ auc = ->(value) { value || -Float::INFINITY }
+ months_better = candidate_report["month_aucs"].zip(best_report["month_aucs"]).count { |mine, theirs| auc.call(mine) > auc.call(theirs) }
+ if auc.call(candidate_report["auc"]) > auc.call(best_report["auc"]) && months_better >= months - 1
+ [ candidate, candidate_report ]
+ else
+ [ best, best_report ]
+ end
+ end
+
+ def month_starts
+ first = today.beginning_of_month
+ (1..months).map { |i| first << i }.reverse
+ end
+
+ # [[confidence or nil, correct?, actual category id, predicted id,
+ # { category id => score }]] for one month, at no threshold so the sweep
+ # can filter. Where it doesn't answer, every category scores alike for
+ # the AUC: no information, rather than a row left out.
+ def month_results(settings, start)
+ categorizer = Family::BayesCategorizer.new(family, settings: settings, as_of: start - 1.day)
+ uniform = categorizer.category_ids.index_with { 1.0 / categorizer.category_ids.size }
+ test_transactions(categorizer, start).map do |transaction|
+ probabilities = categorizer.probabilities(transaction)
+ category_id, confidence = probabilities.max_by { |_, probability| probability }
+ [ confidence, category_id == transaction.category_id, transaction.category_id, category_id, probabilities.presence || uniform ]
+ end
+ end
+
+ def test_transactions(categorizer, start)
+ scope = tested_scope.where(entries: { date: start...(start >> 1) })
+ excluded = categorizer.excluded_category_ids
+ scope = scope.where.not(category_id: excluded) if excluded.any?
+ scope.preload(:entry, :merchant).to_a
+ end
+
+ # Categorized transactions whose category isn't an automatic guess.
+ def tested_scope
+ family.transactions.where.not(category_id: nil).where.not(Transaction.category_from_sql("ai", "bayes")).joins(:entry)
+ end
+
+ def category_names
+ @category_names ||= family.categories.pluck(:id, :name).to_h
+ end
+end
diff --git a/app/models/family/bayes_settings.rb b/app/models/family/bayes_settings.rb
new file mode 100644
index 0000000000..0757b03c8f
--- /dev/null
+++ b/app/models/family/bayes_settings.rb
@@ -0,0 +1,130 @@
+# A family's tuning for Family::BayesCategorizer, stored in
+# families.bayes_settings. Only values that differ from DEFAULTS are stored,
+# so a family that never touched the page follows any later change of a
+# default. DEFAULTS reproduce the original categorizer (multinomial NB, add-1,
+# uniform prior, words from name, notes and merchant name), so the page
+# compares any tuning with it, except that Bayes' own unconfirmed guesses
+# don't train it (skip_self_labels).
+class Family::BayesSettings
+ DEFAULTS = {
+ # Training
+ excluded_category_ids: [],
+ # On: Bayes runs with the rules after every sync, so its own guesses would
+ # otherwise train the next run and a wrong one would be reinforced.
+ skip_self_labels: true,
+ # A guess the user has left alone this long counts as accepted: picking
+ # the same category again doesn't lock it, so there's no other way.
+ self_label_grace_days: 90,
+ exclude_transfers: false,
+ # The training set is held in memory, so it's capped; the newest
+ # transactions are the most representative of current spending.
+ max_training_transactions: 5_000,
+
+ # Words
+ include_notes: true,
+ # How the text splits into words: a–z and 0–9 only (the original), letters of
+ # any script, or any script with symbols inside words kept (CHOICES).
+ word_split: "ascii",
+ drop_numbers: false,
+ keep_single_chars: true,
+ drop_codes: false,
+ spread_filter: false,
+ spread_margin: 0.1,
+ bigrams: false,
+ merchant_name_words: true,
+
+ # Amount
+ amount_field: false,
+ amount_by_direction: true,
+
+ # Account and merchant
+ account_field: false,
+ merchant_field: false,
+ # Matcher (the Merchant matcher rule): a missing merchant is copied from
+ # near-duplicates (Family::SimilarMerchantFiller) this alike, when at
+ # least this many agree. On one family's history 0.8–0.95 made little
+ # difference; 2 instead of 1 halved the mistakes, most of them one shop
+ # under two merchants.
+ lock_similar_merchants: false,
+ similar_threshold: 0.9,
+ similar_min_neighbours: 2,
+ similar_common_share: 0.2,
+ # Copying from its own copies, like Bayes' skip_self_labels.
+ similar_skip_self: true,
+ similar_self_grace_days: 90,
+
+ # Scoring
+ complement: false,
+ smoothing: 1.0,
+ prior: false,
+ binary: false,
+ separate_fields: false,
+
+ # Classifier (the Category classifier rule)
+ threshold: 0.7,
+ lock_results: false
+ }.freeze
+
+ CHOICES = { word_split: %w[ascii unicode symbols] }.freeze
+ # The matcher's similarities and cutoffs scored in Auto-tune, and the
+ # numbers agreeing its table and the Merchant matcher tuning section offer.
+ STEPS = {
+ similar_threshold: [ 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95 ],
+ similar_min_neighbours: [ 1, 2, 3 ],
+ similar_common_share: [ 0.01, 0.02, 0.05, 0.1, 0.2, 0.4 ]
+ }.freeze
+
+ RANGES = {
+ self_label_grace_days: 1..3650,
+ similar_self_grace_days: 1..3650,
+ max_training_transactions: 100..20_000,
+ threshold: 0.05..0.99,
+ spread_margin: 0.0..0.9,
+ smoothing: 0.001..10.0,
+ similar_threshold: 0.5..0.99,
+ similar_min_neighbours: 1..3,
+ similar_common_share: 0.01..1.0
+ }.freeze
+
+ attr_reader :values
+
+ def initialize(stored = {})
+ stored = (stored || {}).to_h.transform_keys(&:to_sym).slice(*DEFAULTS.keys)
+ @values = DEFAULTS.merge(stored.to_h { |key, value| [ key, coerce(key, value) ] }).freeze
+ end
+
+ DEFAULTS.each_key { |key| define_method(key) { values[key] } }
+
+ # What goes in the column: only the differences from DEFAULTS.
+ def to_stored
+ values.reject { |key, value| value == DEFAULTS[key] }.transform_keys(&:to_s)
+ end
+
+ def merge(changes)
+ self.class.new(values.merge(changes.to_h.transform_keys(&:to_sym)))
+ end
+
+ def default?
+ to_stored.empty?
+ end
+
+ # Short and stable: keys an evaluation result and each Bayes label.
+ def digest
+ Digest::SHA256.hexdigest(to_stored.sort.to_json)[0, 12]
+ end
+
+ private
+ def coerce(key, value)
+ case DEFAULTS[key]
+ when true, false then ActiveModel::Type::Boolean.new.cast(value) ? true : false
+ when Array then Array(value).map(&:to_s).reject(&:blank?).uniq.sort
+ when Integer then clamp(key, Integer(value.to_s, exception: false) || DEFAULTS[key])
+ when Float then clamp(key, Float(value.to_s, exception: false) || DEFAULTS[key])
+ when String then CHOICES[key].include?(value.to_s) ? value.to_s : DEFAULTS[key]
+ end
+ end
+
+ def clamp(key, value)
+ RANGES[key] ? value.clamp(RANGES[key].min, RANGES[key].max) : value
+ end
+end
diff --git a/app/models/family/similar_matcher.rb b/app/models/family/similar_matcher.rb
new file mode 100644
index 0000000000..11fd0c3f36
--- /dev/null
+++ b/app/models/family/similar_matcher.rb
@@ -0,0 +1,109 @@
+# Finds near-duplicates of a transaction in a pool by its description:
+# TF-IDF cosine over its words and, separately, its character 3-grams, so
+# "NETFLIX.COM 8812" and "Netflix com" match. Numbers and reference codes
+# are dropped first, so they don't make one shop's lines look different or
+# two shops' look alike. Used by Family::SimilarMerchantFiller to copy a
+# merchant every confirmed near-duplicate agrees on.
+class Family::SimilarMatcher
+ # The cutoff (common_share) is never below this many transactions, so a
+ # small pool keeps a monthly bill.
+ MIN_DOCUMENT_CAP = 50
+ GRAM = 3
+
+ # pool: transactions with their entries loaded. common_share: a feature in
+ # more than this share of the pool ("card", " pa") says nothing about which
+ # transaction it is, and its postings are the long ones, so it's ignored.
+ def initialize(pool, threshold:, min_neighbours:, common_share:)
+ @pool = pool
+ @threshold = threshold
+ @min_neighbours = min_neighbours
+ @common_share = common_share
+ end
+
+ # [[pool transaction, similarity]] at or above the threshold, best first;
+ # never the transaction itself.
+ def neighbours(transaction)
+ query = vectors_for(transaction.entry.name)
+ sums = Hash.new(0.0)
+ query.each do |kind, vector|
+ vector.each do |feature, weight|
+ index[kind][feature]&.each { |i, pool_weight| sums[i] += weight * pool_weight / 2 }
+ end
+ end
+ sums.filter_map { |i, similarity| [ pool[i], similarity ] if similarity >= threshold && pool[i].id != transaction.id }
+ .sort_by { |_, similarity| -similarity }
+ end
+
+ # The value of attribute the neighbours agree on: at least min_neighbours
+ # of them have one, and all that have one have the same. Neighbours
+ # without one (nil) don't count either way.
+ def agreed(transaction, attribute)
+ self.class.agreed(neighbours(transaction).filter_map { |neighbour, _| neighbour.public_send(attribute) }, min_neighbours)
+ end
+
+ # The value when at least min_neighbours values are given, all the same.
+ def self.agreed(values, min_neighbours)
+ values.first if values.size >= min_neighbours && values.uniq.one?
+ end
+
+ private
+ attr_reader :pool, :threshold, :min_neighbours, :common_share
+
+ # { words: { feature => [[pool index, weight]] }, grams: ... }
+ def index
+ @index ||= begin
+ index = { words: {}, grams: {} }
+ pool_vectors.each_with_index do |vectors, i|
+ vectors.each { |kind, vector| vector.each { |feature, weight| (index[kind][feature] ||= []) << [ i, weight ] } }
+ end
+ index
+ end
+ end
+
+ def pool_vectors
+ @pool_vectors ||= pool_features.map { |features| weigh(features) }
+ end
+
+ def pool_features
+ @pool_features ||= pool.map { |transaction| features(transaction.entry.name) }
+ end
+
+ # { words: { feature => weight }, grams: ... }, each L2-normalized, with
+ # sublinear tf × idf; features unknown to the pool or too common skipped.
+ def vectors_for(text)
+ weigh(features(text))
+ end
+
+ def weigh(features)
+ features.to_h do |kind, counts|
+ weights = counts.filter_map do |feature, count|
+ idf = idfs[kind][feature]
+ [ feature, (1 + Math.log(count)) * idf ] if idf
+ end.to_h
+ norm = Math.sqrt(weights.values.sum { |weight| weight**2 })
+ [ kind, norm.zero? ? {} : weights.transform_values { |weight| weight / norm } ]
+ end
+ end
+
+ def idfs
+ @idfs ||= begin
+ max_documents = [ (pool.size * common_share).floor, MIN_DOCUMENT_CAP ].max
+ %i[words grams].to_h do |kind|
+ documents = pool_features.each_with_object(Hash.new(0)) { |features, df| features[kind].each_key { |feature| df[feature] += 1 } }
+ idf = documents.filter_map do |feature, df|
+ [ feature, Math.log((pool.size + 1.0) / (df + 1)) + 1 ] if df <= max_documents
+ end.to_h
+ [ kind, idf ]
+ end
+ end
+ end
+
+ # { words: { word => count }, grams: { 3-gram => count } }
+ def features(text)
+ words = text.to_s.downcase.scan(/[\p{L}\p{N}]+/)
+ .select { |word| word.match?(/\p{L}/) && !word.match?(Family::BayesCategorizer::CODE) }
+ padded = " #{words.join(" ")} "
+ grams = padded.length < GRAM ? [] : (0..padded.length - GRAM).map { |i| padded[i, GRAM] }
+ { words: words.tally, grams: grams.tally }
+ end
+end
diff --git a/app/models/family/similar_merchant_filler.rb b/app/models/family/similar_merchant_filler.rb
new file mode 100644
index 0000000000..a52ecc79ff
--- /dev/null
+++ b/app/models/family/similar_merchant_filler.rb
@@ -0,0 +1,70 @@
+# Fills in a transaction's missing merchant from its near-duplicates
+# (Family::SimilarMatcher): when at least similar_min_neighbours of them have a
+# confirmed merchant, and all the same one. Runs before Bayes, so Bayes sees
+# the merchant. Confirmed means, optionally (Merchant matcher tuning): not its own
+# recent copy, unless the user locked it (a lock it set itself,
+# lock_similar_merchants, doesn't count), so a wrong copy isn't spread. AI
+# merchants count: the detector locks what it sets. The pool is the newest transactions
+# with a merchant, capped like Bayes' training set.
+# Transfers neither give nor get one: they have no merchant, and a
+# description typed in the banking app makes them look alike.
+class Family::SimilarMerchantFiller
+ # as_of: copy only from transactions dated on or before it (the
+ # evaluation passes the day before each month); without it, from all.
+ def initialize(family, settings: family.bayes_settings_object, as_of: nil)
+ @family = family
+ @settings = settings
+ @as_of = as_of
+ end
+
+ # Returns how many of transaction_ids got a merchant.
+ def fill(transaction_ids)
+ return 0 if pool.size < settings.similar_min_neighbours
+
+ matcher = Family::SimilarMatcher.new(pool, threshold: settings.similar_threshold, min_neighbours: settings.similar_min_neighbours,
+ common_share: settings.similar_common_share)
+ eligible(family.transactions.where(id: transaction_ids, merchant_id: nil).enrichable(:merchant_id))
+ .includes(:entry).find_each.count do |transaction|
+ merchant_id = matcher.agreed(transaction, :merchant_id)
+ next false unless merchant_id
+
+ metadata = settings.lock_similar_merchants ? { locked_by_similar: true } : {}
+ filled = transaction.enrich_attribute(:merchant_id, merchant_id, source: "similar", metadata: metadata)
+ transaction.lock_attr!(:merchant_id) if filled && settings.lock_similar_merchants
+ filled
+ end
+ end
+
+ # Transactions whose merchant can be copied, any date.
+ def confirmed
+ scope = eligible(family.transactions.where.not(merchant_id: nil).joins(:entry))
+ scope = scope.where.not(own_copy_sql(settings.similar_self_grace_days.days.ago)) if settings.similar_skip_self
+ scope
+ end
+
+ # The newest of them, dated on or before as_of if given.
+ def pool
+ @pool ||= begin
+ scope = confirmed
+ scope = scope.where(entries: { date: ..as_of }) if as_of
+ scope.preload(:entry)
+ .order("transactions.created_at DESC, transactions.id DESC")
+ .limit(settings.max_training_transactions)
+ .to_a
+ end
+ end
+
+ private
+ attr_reader :family, :settings, :as_of
+
+ # The merchant is still the matcher's recent copy, unlocked or locked by
+ # the matcher itself.
+ def own_copy_sql(cutoff)
+ "#{Transaction.enriched_from_sql("merchant_id", "similar", since: cutoff)} AND (NOT (transactions.locked_attributes ? 'merchant_id') " \
+ "OR #{Transaction.enriched_from_sql("merchant_id", "similar", metadata: { locked_by_similar: true })})"
+ end
+
+ def eligible(scope)
+ scope.where.not(kind: Transaction::TRANSFER_KINDS)
+ end
+end
diff --git a/app/models/rule.rb b/app/models/rule.rb
index 517da613fe..4900d74b47 100644
--- a/app/models/rule.rb
+++ b/app/models/rule.rb
@@ -128,6 +128,14 @@ class Rule < ApplicationRecord
matching_scope.pluck(:id)
end
+ # Holds the family's rule positions until the transaction ends. with_connection
+ # is the transaction's own connection and isn't leased to the thread for good.
+ def self.lock_positions!(family)
+ with_connection do |connection|
+ connection.execute(sanitize_sql_array([ "SELECT pg_advisory_xact_lock(?, hashtext(?))", POSITION_LOCK_NAMESPACE, family.id.to_s ]))
+ end
+ end
+
# Sets the run order of all rules of a family. ordered_ids must list every
# rule of the family exactly once, so a stale page (a rule added or deleted
# meanwhile) cannot leave rules with clashing or missing positions.
@@ -311,9 +319,7 @@ class Rule < ApplicationRecord
def assign_next_position
return if position.to_i.positive?
- self.class.connection.execute(
- self.class.sanitize_sql_array([ "SELECT pg_advisory_xact_lock(?, hashtext(?))", POSITION_LOCK_NAMESPACE, family_id.to_s ])
- )
+ self.class.lock_positions!(family)
self.position = family.rules.maximum(:position).to_i + 1
end
diff --git a/app/models/rule/action_executor/auto_categorize.rb b/app/models/rule/action_executor/auto_categorize.rb
index 0ba902131f..8c653600a8 100644
--- a/app/models/rule/action_executor/auto_categorize.rb
+++ b/app/models/rule/action_executor/auto_categorize.rb
@@ -78,12 +78,7 @@ class Rule::ActionExecutor::AutoCategorize < Rule::ActionExecutor
end
def cached_transaction_ids(protected_scope)
- protected_scope
- .joins(:data_enrichments)
- .where(data_enrichments: { attribute_name: "category_id", source: "ai" })
- .where(Arel.sql("data_enrichments.value = to_jsonb(transactions.category_id::text)"))
- .distinct
- .pluck(:id)
+ protected_scope.category_from("ai").pluck(:id)
end
def log_cache_usage(transaction_ids)
diff --git a/app/models/rule/action_executor/bayes_categorize.rb b/app/models/rule/action_executor/bayes_categorize.rb
new file mode 100644
index 0000000000..8b4667ad8a
--- /dev/null
+++ b/app/models/rule/action_executor/bayes_categorize.rb
@@ -0,0 +1,20 @@
+# The Bayes classifier (Settings → Classifier) as a rule action: categorizes
+# the uncategorized matches it's sure of, in the rule's place in the order.
+# Free, so offered without a provider. Never overrides a lock.
+class Rule::ActionExecutor::BayesCategorize < Rule::ActionExecutor
+ def label
+ "Categorize with the classifier (no AI)"
+ end
+
+ def claimed_attributes
+ [ :category_id ]
+ end
+
+ def reserves_claimed_attributes?
+ false
+ end
+
+ def execute(transaction_scope, value: nil, ignore_attribute_locks: false, rule_run: nil)
+ rule.family.bayes_categorize_uncategorized(transaction_scope)
+ end
+end
diff --git a/app/models/rule/action_executor/fill_similar_merchants.rb b/app/models/rule/action_executor/fill_similar_merchants.rb
new file mode 100644
index 0000000000..b3e7a599ba
--- /dev/null
+++ b/app/models/rule/action_executor/fill_similar_merchants.rb
@@ -0,0 +1,20 @@
+# The merchant matcher (Settings → Classifier) as a rule action: copies a
+# missing merchant from near-duplicates, in the rule's place in the order.
+# Free, so offered without a provider. Never overrides a lock.
+class Rule::ActionExecutor::FillSimilarMerchants < Rule::ActionExecutor
+ def label
+ "Fill missing merchants from similar transactions (no AI)"
+ end
+
+ def claimed_attributes
+ [ :merchant_id ]
+ end
+
+ def reserves_claimed_attributes?
+ false
+ end
+
+ def execute(transaction_scope, value: nil, ignore_attribute_locks: false, rule_run: nil)
+ rule.family.fill_similar_merchants(transaction_scope)
+ end
+end
diff --git a/app/models/rule/registry/transaction_resource.rb b/app/models/rule/registry/transaction_resource.rb
index 14c3982873..a6053ac120 100644
--- a/app/models/rule/registry/transaction_resource.rb
+++ b/app/models/rule/registry/transaction_resource.rb
@@ -24,6 +24,8 @@ class Rule::Registry::TransactionResource < Rule::Registry
Rule::ActionExecutor::SetAsTransferOrPayment,
Rule::ActionExecutor::SplitTransaction,
Rule::ActionExecutor::SendEmailNotification,
+ Rule::ActionExecutor::FillSimilarMerchants,
+ Rule::ActionExecutor::BayesCategorize,
Rule::ActionExecutor::AutoCategorize,
Rule::ActionExecutor::AutoDetectMerchants
].freeze
diff --git a/app/models/transaction.rb b/app/models/transaction.rb
index 4faf687130..55b34b9684 100644
--- a/app/models/transaction.rb
+++ b/app/models/transaction.rb
@@ -218,6 +218,33 @@ class Transaction < ApplicationRecord
"AND #{not_pending_sql(table_alias, providers: providers)}"
end
+ # Transactions whose category is still the one an automatic source (e.g.
+ # "ai", "bayes") set.
+ scope :category_from, ->(*sources, since: nil, metadata: nil) { where(category_from_sql(*sources, since:, metadata:)) }
+
+ def self.category_from_sql(*sources, **options)
+ enriched_from_sql("category_id", *sources, **options)
+ end
+
+ # Transactions whose attribute (category_id, merchant_id; internal callers
+ # only) is still the value an automatic source set: that source's
+ # enrichment holds the current value. since: only enrichments written
+ # after it; metadata: only those whose metadata contains it.
+ def self.enriched_from_sql(attribute, *sources, since: nil, metadata: nil)
+ sql = +<<~SQL.squish
+ EXISTS (
+ SELECT 1 FROM data_enrichments de
+ WHERE de.enrichable_type = 'Transaction'
+ AND de.enrichable_id = transactions.id
+ AND de.attribute_name = :attribute
+ AND de.source IN (:sources)
+ AND de.value = to_jsonb(transactions.#{attribute}::text)
+ SQL
+ sql << " AND de.updated_at > :since" if since
+ sql << " AND de.metadata @> CAST(:metadata AS jsonb)" if metadata
+ sanitize_sql_array([ "#{sql})", { attribute: attribute, sources: sources.flatten.map(&:to_s), since: since, metadata: metadata&.to_json } ])
+ end
+
# Family-scoped query for Enrichable#clear_ai_cache
def self.family_scope(family)
joins(entry: :account).where(accounts: { family_id: family.id })
diff --git a/app/views/pages/dashboard/_filter_popover.html.erb b/app/views/pages/dashboard/_filter_popover.html.erb
index b39672fe68..82419d4500 100644
--- a/app/views/pages/dashboard/_filter_popover.html.erb
+++ b/app/views/pages/dashboard/_filter_popover.html.erb
@@ -1,4 +1,4 @@
-<%# locals: (button_text:, search_label:, apply_text:, hidden_fields: {}, list_controllers: "list-filter") %>
+<%# locals: (button_text:, search_label:, apply_text:, hidden_fields: {}, list_controllers: "list-filter", url: root_path, method: :get, form_data: { turbo_frame: "dashboard_sections", turbo_action: "advance" }) %>
<%# The checklist filter a dashboard widget puts beside its month picker: a
GET form back into the dashboard_sections frame, so the selection lives in
the URL, with a searchable list of options (yielded by the caller, one
@@ -7,7 +7,8 @@
month, the other widgets' months and filters) through the submit, so
applying this filter doesn't reset the rest of the dashboard. The submit
advances the address bar (as UI::PeriodPicker's links do), so the state
- survives a refresh, a bookmark and Back. %>
+ survives a refresh, a bookmark and Back. url, method and form_data let
+ another page reuse the checklist for a form that saves instead. %>
<%= render DS::Popover.new(variant: :button, no_padding: true) do |popover| %>
<% popover.with_button(
type: "button",
@@ -17,7 +18,7 @@
) %>
<% popover.with_custom_content do %>
- <%= form_with url: root_path, method: :get, data: { turbo_frame: "dashboard_sections", turbo_action: "advance" }, class: "p-3 w-56 space-y-2" do %>
+ <%= form_with url: url, method: method, data: form_data, class: "p-3 w-56 space-y-2" do %>
<% hidden_fields.each do |name, value| %>
<% if value.is_a?(Array) %>
<% value.each do |item| %>
diff --git a/app/views/settings/_settings_nav.html.erb b/app/views/settings/_settings_nav.html.erb
index 83fff7e804..172dcbc2eb 100644
--- a/app/views/settings/_settings_nav.html.erb
+++ b/app/views/settings/_settings_nav.html.erb
@@ -28,6 +28,7 @@ nav_sections = [
header: t(".advanced_section_title"),
items: [
{ label: t(".ai_prompts_label"), path: settings_ai_prompts_path, icon: "bot" },
+ { label: t(".classifier_label"), path: settings_classifier_path, icon: "sliders-horizontal" },
{ label: t(".llm_usage_label"), path: settings_llm_usage_path, icon: "activity" },
{ label: t(".api_keys_label"), path: settings_api_keys_path, icon: "key" },
{ label: t(".mcp_label"), path: settings_mcp_path, icon: "plug" },
diff --git a/app/views/settings/classifiers/_account.html.erb b/app/views/settings/classifiers/_account.html.erb
new file mode 100644
index 0000000000..d202c451b8
--- /dev/null
+++ b/app/views/settings/classifiers/_account.html.erb
@@ -0,0 +1,4 @@
+<%# locals: (settings:) %>
+<%= classifier_section_form do %>
+ <%= render "settings/classifiers/option", key: :account_field, settings: settings, label: t(".account_field"), hint: t(".account_field_hint") %>
+<% end %>
diff --git a/app/views/settings/classifiers/_amount.html.erb b/app/views/settings/classifiers/_amount.html.erb
new file mode 100644
index 0000000000..a231712c7f
--- /dev/null
+++ b/app/views/settings/classifiers/_amount.html.erb
@@ -0,0 +1,8 @@
+<%# locals: (settings:) %>
+<%# The amount, then its direction. Amounts are only ever compared within
+ one currency. %>
+<%= classifier_section_form do %>
+ <%= render "settings/classifiers/option", key: :amount_field, settings: settings, label: t(".amount_field"), hint: t(".amount_field_hint") %>
+ <%= render "settings/classifiers/option", key: :amount_by_direction, settings: settings, indent: true, disabled: !settings.amount_field,
+ label: t(".amount_by_direction"), hint: t(".amount_by_direction_hint") %>
+<% end %>
diff --git a/app/views/settings/classifiers/_category_training.html.erb b/app/views/settings/classifiers/_category_training.html.erb
new file mode 100644
index 0000000000..7a95ecfbd2
--- /dev/null
+++ b/app/views/settings/classifiers/_category_training.html.erb
@@ -0,0 +1,52 @@
+<%# locals: (settings:, categories:) %>
+<div class="space-y-4">
+ <%# Which categories it learns, which labels it trusts, then how many. %>
+ <div class="flex items-center justify-between gap-x-4">
+ <div class="flex-1 min-w-0">
+ <p class="text-sm text-primary"><%= t(".categories") %></p>
+ <p class="text-xs text-secondary"><%= t(".categories_hint") %></p>
+ </div>
+ <% excluded = settings.excluded_category_ids %>
+ <%= render layout: "pages/dashboard/filter_popover", locals: {
+ button_text: excluded.empty? ? t(".categories_all") : t(".categories_some", count: categories.size - excluded.size, total: categories.size),
+ search_label: t(".search_categories"),
+ apply_text: t(".apply"),
+ hidden_fields: { category_filter: "1" },
+ url: settings_classifier_path,
+ method: :patch,
+ form_data: {},
+ list_controllers: "list-filter category-filter"
+ } do %>
+ <%# The transactions filter's cascade: picking a parent covers its
+ subcategories, and a parent is submitted only while all of them
+ are checked. %>
+ <% categories.each do |category| %>
+ <%= render layout: "pages/dashboard/filter_popover_option", locals: {
+ name: "included_category_ids[]",
+ value: category.id,
+ checked: excluded.exclude?(category.id.to_s),
+ filter_name: category.display_name,
+ checkbox_data: {
+ category_filter_target: "checkbox",
+ action: "change->category-filter#toggle",
+ category_id: category.id,
+ parent_id: category.parent_id
+ }
+ } do %>
+ <% if category.parent_id.present? %>
+ <%= icon("corner-down-right", size: "sm") %>
+ <% end %>
+ <%= render partial: "categories/badge", locals: { category: category } %>
+ <% end %>
+ <% end %>
+ <% end %>
+ </div>
+
+ <%= classifier_section_form do %>
+ <%= render "settings/classifiers/option", key: :exclude_transfers, settings: settings,
+ label: t(".exclude_transfers"), hint: t(".exclude_transfers_hint") %>
+ <%= render "settings/classifiers/option", key: :skip_self_labels, settings: settings,
+ number_key: :self_label_grace_days,
+ label: t(".skip_self_labels"), hint: t(".skip_self_labels_hint") %>
+ <% end %>
+</div>
diff --git a/app/views/settings/classifiers/_classifier.html.erb b/app/views/settings/classifiers/_classifier.html.erb
new file mode 100644
index 0000000000..d90f3abe77
--- /dev/null
+++ b/app/views/settings/classifiers/_classifier.html.erb
@@ -0,0 +1,13 @@
+<%# locals: (settings:, active:) %>
+<%# What Bayes does: its rule's switch (categorizing, in the rule order), how
+ sure it must be, and whether its categories are locked. %>
+<div class="space-y-4">
+ <%= render "settings/classifiers/rule_toggle", action_type: "bayes_categorize", active: active,
+ label: t(".rule"), hint: t(".rule_hint") %>
+ <%= classifier_section_form do %>
+ <%= render "settings/classifiers/number", key: :threshold, settings: settings,
+ attrs: { step: 0.01 },
+ label: t(".threshold"), hint: t(".threshold_hint") %>
+ <%= render "settings/classifiers/toggle", key: :lock_results, settings: settings, label: t(".lock_results"), hint: t(".lock_results_hint") %>
+ <% end %>
+</div>
diff --git a/app/views/settings/classifiers/_evaluation.html.erb b/app/views/settings/classifiers/_evaluation.html.erb
new file mode 100644
index 0000000000..641bc7f01c
--- /dev/null
+++ b/app/views/settings/classifiers/_evaluation.html.erb
@@ -0,0 +1,119 @@
+<%# locals: (evaluation:, settings:, running:, weight:) %>
+<%# Replaced over the family's Turbo stream when BayesEvaluationJob finishes,
+ so translation keys are absolute (no request to resolve "." against). %>
+<div id="classifier_evaluation" class="space-y-4">
+ <%# In the order of the table's columns. %>
+ <div class="flex flex-wrap items-center gap-2">
+ <%= render DS::Button.new(text: t("settings.classifiers.evaluation.run"), href: evaluate_settings_classifier_path,
+ method: :post, variant: :outline, icon: "flask-conical", disabled: running) %>
+ <%= render DS::Button.new(text: t("settings.classifiers.evaluation.find_best"), href: find_best_settings_classifier_path,
+ method: :post, icon: "search", disabled: running) %>
+ <%= render DS::Button.new(text: t("settings.classifiers.evaluation.reset"), href: settings_classifier_path, method: :patch,
+ variant: :outline, icon: "rotate-ccw", params: { reset: "1" },
+ confirm: t("settings.classifiers.evaluation.reset_confirm"), disabled: running) %>
+ <%= render DS::Tooltip.new(text: t("settings.classifiers.evaluation.buttons_hint", tuning: Family::BayesEvaluation::MONTHS - Family::BayesEvaluation::HOLDOUT_MONTHS),
+ placement: "top-start") %>
+ </div>
+
+ <% if running %>
+ <%# One line, its height kept while empty and long changes cut short,
+ so the page doesn't move as the progress changes. %>
+ <div class="text-sm text-secondary">
+ <p><%= t("settings.classifiers.evaluation.running") %></p>
+ <p id="classifier_evaluation_progress" class="h-5 truncate"></p>
+ </div>
+ <% end %>
+
+ <% if evaluation %>
+ <% stale = evaluation["digest"] != settings.digest %>
+ <% best = evaluation["best"] %>
+ <% changes = Family::BayesEvaluation.apply_changes(evaluation, settings, weight) %>
+ <% matcher_columns = Family::BayesEvaluation.matcher_columns(evaluation, settings, weight) %>
+ <% if stale %>
+ <%= render DS::Alert.new(message: t("settings.classifiers.evaluation.stale"), variant: :warning) %>
+ <% end %>
+ <% if evaluation["short_history"] %>
+ <%= render DS::Alert.new(message: t("settings.classifiers.evaluation.short_history", months: Family::BayesEvaluation::MONTHS), variant: :warning) %>
+ <% end %>
+
+ <p class="text-xs text-secondary">
+ <%= t("settings.classifiers.evaluation.ran_at",
+ time: time_ago_in_words(Time.zone.parse(evaluation["ran_at"])),
+ count: evaluation.dig("current", "n"),
+ months: evaluation["months"].values_at(0, -1).uniq.join(" – ")) %>
+ </p>
+
+ <% columns = [ [ t("settings.classifiers.evaluation.current"), evaluation["current"] ] ] %>
+ <% columns << [ t("settings.classifiers.evaluation.best"), best["report"] ] if best %>
+ <% columns << [ t("settings.classifiers.evaluation.defaults"), evaluation["defaults"] ] %>
+ <h3 class="text-sm font-medium text-primary"><%= t("settings.classifiers.evaluation.categories_heading") %></h3>
+ <%= render "settings/classifiers/sweep_table", columns: columns, weight: weight %>
+ <p class="text-xs text-secondary"><%= t("settings.classifiers.evaluation.description", months: Family::BayesEvaluation::HOLDOUT_MONTHS) %></p>
+
+ <% if matcher_columns %>
+ <%# Like the category table: your cutoff and number agreeing, the best
+ found for the cost of a mistake (of every cutoff and number scored)
+ and the defaults', each with its best similarity in bold. Apply sets
+ the best found's. %>
+ <h3 class="text-sm font-medium text-primary"><%= t("settings.classifiers.evaluation.merchants_heading") %></h3>
+ <%= render "settings/classifiers/sweep_table", label: t("settings.classifiers.evaluation.similarity"),
+ weight: weight, columns: matcher_columns.map { |column, _, _, sweep| [ t("settings.classifiers.evaluation.#{column}"), { "sweep" => sweep } ] } %>
+ <p class="text-xs text-secondary">
+ <%= t("settings.classifiers.evaluation.matcher_description", count: evaluation.dig("matcher", "n"), months: Family::BayesEvaluation::HOLDOUT_MONTHS) %>
+ </p>
+ <% end %>
+
+ <div class="space-y-2">
+ <% if best && !evaluation["short_history"] && Family::BayesEvaluation.best_changes(evaluation, weight).empty? %>
+ <p class="text-sm text-secondary"><%= t("settings.classifiers.evaluation.best_no_changes") %></p>
+ <% end %>
+ <% if changes.any? %>
+ <p class="text-sm text-primary"><%= t("settings.classifiers.evaluation.best_changes") %></p>
+ <ul class="text-sm text-secondary space-y-0.5">
+ <% changes.each do |key, value| %>
+ <li>
+ <%= t("settings.classifiers.#{Family::BayesEvaluation.section_for(key)}.#{key}") %>:
+ <span class="text-primary"><%= Family::BayesEvaluation.value_label(key, value) %></span>
+ </li>
+ <% end %>
+ </ul>
+ <% end %>
+ <div class="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
+ <%# Changing the cost saves it and reloads, moving the bold rows and what Apply sets. %>
+ <%= form_with url: remember_weight_settings_classifier_path, method: :post, class: "flex items-center gap-2",
+ data: { controller: "auto-submit-form" } do |form| %>
+ <label for="weight_trigger" class="text-sm text-primary whitespace-nowrap"><%= t("settings.classifiers.evaluation.weight") %></label>
+ <div class="w-40">
+ <%= render DS::Select.new(form: form, method: :weight, selected: weight,
+ items: Family::BayesEvaluation::WEIGHTS.map { |w| { value: w, label: t("settings.classifiers.evaluation.weight_option", count: w) } }) %>
+ </div>
+ <%= render DS::Tooltip.new(text: t("settings.classifiers.evaluation.weight_hint"), placement: "top-start") %>
+ <% end %>
+ <%= render DS::Button.new(text: t("settings.classifiers.evaluation.apply_best"), href: apply_best_settings_classifier_path,
+ method: :patch, icon: "check", disabled: running || stale || changes.empty?) %>
+ </div>
+ </div>
+
+ <% column, report, threshold = Family::BayesEvaluation.mistakes(evaluation, weight) %>
+ <% mistakes = report.dig("confusions", threshold) || [] %>
+ <% uncategorized = report.dig("uncategorized", threshold) || [] %>
+ <% column_name = t("settings.classifiers.evaluation.#{column}") %>
+ <%= render "settings/classifiers/mistakes",
+ confusions_title: t("settings.classifiers.evaluation.confusions", column: column_name, threshold: threshold),
+ confusions: mistakes, no_confusions: t("settings.classifiers.evaluation.no_confusions"),
+ left_title: t("settings.classifiers.evaluation.uncategorized", column: column_name, threshold: threshold),
+ left: uncategorized, no_left: t("settings.classifiers.evaluation.no_uncategorized") %>
+
+ <% matcher_column, similarity, matcher_row = Family::BayesEvaluation.matcher_mistakes(evaluation, settings, weight) %>
+ <% if matcher_column %>
+ <% matcher_column_name = t("settings.classifiers.evaluation.#{matcher_column}") %>
+ <%= render "settings/classifiers/mistakes",
+ confusions_title: t("settings.classifiers.evaluation.matcher_confusions", column: matcher_column_name, similarity: similarity),
+ confusions: matcher_row["confusions"], no_confusions: t("settings.classifiers.evaluation.no_matcher_confusions"),
+ left_title: t("settings.classifiers.evaluation.unfilled", column: matcher_column_name, similarity: similarity),
+ left: matcher_row["unfilled"], no_left: t("settings.classifiers.evaluation.no_unfilled") %>
+ <% end %>
+ <% elsif !running %>
+ <p class="text-sm text-secondary"><%= t("settings.classifiers.evaluation.none") %></p>
+ <% end %>
+</div>
diff --git a/app/views/settings/classifiers/_matcher.html.erb b/app/views/settings/classifiers/_matcher.html.erb
new file mode 100644
index 0000000000..dea09fee7c
--- /dev/null
+++ b/app/views/settings/classifiers/_matcher.html.erb
@@ -0,0 +1,14 @@
+<%# locals: (settings:, active:) %>
+<%# The matcher: its rule's switch (filling in missing merchants from
+ near-duplicates, in the rule order), how alike they must be (also set by
+ Auto-tune's Apply), and whether it locks them. %>
+<div class="space-y-4">
+ <%= render "settings/classifiers/rule_toggle", action_type: "fill_similar_merchants", active: active,
+ label: t(".rule"), hint: t(".rule_hint") %>
+ <%= classifier_section_form do %>
+ <%= render "settings/classifiers/number", key: :similar_threshold, settings: settings,
+ attrs: { step: 0.01 },
+ label: t(".similar_threshold"), hint: t(".similar_threshold_hint") %>
+ <%= render "settings/classifiers/toggle", key: :lock_similar_merchants, settings: settings, label: t(".lock_similar_merchants"), hint: t(".lock_similar_merchants_hint") %>
+ <% end %>
+</div>
diff --git a/app/views/settings/classifiers/_matcher_tuning.html.erb b/app/views/settings/classifiers/_matcher_tuning.html.erb
new file mode 100644
index 0000000000..c1732b80fb
--- /dev/null
+++ b/app/views/settings/classifiers/_matcher_tuning.html.erb
@@ -0,0 +1,14 @@
+<%# locals: (settings:) %>
+<%# How many near-duplicates must agree on a merchant, which words are too
+ common to count, and what it copies from. %>
+<%= classifier_section_form do |form| %>
+ <%= render "settings/classifiers/select", form: form, key: :similar_min_neighbours, settings: settings,
+ choices: Family::BayesSettings::STEPS[:similar_min_neighbours].map { |n| [ t(".similar_min_neighbours_option", count: n), n ] },
+ label: t(".similar_min_neighbours"), hint: t(".similar_min_neighbours_hint") %>
+ <%= render "settings/classifiers/number", key: :similar_common_share, settings: settings,
+ attrs: { step: 0.01 },
+ label: t(".similar_common_share"), hint: t(".similar_common_share_hint") %>
+ <%= render "settings/classifiers/option", key: :similar_skip_self, settings: settings,
+ number_key: :similar_self_grace_days,
+ label: t(".similar_skip_self"), hint: t(".similar_skip_self_hint") %>
+<% end %>
diff --git a/app/views/settings/classifiers/_merchant.html.erb b/app/views/settings/classifiers/_merchant.html.erb
new file mode 100644
index 0000000000..8f833e736b
--- /dev/null
+++ b/app/views/settings/classifiers/_merchant.html.erb
@@ -0,0 +1,7 @@
+<%# locals: (settings:) %>
+<%# The merchant's two forms: its name as words (the original), and its identity
+ as one token. %>
+<%= classifier_section_form do %>
+ <%= render "settings/classifiers/option", key: :merchant_name_words, settings: settings, label: t(".merchant_name_words"), hint: t(".merchant_name_words_hint") %>
+ <%= render "settings/classifiers/option", key: :merchant_field, settings: settings, label: t(".merchant_field"), hint: t(".merchant_field_hint") %>
+<% end %>
diff --git a/app/views/settings/classifiers/_mistakes.html.erb b/app/views/settings/classifiers/_mistakes.html.erb
new file mode 100644
index 0000000000..e71c48bf8c
--- /dev/null
+++ b/app/views/settings/classifiers/_mistakes.html.erb
@@ -0,0 +1,31 @@
+<%# locals: (confusions_title:, confusions:, no_confusions:, left_title:, left:, no_left:) %>
+<%# The most common mistakes, [[actual, predicted, count]], and what was
+ left unanswered, [[actual, count]], for one table's column. Side by side
+ when there's room, stacked on a phone. Absolute keys: also rendered from
+ BayesEvaluationJob. %>
+<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
+ <div class="space-y-1">
+ <p class="text-sm text-primary"><%= confusions_title %></p>
+ <% if confusions.empty? %>
+ <p class="text-xs text-secondary"><%= no_confusions %></p>
+ <% else %>
+ <ul class="text-sm text-secondary space-y-0.5">
+ <% confusions.each do |actual, predicted, count| %>
+ <li><span class="tabular-nums text-primary"><%= count %></span> <%= t("settings.classifiers.evaluation.confusion", actual: actual, predicted: predicted) %></li>
+ <% end %>
+ </ul>
+ <% end %>
+ </div>
+ <div class="space-y-1">
+ <p class="text-sm text-primary"><%= left_title %></p>
+ <% if left.empty? %>
+ <p class="text-xs text-secondary"><%= no_left %></p>
+ <% else %>
+ <ul class="text-sm text-secondary space-y-0.5">
+ <% left.each do |actual, count| %>
+ <li><span class="tabular-nums text-primary"><%= count %></span> <%= actual %></li>
+ <% end %>
+ </ul>
+ <% end %>
+ </div>
+</div>
diff --git a/app/views/settings/classifiers/_number.html.erb b/app/views/settings/classifiers/_number.html.erb
new file mode 100644
index 0000000000..b4a4ff4369
--- /dev/null
+++ b/app/views/settings/classifiers/_number.html.erb
@@ -0,0 +1,14 @@
+<%# locals: (key:, label:, hint:, settings:, attrs: {}) %>
+<%# One number row of Settings → Classifier. A blank number goes back to its
+ default; min and max come from Family::BayesSettings::RANGES. %>
+<% range = Family::BayesSettings::RANGES[key] %>
+<div class="flex items-center justify-between gap-x-4">
+ <div class="flex-1 min-w-0">
+ <p class="text-sm text-primary"><%= label %></p>
+ <p class="text-xs text-secondary"><%= hint %></p>
+ </div>
+ <%= number_field_tag "bayes_settings[#{key}]", settings.public_send(key),
+ id: nil, autocomplete: "off", aria: { label: label },
+ class: "rounded-lg border border-primary px-3 py-1.5 text-sm bg-container text-primary w-36 shrink-0",
+ data: { auto_submit_form_target: "auto" }, min: range&.min, max: range&.max, **attrs %>
+</div>
diff --git a/app/views/settings/classifiers/_option.html.erb b/app/views/settings/classifiers/_option.html.erb
new file mode 100644
index 0000000000..5e0f405319
--- /dev/null
+++ b/app/views/settings/classifiers/_option.html.erb
@@ -0,0 +1,27 @@
+<%# locals: (key:, label:, hint:, settings:, disabled: false, indent: false, number_key: nil, number_attrs: {}) %>
+<%# One checkbox row of Settings → Classifier, inside a section's
+ auto-submitting form. The hidden "0" makes unchecking submit; a disabled
+ row (its parent option is off) submits nothing, so its value is kept.
+ number_key adds the row's own number (e.g. a grace period in days), its
+ min and max from Family::BayesSettings::RANGES. %>
+<div class="<%= class_names("flex flex-1 items-center justify-between gap-x-4 min-w-0", "pl-6" => indent) %>">
+ <label class="flex flex-1 items-start gap-2 cursor-pointer min-w-0">
+ <%= hidden_field_tag "bayes_settings[#{key}]", "0", id: nil, disabled: disabled %>
+ <%= check_box_tag "bayes_settings[#{key}]", "1", settings.public_send(key),
+ id: nil, disabled: disabled,
+ class: "checkbox checkbox--light mt-0.5",
+ data: { auto_submit_form_target: "auto" } %>
+ <span class="min-w-0">
+ <span class="text-sm text-primary"><%= label %></span>
+ <span class="block text-xs text-secondary"><%= hint %></span>
+ </span>
+ </label>
+ <% if number_key %>
+ <% range = Family::BayesSettings::RANGES[number_key] %>
+ <%= number_field_tag "bayes_settings[#{number_key}]", settings.public_send(number_key),
+ id: nil, disabled: disabled || !settings.public_send(key), autocomplete: "off",
+ class: "rounded-lg border border-primary px-3 py-1.5 text-sm bg-container text-primary w-36 shrink-0",
+ aria: { label: label },
+ data: { auto_submit_form_target: "auto" }, min: range&.min, max: range&.max, **number_attrs %>
+ <% end %>
+</div>
diff --git a/app/views/settings/classifiers/_rule_toggle.html.erb b/app/views/settings/classifiers/_rule_toggle.html.erb
new file mode 100644
index 0000000000..1964039e2c
--- /dev/null
+++ b/app/views/settings/classifiers/_rule_toggle.html.erb
@@ -0,0 +1,9 @@
+<%# locals: (action_type:, active:, label:, hint:) %>
+<%# The switch of the matcher's or Bayes' rule (Family::CLASSIFIER_ACTION_TYPES),
+ on and off with that rule on the Rules page. Its own form: it saves the
+ rule, not the settings. %>
+<%= form_with url: rule_settings_classifier_path, method: :patch,
+ data: { controller: "auto-submit-form", auto_submit_form_trigger_event_value: "change" } do %>
+ <%= hidden_field_tag :action_type, action_type, id: nil %>
+ <%= render "settings/classifiers/toggle", key: "#{action_type}_rule", name: "active", checked: active, label: label, hint: hint %>
+<% end %>
diff --git a/app/views/settings/classifiers/_scoring.html.erb b/app/views/settings/classifiers/_scoring.html.erb
new file mode 100644
index 0000000000..3753724f51
--- /dev/null
+++ b/app/views/settings/classifiers/_scoring.html.erb
@@ -0,0 +1,11 @@
+<%# locals: (settings:) %>
+<%# Most important first: the method and its smoothing, then how the fields
+ and the categories' sizes weigh in. %>
+<%= classifier_section_form do %>
+ <%= render "settings/classifiers/option", key: :complement, settings: settings, label: t(".complement"), hint: t(".complement_hint") %>
+ <%= render "settings/classifiers/number", key: :smoothing, settings: settings,
+ attrs: { step: "any" }, label: t(".smoothing"), hint: t(".smoothing_hint") %>
+ <%= render "settings/classifiers/option", key: :separate_fields, settings: settings, disabled: !(settings.merchant_field || settings.account_field),
+ label: t(".separate_fields"), hint: t(".separate_fields_hint") %>
+ <%= render "settings/classifiers/option", key: :prior, settings: settings, label: t(".prior"), hint: t(".prior_hint") %>
+<% end %>
diff --git a/app/views/settings/classifiers/_select.html.erb b/app/views/settings/classifiers/_select.html.erb
new file mode 100644
index 0000000000..0867e83d17
--- /dev/null
+++ b/app/views/settings/classifiers/_select.html.erb
@@ -0,0 +1,13 @@
+<%# locals: (form:, key:, label:, hint:, settings:, choices:, width: "w-36") %>
+<%# One dropdown row of Settings → Classifier; choices: [[label, value]].
+ DS::Select submits its auto-submitting form when a choice is picked. %>
+<div class="flex items-center justify-between gap-x-4">
+ <div class="flex-1 min-w-0">
+ <label for="<%= key %>_trigger" class="block text-sm text-primary"><%= label %></label>
+ <p class="text-xs text-secondary"><%= hint %></p>
+ </div>
+ <div class="<%= width %> shrink-0">
+ <%= render DS::Select.new(form: form, method: key, selected: settings.public_send(key),
+ items: choices.map { |choice_label, value| { value: value, label: choice_label } }) %>
+ </div>
+</div>
diff --git a/app/views/settings/classifiers/_sweep_table.html.erb b/app/views/settings/classifiers/_sweep_table.html.erb
new file mode 100644
index 0000000000..be27c8d9b4
--- /dev/null
+++ b/app/views/settings/classifiers/_sweep_table.html.erb
@@ -0,0 +1,21 @@
+<%# locals: (columns:, weight:, label: t("settings.classifiers.evaluation.threshold")) %>
+<%# columns: [[heading, report]]; label heads the first column, the value
+ each row is at. Each cell is right / wrong; each column's best row for the
+ cost of a mistake, weight, is bold. %>
+<% rows_by_threshold = columns.map { |_, report| report["sweep"].index_by { |row| row["threshold"] } } %>
+<% bolds = columns.map { |_, report| Family::BayesEvaluation.best_threshold(report["sweep"], weight) if report["sweep"].any? } %>
+<div class="space-y-1">
+ <%= render DS::Table.new(rows: rows_by_threshold.flat_map(&:keys).uniq.sort, inset: true, label: label) do |table| %>
+ <% table.with_column(label, numeric: true, row_header: true) { |threshold| threshold.to_s } %>
+ <% columns.each_with_index do |(heading, _), i| %>
+ <% table.with_column(heading, numeric: true) do |threshold| %>
+ <% if (cell = rows_by_threshold[i][threshold]) %>
+ <span class="<%= "font-medium" if threshold == bolds[i] %>"><%= cell["right"] %> / <span class="text-destructive"><%= cell["wrong"] %></span></span>
+ <% else %>
+ –
+ <% end %>
+ <% end %>
+ <% end %>
+ <% end %>
+ <p class="text-xs text-secondary"><%= t("settings.classifiers.evaluation.right_wrong") %></p>
+</div>
diff --git a/app/views/settings/classifiers/_toggle.html.erb b/app/views/settings/classifiers/_toggle.html.erb
new file mode 100644
index 0000000000..b7ae880ab8
--- /dev/null
+++ b/app/views/settings/classifiers/_toggle.html.erb
@@ -0,0 +1,18 @@
+<%# locals: (key:, label:, hint:, settings: nil, name: "bayes_settings[#{key}]", checked: settings.public_send(key)) %>
+<%# One switch row of Settings → Classifier, for a setting that changes what's
+ stored, inside a section's auto-submitting form; a rule's switch passes
+ its own name and state (rule_toggle). DS::Toggle submits its own off
+ value. %>
+<div class="flex items-center justify-between gap-x-4">
+ <span class="min-w-0">
+ <span class="text-sm text-primary"><%= label %></span>
+ <span class="block text-xs text-secondary"><%= hint %></span>
+ </span>
+ <%= render DS::Toggle.new(
+ id: "bayes_settings_#{key}",
+ name: name,
+ checked: checked,
+ aria: { label: label },
+ data: { auto_submit_form_target: "auto" }
+ ) %>
+</div>
diff --git a/app/views/settings/classifiers/_training.html.erb b/app/views/settings/classifiers/_training.html.erb
new file mode 100644
index 0000000000..604909dd3f
--- /dev/null
+++ b/app/views/settings/classifiers/_training.html.erb
@@ -0,0 +1,8 @@
+<%# locals: (settings:) %>
+<%# How many of the newest transactions the classifier learns from and the
+ matcher copies from: one setting for both. %>
+<%= classifier_section_form do %>
+ <%= render "settings/classifiers/number", key: :max_training_transactions, settings: settings,
+ attrs: { step: 100 },
+ label: t(".max_training_transactions"), hint: t(".max_training_transactions_hint") %>
+<% end %>
diff --git a/app/views/settings/classifiers/_words.html.erb b/app/views/settings/classifiers/_words.html.erb
new file mode 100644
index 0000000000..b6068d338b
--- /dev/null
+++ b/app/views/settings/classifiers/_words.html.erb
@@ -0,0 +1,22 @@
+<%# locals: (settings:) %>
+<%# In the order the text is handled: what's read, how it splits into
+ words, which words are dropped, then how they're counted. Splitting
+ comes before dropping: split with symbols, mcdonald's stays whole, so
+ there's no "s" to drop. %>
+<%= classifier_section_form do |form| %>
+ <%= render "settings/classifiers/option", key: :include_notes, settings: settings, label: t(".include_notes"), hint: t(".include_notes_hint") %>
+
+ <%= render "settings/classifiers/select", form: form, key: :word_split, settings: settings, width: "w-64 max-w-1/2",
+ choices: Family::BayesSettings::CHOICES[:word_split].map { |choice| [ t(".word_split_#{choice}"), choice ] },
+ label: t(".word_split"), hint: t(".word_split_hint") %>
+
+ <%= render "settings/classifiers/option", key: :drop_numbers, settings: settings, label: t(".drop_numbers"), hint: t(".drop_numbers_hint") %>
+ <%= render "settings/classifiers/option", key: :keep_single_chars, settings: settings, label: t(".keep_single_chars"), hint: t(".keep_single_chars_hint") %>
+ <%= render "settings/classifiers/option", key: :drop_codes, settings: settings, label: t(".drop_codes"), hint: t(".drop_codes_hint") %>
+ <%= render "settings/classifiers/option", key: :spread_filter, settings: settings,
+ number_key: :spread_margin, number_attrs: { step: 0.05 },
+ label: t(".spread_filter"), hint: t(".spread_filter_hint") %>
+
+ <%= render "settings/classifiers/option", key: :binary, settings: settings, label: t(".binary"), hint: t(".binary_hint") %>
+ <%= render "settings/classifiers/option", key: :bigrams, settings: settings, label: t(".bigrams"), hint: t(".bigrams_hint") %>
+<% end %>
diff --git a/app/views/settings/classifiers/show.html.erb b/app/views/settings/classifiers/show.html.erb
new file mode 100644
index 0000000000..b7faeb5e86
--- /dev/null
+++ b/app/views/settings/classifiers/show.html.erb
@@ -0,0 +1,69 @@
+<%= content_for :page_title, t(".title") %>
+<%= content_for :page_actions do %>
+ <%= render DS::Menu.new do |menu| %>
+ <% menu.with_item(
+ variant: "button",
+ text: t(".clear_locks"),
+ href: clear_locks_settings_classifier_path,
+ icon: "unlock",
+ method: :post,
+ confirm: CustomConfirm.new(
+ title: t(".clear_locks_confirm_title"),
+ body: t(".clear_locks_confirm_body"),
+ btn_text: t(".clear_locks_confirm_button")
+ )) %>
+ <% end %>
+ <%= render DS::Button.new(
+ text: t(".run"),
+ variant: "secondary",
+ href: run_settings_classifier_path,
+ method: :post,
+ icon: "play"
+ ) %>
+<% end %>
+<%= settings_section title: t(".title"), subtitle: t(".description") do %>
+ <%= render "settings/classifiers/classifier", settings: @settings, active: @rules_active["bayes_categorize"] %>
+<% end %>
+<%= settings_section title: t(".matcher"), subtitle: t(".matcher_description") do %>
+ <%= render "settings/classifiers/matcher", settings: @settings, active: @rules_active["fill_similar_merchants"] %>
+<% end %>
+<%= settings_section title: t(".auto_tune") do %>
+ <%= render "settings/classifiers/evaluation", evaluation: @evaluation, settings: @settings, running: @evaluation_running, weight: @weight %>
+<% end %>
+<%= settings_section title: t(".training") do %>
+ <%= render "settings/classifiers/training", settings: @settings %>
+<% end %>
+<%= settings_section title: t(".category_training") do %>
+ <%= render "settings/classifiers/category_training", settings: @settings, categories: @categories %>
+<% end %>
+<%= settings_section title: t(".matcher_tuning") do %>
+ <%= render "settings/classifiers/matcher_tuning", settings: @settings %>
+<% end %>
+<%= settings_section title: t(".words") do %>
+ <%= render "settings/classifiers/words", settings: @settings %>
+<% end %>
+<%= settings_section title: t(".merchant") do %>
+ <%= render "settings/classifiers/merchant", settings: @settings %>
+<% end %>
+<%= settings_section title: t(".amount") do %>
+ <%= render "settings/classifiers/amount", settings: @settings %>
+<% end %>
+<%= settings_section title: t(".account") do %>
+ <%= render "settings/classifiers/account", settings: @settings %>
+<% end %>
+<%= settings_section title: t(".scoring") do %>
+ <%= render "settings/classifiers/scoring", settings: @settings %>
+<% end %>
+
+<% if @add_rule %>
+ <%# Turning on a switch whose rule was deleted (rule): add it again? %>
+ <% name = Family.classifier_rule_name(@add_rule) %>
+ <%= render DS::Dialog.new(disable_frame: true, width: "md") do |dialog| %>
+ <% dialog.with_header(title: t(".add_rule_title", name: name)) %>
+ <% dialog.with_body do %>
+ <p class="text-sm text-secondary"><%= t(".add_rule_body", name: name) %></p>
+ <% end %>
+ <% dialog.with_action(cancel_action: true, text: t(".add_rule_cancel"), variant: "outline") %>
+ <% dialog.with_action(text: t(".add_rule_confirm"), href: add_rule_settings_classifier_path, method: :post, params: { action_type: @add_rule }) %>
+ <% end %>
+<% end %>
diff --git a/config/locales/breadcrumbs/en.yml b/config/locales/breadcrumbs/en.yml
index 06e635e164..4d4c0e77fc 100644
--- a/config/locales/breadcrumbs/en.yml
+++ b/config/locales/breadcrumbs/en.yml
@@ -18,6 +18,7 @@ en:
categorize: Categorize
changelog: What's new
chats: Chats
+ classifier: Classifier
coinbase_items: Coinbase
coinstats_items: CoinStats
credit_cards: Credit cards
diff --git a/config/locales/views/rules/en.yml b/config/locales/views/rules/en.yml
index 9774bbfb0f..718506fd02 100644
--- a/config/locales/views/rules/en.yml
+++ b/config/locales/views/rules/en.yml
@@ -12,6 +12,9 @@ en:
hide_for_today: Hide for today
hide_for_today_hint: "Hide for today pauses these suggestions for 24 hours."
message: Updated to %{category_name}
+ classifier_rules:
+ category_classifier: Category classifier
+ merchant_matcher: Merchant matcher
rule:
edit: Edit
re_apply_rule: Re-apply rule
diff --git a/config/locales/views/settings/classifiers/en.yml b/config/locales/views/settings/classifiers/en.yml
new file mode 100644
index 0000000000..602f3bd4eb
--- /dev/null
+++ b/config/locales/views/settings/classifiers/en.yml
@@ -0,0 +1,156 @@
+---
+en:
+ settings:
+ classifiers:
+ account:
+ account_field: Include the account as one token
+ account_field_hint: "Which account a transaction is in counts as evidence. It never decides alone: a transaction needs a known word or merchant."
+ amount:
+ amount_by_direction: Include the direction, money in or out
+ amount_by_direction_hint: Each category learns which way its money goes, and refunds and purchases at the same shop stay apart.
+ amount_field: Include the amount
+ amount_field_hint: Compares the amount with each category's usual amounts in the same currency, on a log scale.
+ category_training:
+ apply: Apply
+ categories: Categories
+ categories_all: All categories
+ categories_hint: Unchecked categories, with their subcategories, are left out of training, so Bayes never picks them.
+ categories_some: "%{count} of %{total} categories"
+ exclude_transfers: Exclude transfers
+ exclude_transfers_hint: Transfers and payments between your accounts.
+ search_categories: Search categories
+ skip_self_labels: Don't learn from Bayes' own guesses until confirmed or this many days old
+ skip_self_labels_hint: Confirmed means you changed or locked it. A wrong guess isn't fed back in and reinforced; one left alone that long counts as accepted.
+ add_rule:
+ success: The %{name} rule was added to the top of your rules.
+ classifier:
+ apply: Apply
+ lock_results: Lock the categories the classifier sets
+ lock_results_hint: Stops rules changing Bayes' picks, unless you click Apply on a rule. AI never changes Bayes' picks, locked or not.
+ rule: Categorize with the classifier
+ rule_hint: The Category classifier rule, on and off with it in Rules. It categorizes uncategorized transactions in your rule order, after each sync; what it isn't sure about is left for an Auto-categorize rule.
+ threshold: Threshold
+ threshold_hint: Lowest score Bayes acts on (0.05–0.99). Lower categorizes more, with more mistakes.
+ clear_locks:
+ success: Bayes' locks are being cleared. This may take a few moments.
+ evaluation:
+ apply_best: Apply these settings
+ best: Best found
+ best_changes: "Best found, changed from yours:"
+ best_no_changes: Nothing scored better than your settings.
+ buttons_hint: "Test my settings scores your settings. Find best settings searches the %{tuning} months before the ones shown, so what it finds is scored on months it didn't see. It judges by ROC-AUC: how well the scores rank each category's transactions above the rest, at any threshold, keeping a change only when it's higher overall and in all but one of those %{tuning} months alone. It first picks the inputs (every combination of the merchant token, amount and account; then scoring the merchant and account apart; then the merchant's name and the notes as words), then tries one change at a time to the other settings, and last to Scoring. Defaults are the original classifier's, with your choice of categories; Reset to defaults switches to them and tests them."
+ categories_heading: Category classifier
+ change: "%{setting}: %{value}"
+ confusion: "%{actual} → %{predicted}"
+ confusions: "Most common mistakes: %{column} at %{threshold}"
+ current: My settings
+ defaults: Defaults
+ description: Each column is scored on the last %{months} months as new transactions, each month trained on the history before it, then compared with your categories. Testing changes no transaction's category, and the classifier settings change only when you apply or reset.
+ find_best: Find best settings
+ matcher_confusions: "Most common merchant mistakes: %{column} at %{similarity}"
+ matcher_description: "Merchants the matcher fills on the same %{months} months: %{count} transactions with a merchant, each matched against the history before its month with its merchant hidden; right is the merchant it has. Every cutoff and number of merchants is scored; Best found is the one with the best cell for the cost of a mistake, which Apply sets. Testing fills in no merchants."
+ merchants_heading: Merchant matcher
+ no_confusions: No mistakes at this threshold.
+ no_matcher_confusions: No merchant mistakes at this similarity.
+ no_uncategorized: Nothing left uncategorized at this threshold.
+ no_unfilled: Nothing left without a merchant at this similarity.
+ none: Not tested yet.
+ "off": "off"
+ "on": "on"
+ ran_at: Scored %{time} ago on %{count} transactions (%{months}).
+ reset: Reset to defaults
+ reset_confirm: Reset every classifier setting to its default, and test them?
+ right_wrong: Each cell is right / wrong.
+ run: Test my settings
+ running: Testing… this section updates when it's done.
+ short_history: Not enough history to tune the category classifier yet. This needs about %{months} months of categorized transactions, so Apply leaves its settings alone for now.
+ similarity: Similarity
+ stale: The settings have changed since this test.
+ threshold: Threshold
+ trying: "Trying %{changes}…"
+ uncategorized: "Most common uncategorized: %{column} at %{threshold}"
+ unfilled: "Most common unfilled: %{column} at %{similarity}"
+ weight: A mistake costs
+ weight_hint: "Picks what Apply sets: the bold cells, where right answers minus this many per mistake is highest. Best found's threshold for categories; the cutoff, similarity and number of merchants for the matcher."
+ weight_option:
+ one: 1 right answer
+ other: "%{count} right answers"
+ matcher:
+ lock_similar_merchants: Lock the merchants the matcher sets
+ lock_similar_merchants_hint: Stops rules, AI and syncs changing them, unless you click Apply on a rule. Its own locks don't count as confirmed (Merchant matcher tuning).
+ rule: Fill in missing merchants from near-duplicates
+ rule_hint: "The Merchant matcher rule, on and off with it in Rules. In your rule order, a transaction without a merchant gets the one its near-duplicates, like \"NETFLIX.COM 8812\" and \"Netflix com\", all have. Transfers are left out."
+ similar_threshold: Similarity
+ similar_threshold_hint: Lowest similarity of the descriptions, ignoring numbers and reference codes (0.5–0.99). Lower fills more, with more mistakes. Auto-tune's Apply sets it too.
+ matcher_tuning:
+ similar_common_share: Cutoff
+ similar_common_share_hint: A word or 3-letter piece in more than this share of the transactions it copies from (0.01–1), and in at least 50 of them, is too common to tell them apart, like "card" or "payment", so it's ignored. Higher counts more of them. Auto-tune's Apply sets it too.
+ similar_min_neighbours: Merchants agreeing
+ similar_min_neighbours_hint: How many near-duplicates must have the merchant, with none having another. 1 copies a single transaction, mistakes too.
+ similar_min_neighbours_option:
+ one: 1 merchant
+ other: "%{count} merchants"
+ similar_skip_self: Don't copy from the matcher's own merchants until confirmed or this many days old
+ similar_skip_self_hint: Confirmed means you changed or locked it. A wrong copy isn't spread; one left alone that long counts as accepted.
+ merchant:
+ merchant_field: Include the merchant as one token, when set
+ merchant_field_hint: Counts by identity, so a renamed merchant keeps its history.
+ merchant_name_words: Include the merchant's name as words
+ merchant_name_words_hint: Read like the description, as the original does, so similar names share evidence. Overlaps with the token below.
+ run:
+ success: Bayes is categorizing uncategorized transactions. This may take a few moments.
+ scoring:
+ complement: Use complement naive Bayes
+ complement_hint: Scores each category by how badly the transaction fits the others, which copes better with categories of very different sizes. Off is the original multinomial.
+ prior: Include how often each category is used
+ prior_hint: Leans towards the categories you use most. Off treats every category alike, as the original does.
+ separate_fields: Score the merchant and account apart from the words
+ separate_fields_hint: Each gets its own distribution, so a long description doesn't outweigh them. Needs the merchant or the account included; the amount is always scored on its own.
+ smoothing: Smoothing
+ smoothing_hint: Added to every count so an unseen word doesn't rule a category out (0.001–10). 1 is the original's; lower trusts what's been seen more.
+ show:
+ add_rule_body: There's no %{name} rule in your rules, so there's nothing to turn on. Add it to the top of your rules?
+ add_rule_cancel: "No"
+ add_rule_confirm: Add rule
+ add_rule_title: Add the %{name} rule?
+ account: Account tuning
+ amount: Amount tuning
+ auto_tune: Auto-tune
+ category_training: Category classifier tuning
+ clear_locks: Clear Bayes locks
+ clear_locks_confirm_body: Unlocks the categories Bayes locked and the merchants the matcher locked that are still what they set, so rules and AI can change them again. The categories and merchants stay.
+ clear_locks_confirm_button: Clear locks
+ clear_locks_confirm_title: Clear Bayes locks?
+ description: The Bayes category classifier learns from your categorized transactions and categorizes new ones before any AI provider. Changes to these settings take effect from the next categorization run; transactions already categorized keep their categories.
+ matcher: Matcher
+ matcher_description: Fills in missing merchants from near-duplicates, as the Merchant matcher rule (after each sync) and on Run. It changes the merchants stored.
+ matcher_tuning: Merchant matcher tuning
+ merchant: Merchant tuning
+ run: Run
+ scoring: Scoring
+ title: Classifier
+ training: Training
+ words: Transaction tuning
+ training:
+ max_training_transactions: Training transactions
+ max_training_transactions_hint: "How many of the newest transactions to use (100–20,000): the categorized ones the classifier learns from, and the ones with a merchant the matcher copies from."
+ words:
+ bigrams: Include word pairs
+ bigrams_hint: "Neighbouring words also count together, like \"card payment\"."
+ binary: Exclude repeated words
+ binary_hint: Each word counts once per transaction.
+ drop_codes: Exclude reference codes
+ drop_codes_hint: Words mixing letters with 2 or more digits, like 2k4l19.
+ drop_numbers: Exclude numbers
+ drop_numbers_hint: Store numbers, dates and amounts in the description.
+ include_notes: Include notes
+ include_notes_hint: Reads the notes as well as the name.
+ keep_single_chars: Include one-character words
+ keep_single_chars_hint: "Single letters and digits left after splitting, like the \"s\" of mcdonald's."
+ spread_filter: Exclude words every category uses alike
+ spread_filter_hint: They say nothing about the category. The number is how far above an even share one category's use must be.
+ word_split: Words are made of
+ word_split_ascii: a–z and 0–9
+ word_split_hint: "Every other character splits words. Letters of any script keep words like Geschäft or Кофейня whole; with inner symbols, letters joined by one symbol stay one word too, like mcdonald's, s/o and m&s (a symbol at either end, as in *netflix, is still dropped)."
+ word_split_symbols: Letters, digits, inner symbols
+ word_split_unicode: Letters and digits, any script
diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml
index 6920d94c32..7b2b6e373d 100644
--- a/config/locales/views/settings/en.yml
+++ b/config/locales/views/settings/en.yml
@@ -359,6 +359,7 @@ en:
accounts_label: Accounts
advanced_section_title: Advanced
ai_prompts_label: AI Prompts
+ classifier_label: Classifier
background_jobs_label: Background jobs
api_key_label: API Keys
payment_label: Payment
diff --git a/config/routes.rb b/config/routes.rb
index 09f126aa8d..e0cfda3df8 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -404,6 +404,16 @@ Rails.application.routes.draw do
delete "tokens/:token_id", to: "mcp#revoke", as: :revoke_token
end
resource :ai_prompts, only: %i[show update]
+ resource :classifier, only: %i[show update] do
+ patch :rule
+ post :add_rule
+ post :run
+ post :clear_locks
+ post :evaluate
+ post :find_best
+ post :remember_weight
+ patch :apply_best
+ end
resource :llm_usage, only: :show
resource :guides, only: :show
get "bank_sync", to: redirect("/settings/providers", status: 301)
diff --git a/db/migrate/20261017120000_add_bayes_settings_to_families.rb b/db/migrate/20261017120000_add_bayes_settings_to_families.rb
new file mode 100644
index 0000000000..9fcca40b69
--- /dev/null
+++ b/db/migrate/20261017120000_add_bayes_settings_to_families.rb
@@ -0,0 +1,5 @@
+class AddBayesSettingsToFamilies < ActiveRecord::Migration[8.1]
+ def change
+ add_column :families, :bayes_settings, :jsonb, default: {}, null: false
+ end
+end
diff --git a/db/migrate/20261020090000_add_classifier_rules.rb b/db/migrate/20261020090000_add_classifier_rules.rb
new file mode 100644
index 0000000000..d4460cedc4
--- /dev/null
+++ b/db/migrate/20261020090000_add_classifier_rules.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+# The merchant matcher and Bayes become rules, Merchant matcher and Category
+# classifier, at the top of every family's order (users can move them). Each
+# is on where the family already has an active rule doing the same with AI,
+# so only families paying for that get the free step before it. Their old
+# on/off settings go, and the account filter: a rule's conditions choose
+# accounts now.
+class AddClassifierRules < ActiveRecord::Migration[8.1]
+ RULES = [
+ # action_type, name, position, the AI action that turns it on
+ [ "fill_similar_merchants", "Merchant matcher", 1, "auto_detect_merchants" ],
+ [ "bayes_categorize", "Category classifier", 2, "auto_categorize" ]
+ ].freeze
+
+ def up
+ execute "UPDATE rules SET position = position + #{RULES.size}"
+
+ RULES.each do |action_type, name, position, ai_action_type|
+ execute <<~SQL
+ WITH added AS (
+ INSERT INTO rules (family_id, name, resource_type, active, position, created_at, updated_at)
+ SELECT families.id, #{connection.quote(name)}, 'transaction',
+ EXISTS (
+ SELECT 1 FROM rules ai_rules
+ JOIN rule_actions ON rule_actions.rule_id = ai_rules.id
+ WHERE ai_rules.family_id = families.id AND ai_rules.active
+ AND rule_actions.action_type = #{connection.quote(ai_action_type)}
+ ),
+ #{position}, NOW(), NOW()
+ FROM families
+ RETURNING id
+ )
+ INSERT INTO rule_actions (rule_id, action_type, created_at, updated_at)
+ SELECT id, #{connection.quote(action_type)}, NOW(), NOW() FROM added
+ SQL
+ end
+
+ execute "UPDATE families SET bayes_settings = bayes_settings - 'categorize_after_sync' - 'fill_similar_merchants' - 'excluded_account_ids'"
+ end
+
+ # Removes the two actions, and the rules left without one, then numbers
+ # each family's rules 1… again in their order.
+ def down
+ action_types = RULES.map { |action_type, *| connection.quote(action_type) }.join(", ")
+ execute "DELETE FROM rule_actions WHERE action_type IN (#{action_types})"
+ emptied = "SELECT id FROM rules WHERE NOT EXISTS (SELECT 1 FROM rule_actions WHERE rule_actions.rule_id = rules.id)"
+ execute "DELETE FROM rule_runs WHERE rule_id IN (#{emptied})"
+ execute "DELETE FROM rule_conditions WHERE rule_id IN (#{emptied})"
+ execute "DELETE FROM rules WHERE id IN (#{emptied})"
+ execute <<~SQL
+ UPDATE rules SET position = ranked.rn
+ FROM (SELECT id, ROW_NUMBER() OVER (PARTITION BY family_id ORDER BY position, created_at, id) AS rn FROM rules) ranked
+ WHERE rules.id = ranked.id
+ SQL
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index c0963b4c06..5973f38759 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -843,6 +843,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_20_090000) do
t.jsonb "ai_prompt_overrides", default: {}, null: false
t.string "assistant_type", default: "builtin", null: false
t.boolean "auto_sync_on_login", default: true, null: false
+ t.jsonb "bayes_settings", default: {}, null: false
t.string "bills_feed_token"
t.boolean "categories_locked", default: false, null: false
t.decimal "categorization_confidence_threshold", precision: 3, scale: 2, default: "0.7", null: false
diff --git a/test/controllers/settings/classifiers_controller_test.rb b/test/controllers/settings/classifiers_controller_test.rb
new file mode 100644
index 0000000000..a0955fb421
--- /dev/null
+++ b/test/controllers/settings/classifiers_controller_test.rb
@@ -0,0 +1,277 @@
+require "test_helper"
+
+class Settings::ClassifiersControllerTest < ActionDispatch::IntegrationTest
+ include ActiveJob::TestHelper
+
+ setup do
+ @admin = users(:family_admin)
+ @family = @admin.family
+ end
+
+ test "admin can view the classifier settings" do
+ sign_in @admin
+ get settings_classifier_path
+
+ assert_response :success
+ assert_select "input[type=checkbox][name='bayes_settings[merchant_name_words]'][checked]"
+ assert_select "input[type=hidden][name='bayes_settings[word_split]'][value='ascii']"
+ assert_select "input[name='bayes_settings[threshold]'][value='0.7']"
+ assert_select "input[name='included_category_ids[]']", count: @family.categories.count
+ assert_select "#classifier_evaluation"
+ # The fixture family has no classifier rules, so both switches are off.
+ assert_select "input[type=checkbox][role=switch][name='active']:not([checked])", count: 2
+ assert_select ".translation_missing", count: 0
+ assert_select "span", text: I18n.t("settings.classifiers.category_training.exclude_transfers_hint")
+ end
+
+ test "non-admin member cannot view the classifier settings" do
+ sign_in users(:family_member)
+ get settings_classifier_path
+
+ assert_redirected_to accounts_path
+ end
+
+ test "each section's update keeps the other sections' settings" do
+ sign_in @admin
+
+ patch settings_classifier_path, params: { bayes_settings: { bigrams: "1", threshold: "0.6" } }
+ patch settings_classifier_path, params: { bayes_settings: { complement: "1" } }
+
+ assert_redirected_to settings_classifier_path
+ settings = @family.reload.bayes_settings_object
+ assert settings.bigrams
+ assert_equal 0.6, settings.threshold
+ assert settings.complement
+ end
+
+ test "out-of-range values are clamped and unknown keys ignored" do
+ sign_in @admin
+
+ patch settings_classifier_path, params: { bayes_settings: { threshold: "5", max_training_transactions: "1", nonsense: "1" } }
+
+ assert_equal({ "threshold" => 0.99, "max_training_transactions" => 100 }, @family.reload.bayes_settings)
+ end
+
+ test "the category checklist saves what's unchecked, respecting the cascade" do
+ sign_in @admin
+ parent = @family.categories.create!(name: "Parent")
+ kept_child = @family.categories.create!(name: "Kept child", parent: parent)
+ dropped_child = @family.categories.create!(name: "Dropped child", parent: parent)
+ others = @family.categories.where.not(id: [ parent.id, kept_child.id, dropped_child.id ]).pluck(:id)
+
+ # A partly checked parent isn't submitted, but isn't excluded either.
+ patch settings_classifier_path, params: { category_filter: "1", included_category_ids: others + [ kept_child.id ] }
+
+ assert_equal [ dropped_child.id.to_s ], @family.reload.bayes_settings_object.excluded_category_ids
+ end
+
+ test "reset clears every setting and tests the defaults" do
+ @family.update_bayes_settings!(bigrams: "1")
+ sign_in @admin
+
+ assert_enqueued_with(job: BayesEvaluationJob, args: [ @family, { action: "reset" } ]) do
+ patch settings_classifier_path, params: { reset: "1" }
+ end
+
+ assert_equal({}, @family.reload.bayes_settings)
+ assert_redirected_to settings_classifier_path(anchor: "classifier_evaluation")
+ end
+
+ test "a rule's switch offers to add its rule when there's none, then turns it off and on" do
+ sign_in @admin
+ name = I18n.t("rules.classifier_rules.category_classifier")
+ title = I18n.t("settings.classifiers.show.add_rule_title", name: name)
+
+ patch rule_settings_classifier_path, params: { action_type: "bayes_categorize", active: "1" }
+ assert_redirected_to settings_classifier_path(add_rule: "bayes_categorize")
+ get settings_classifier_path(add_rule: "bayes_categorize")
+ assert_select "dialog", text: /#{Regexp.escape(title)}/
+
+ assert_difference -> { @family.rules.count }, 1 do
+ post add_rule_settings_classifier_path, params: { action_type: "bayes_categorize" }
+ end
+ rule = @family.classifier_rules("bayes_categorize").sole
+ assert rule.active?
+ assert_equal 1, rule.position
+
+ patch rule_settings_classifier_path, params: { action_type: "bayes_categorize", active: "0" }
+ assert_not rule.reload.active?
+ patch rule_settings_classifier_path, params: { action_type: "bayes_categorize", active: "1" }
+ assert rule.reload.active?
+ # With the rule there, the question isn't asked.
+ get settings_classifier_path(add_rule: "bayes_categorize")
+ assert_select "dialog", text: /#{Regexp.escape(title)}/, count: 0
+ end
+
+ test "a rule's switch only knows the matcher and Bayes" do
+ sign_in @admin
+
+ patch rule_settings_classifier_path, params: { action_type: "auto_categorize", active: "1" }
+
+ assert_response :bad_request
+ end
+
+ test "run and clear locks queue their jobs" do
+ sign_in @admin
+
+ assert_enqueued_with(job: BayesCategorizeJob, args: [ @family ]) do
+ post run_settings_classifier_path
+ end
+ assert_redirected_to settings_classifier_path
+
+ assert_enqueued_with(job: ClearBayesLocksJob, args: [ @family ]) do
+ post clear_locks_settings_classifier_path
+ end
+ assert_redirected_to settings_classifier_path
+ end
+
+ test "test my settings and find best settings queue their run" do
+ sign_in @admin
+
+ assert_enqueued_with(job: BayesEvaluationJob, args: [ @family, { action: "test" } ]) do
+ post evaluate_settings_classifier_path
+ end
+ assert_redirected_to settings_classifier_path(anchor: "classifier_evaluation")
+
+ assert_enqueued_with(job: BayesEvaluationJob, args: [ @family, { action: "find_best" } ]) do
+ post find_best_settings_classifier_path
+ end
+ end
+
+ test "no second run while one is running" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ sign_in @admin
+ Family::BayesEvaluation.mark_running!(@family)
+
+ assert_no_enqueued_jobs only: BayesEvaluationJob do
+ post evaluate_settings_classifier_path
+ post find_best_settings_classifier_path
+ end
+ assert_redirected_to settings_classifier_path(anchor: "classifier_evaluation")
+ end
+
+ test "the cost of a mistake is saved as it changes, within its range" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ sign_in @admin
+
+ assert_no_enqueued_jobs do
+ post remember_weight_settings_classifier_path, params: { weight: "9" }
+ end
+
+ assert_redirected_to settings_classifier_path(anchor: "classifier_evaluation")
+ assert_equal 3, Family::BayesEvaluation.weight(@family)
+ end
+
+ test "apply saves the matcher's best cell with Find best settings' result, and nothing after only a test" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ sign_in @admin
+ row = ->(similarity, right) { { "threshold" => similarity, "right" => right, "wrong" => 1 } }
+ tested = {
+ "version" => Family::BayesEvaluation::RESULT_VERSION, "digest" => @family.bayes_settings_object.digest,
+ "current" => { "threshold" => 0.7 },
+ "matcher" => { "n" => 12, "cutoffs" => { 0.1 => { 1 => [ row.call(0.9, 9) ], 2 => [ row.call(0.9, 8) ], 3 => [ row.call(0.85, 10), row.call(0.9, 7) ] } } }
+ }
+ Rails.cache.write(Family::BayesEvaluation.cache_key(@family), tested)
+
+ assert_no_enqueued_jobs do
+ patch apply_best_settings_classifier_path
+ end
+ assert_equal({}, @family.reload.bayes_settings)
+
+ # Find best found nothing better for the categories: only the matcher changes.
+ found = tested.merge("best" => { "changes" => {}, "report" => { "sweep" => [ { "threshold" => 0.7, "right" => 1, "wrong" => 0 } ] } })
+ Rails.cache.write(Family::BayesEvaluation.cache_key(@family), found)
+ assert_enqueued_with(job: BayesEvaluationJob, args: [ @family, { action: "test" } ]) do
+ patch apply_best_settings_classifier_path
+ end
+ assert_equal({ "similar_common_share" => 0.1, "similar_min_neighbours" => 3, "similar_threshold" => 0.85 }, @family.reload.bayes_settings)
+ end
+
+ test "the page shows the matcher's table, without Best found after a test" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ sign_in @admin
+ report = { "n" => 1, "threshold" => 0.7, "sweep" => [ { "threshold" => 0.7, "right" => 1, "wrong" => 0 } ], "confusions" => {}, "uncategorized" => {} }
+ sweep = [ { "threshold" => 0.9, "right" => 5, "wrong" => 1, "confusions" => [], "unfilled" => [] } ]
+ Rails.cache.write(Family::BayesEvaluation.cache_key(@family), {
+ "version" => Family::BayesEvaluation::RESULT_VERSION, "action" => "test", "digest" => @family.bayes_settings_object.digest,
+ "ran_at" => Time.current.iso8601, "months" => %w[2026-08 2026-09], "current" => report, "defaults" => report,
+ "matcher" => { "n" => 6, "cutoffs" => { 0.2 => { 1 => sweep, 2 => sweep, 3 => sweep } } }
+ })
+
+ get settings_classifier_path
+
+ # After a test, both tables have My settings and Defaults, and no Best found.
+ %w[current defaults].each { |column| assert_select "#classifier_evaluation th", text: I18n.t("settings.classifiers.evaluation.#{column}"), count: 2 }
+ assert_select "#classifier_evaluation th", text: I18n.t("settings.classifiers.evaluation.best"), count: 0
+ assert_select "#classifier_evaluation th", text: I18n.t("settings.classifiers.evaluation.similarity")
+ assert_select "h2", text: I18n.t("settings.classifiers.show.matcher_tuning")
+ # Each column's best row in bold: 0.7 in the category table's two, 0.9 in the matcher's.
+ assert_select "#classifier_evaluation td span.font-medium", count: 4
+ assert_select ".translation_missing", count: 0
+ end
+
+ test "the page shows the three columns, the buttons in their order, and the best found's mistakes" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ sign_in @admin
+ report = ->(threshold) {
+ { "n" => 10, "threshold" => threshold, "sweep" => [ { "threshold" => 0.4, "right" => 8, "wrong" => 1 }, { "threshold" => 0.8, "right" => 6, "wrong" => 0 } ],
+ "confusions" => { 0.4 => [ [ "Coffee", "Groceries", 1 ] ], 0.8 => [] }, "uncategorized" => { 0.4 => [ [ "Splurge", 2 ] ], 0.8 => [] } }
+ }
+ Rails.cache.write(Family::BayesEvaluation.cache_key(@family), {
+ "version" => Family::BayesEvaluation::RESULT_VERSION, "action" => "find_best", "digest" => @family.bayes_settings_object.digest,
+ "ran_at" => Time.current.iso8601, "months" => %w[2026-08 2026-09], "current" => report.call(0.7), "defaults" => report.call(0.7),
+ "best" => { "changes" => { "binary" => true }, "report" => report.call(0.7) }
+ })
+
+ get settings_classifier_path
+
+ assert_select "#classifier_evaluation th", text: I18n.t("settings.classifiers.evaluation.current")
+ assert_select "#classifier_evaluation th", text: I18n.t("settings.classifiers.evaluation.best")
+ assert_select "#classifier_evaluation th", text: I18n.t("settings.classifiers.evaluation.defaults")
+ buttons = css_select("#classifier_evaluation button").map { |button| button.text.strip }
+ labels = %w[run find_best reset apply_best].map { |key| I18n.t("settings.classifiers.evaluation.#{key}") }
+ assert_equal labels, buttons & labels
+ # At a cost of 1, 0.4 scores 7 and 0.8 scores 6: Apply would set 0.4.
+ assert_select "li", text: /Coffee → Groceries/
+ assert_select "li", text: /2\s+Splurge/
+ assert_select ".translation_missing", count: 0
+ end
+
+ test "with too little history the page warns and Apply stays off" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ sign_in @admin
+ report = { "n" => 0, "threshold" => 0.7, "sweep" => [ { "threshold" => 0.7, "right" => 0, "wrong" => 0 } ], "confusions" => {}, "uncategorized" => {} }
+ Rails.cache.write(Family::BayesEvaluation.cache_key(@family), {
+ "version" => Family::BayesEvaluation::RESULT_VERSION, "action" => "find_best", "digest" => @family.bayes_settings_object.digest,
+ "ran_at" => Time.current.iso8601, "months" => %w[2026-08 2026-09], "current" => report, "defaults" => report,
+ "best" => { "changes" => { "binary" => true }, "report" => report }, "short_history" => true
+ })
+
+ get settings_classifier_path
+
+ assert_select "#classifier_evaluation", text: /#{Regexp.escape(I18n.t("settings.classifiers.evaluation.short_history", months: Family::BayesEvaluation::MONTHS))}/
+ assert_select "#classifier_evaluation button[disabled]", text: I18n.t("settings.classifiers.evaluation.apply_best")
+ end
+
+ test "apply saves the best found at the threshold for the chosen cost and tests it, unless the settings changed since" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ sign_in @admin
+ best = { "changes" => { "binary" => true },
+ "report" => { "sweep" => [ { "threshold" => 0.4, "right" => 10, "wrong" => 2 }, { "threshold" => 0.8, "right" => 7, "wrong" => 0 } ] } }
+ result = { "version" => Family::BayesEvaluation::RESULT_VERSION, "current" => { "threshold" => 0.7 }, "best" => best }
+ Rails.cache.write(Family::BayesEvaluation.cache_key(@family), result.merge("digest" => "stale"))
+
+ assert_no_enqueued_jobs do
+ patch apply_best_settings_classifier_path
+ end
+ assert_equal({}, @family.reload.bayes_settings)
+
+ # A mistake costs 2: 0.4 scores 6, 0.8 scores 7.
+ Family::BayesEvaluation.remember_weight!(@family, 2)
+ Rails.cache.write(Family::BayesEvaluation.cache_key(@family), result.merge("digest" => @family.bayes_settings_object.digest))
+ assert_enqueued_with(job: BayesEvaluationJob, args: [ @family, { action: "test" } ]) do
+ patch apply_best_settings_classifier_path
+ end
+ assert_equal({ "threshold" => 0.8, "binary" => true }, @family.reload.bayes_settings)
+ end
+end
diff --git a/test/jobs/bayes_categorize_job_test.rb b/test/jobs/bayes_categorize_job_test.rb
new file mode 100644
index 0000000000..2c24eb46b3
--- /dev/null
+++ b/test/jobs/bayes_categorize_job_test.rb
@@ -0,0 +1,24 @@
+require "test_helper"
+
+class BayesCategorizeJobTest < ActiveJob::TestCase
+ setup do
+ @family = families(:empty)
+ end
+
+ test "Run fills merchants while the matcher's rule is on, then runs Bayes" do
+ @family.stubs(:classifier_rule_active?).with("fill_similar_merchants").returns(true)
+ sequence = sequence("run")
+ @family.expects(:fill_similar_merchants).in_sequence(sequence)
+ @family.expects(:bayes_categorize_uncategorized).in_sequence(sequence)
+
+ BayesCategorizeJob.perform_now(@family)
+ end
+
+ test "Run skips the matcher while its rule is off" do
+ @family.stubs(:classifier_rule_active?).with("fill_similar_merchants").returns(false)
+ @family.expects(:fill_similar_merchants).never
+ @family.expects(:bayes_categorize_uncategorized)
+
+ BayesCategorizeJob.perform_now(@family)
+ end
+end
diff --git a/test/jobs/bayes_evaluation_job_test.rb b/test/jobs/bayes_evaluation_job_test.rb
new file mode 100644
index 0000000000..e1ecbc932d
--- /dev/null
+++ b/test/jobs/bayes_evaluation_job_test.rb
@@ -0,0 +1,39 @@
+require "test_helper"
+
+class BayesEvaluationJobTest < ActiveJob::TestCase
+ test "runs the evaluation and replaces the page's results panel" do
+ family = families(:empty)
+ evaluation = { "digest" => family.bayes_settings_object.digest }
+ Family::BayesEvaluation.any_instance.expects(:run!).returns(evaluation)
+ Turbo::StreamsChannel.expects(:broadcast_replace_to).with do |*args|
+ options = args.last
+ args.first == family && options[:target] == "classifier_evaluation" && options[:locals][:evaluation] == evaluation
+ end
+
+ BayesEvaluationJob.perform_now(family)
+ end
+
+ test "a failed run puts the panel back on the last result and still raises" do
+ family = families(:empty)
+ cached = { "digest" => "earlier" }
+ Family::BayesEvaluation.stubs(:cached).with(family).returns(cached)
+ Family::BayesEvaluation.any_instance.expects(:run!).raises(ActiveRecord::QueryCanceled)
+ Turbo::StreamsChannel.expects(:broadcast_replace_to).with do |*args|
+ options = args.last
+ options[:target] == "classifier_evaluation" && options[:locals][:evaluation] == cached && options[:locals][:running] == false
+ end
+
+ assert_raises(ActiveRecord::QueryCanceled) { BayesEvaluationJob.perform_now(family) }
+ end
+
+ test "a search shows each change it tries" do
+ family = families(:empty)
+ Family::BayesEvaluation.any_instance.expects(:run!).with(action: "find_best").multiple_yields([ { binary: true } ], [ { smoothing: 0.1 } ], [ { word_split: "unicode", amount_field: true } ]).returns({})
+ Turbo::StreamsChannel.expects(:broadcast_update_to).with(family, target: "classifier_evaluation_progress", html: "Trying Exclude repeated words: on…")
+ Turbo::StreamsChannel.expects(:broadcast_update_to).with(family, target: "classifier_evaluation_progress", html: "Trying Smoothing: 0.1…")
+ Turbo::StreamsChannel.expects(:broadcast_update_to).with(family, target: "classifier_evaluation_progress", html: "Trying Words are made of: Letters and digits, any script; Include the amount: on…")
+ Turbo::StreamsChannel.expects(:broadcast_replace_to)
+
+ BayesEvaluationJob.perform_now(family, action: "find_best")
+ end
+end
diff --git a/test/models/category/cache_invalidation_concurrency_test.rb b/test/models/category/cache_invalidation_concurrency_test.rb
index f3f01d0d75..216e510734 100644
--- a/test/models/category/cache_invalidation_concurrency_test.rb
+++ b/test/models/category/cache_invalidation_concurrency_test.rb
@@ -31,6 +31,7 @@ class Category::CacheInvalidationConcurrencyTest < ActiveSupport::TestCase
Category.where(family_id: @family.id).delete_all if @family
Account.where(id: @account.id).delete_all if @account
Depository.where(id: @account.accountable_id).delete_all if @account
+ Rule.where(family_id: @family.id).destroy_all if @family
Family.where(id: @family.id).delete_all if @family
end
diff --git a/test/models/family/auto_categorize_transactions_test.rb b/test/models/family/auto_categorize_transactions_test.rb
index 1fefdea74b..be362d6621 100644
--- a/test/models/family/auto_categorize_transactions_test.rb
+++ b/test/models/family/auto_categorize_transactions_test.rb
@@ -20,79 +20,104 @@ class Family::AutoCategorizeTransactionsTest < ActiveSupport::TestCase
10.times { create_transaction(account: @account, name: "Safeway Groceries", category: @groceries) }
end
- test "bayes handles everything: LLM provider never touched" do
+ test "the rule's auto-categorize is the LLM only, even when Bayes would know" do
train_two_categories
- Provider::Registry.expects(:preferred_llm_provider).never
-
+ Provider::Registry.stubs(:preferred_llm_provider).returns(@llm_provider)
txn = create_transaction(account: @account, name: "Starbucks Coffee").transaction
- assert_difference [ "DataEnrichment.count", "DebugLogEntry.count" ], 1 do
- assert_equal 1, @family.auto_categorize_transactions([ txn.id ])
- end
- assert_equal @coffee, txn.reload.category
- assert_equal "bayes", txn.data_enrichments.find_by(attribute_name: "category_id").source
+ @llm_provider.expects(:auto_categorize).returns(provider_success_response([
+ AutoCategorization.new(transaction_id: txn.id, category_name: @groceries.name)
+ ])).once
- log_entry = DebugLogEntry.order(:created_at).last
- assert_equal "auto_categorization", log_entry.category
- assert_equal "info", log_entry.level
- assert_equal "Bayesian categorization handled all transactions; skipped LLM categorization", log_entry.message
- assert_equal "Family", log_entry.source
- assert_equal @family, log_entry.family
- assert_equal [ txn.id ], log_entry.metadata["requested_transaction_ids"]
- assert_equal [ txn.id ], log_entry.metadata["categorized_transaction_ids"]
- assert_equal 1, log_entry.metadata["modified_count"]
+ assert_equal 1, @family.auto_categorize_transactions([ txn.id ])
+ assert_equal @groceries, txn.reload.category
+ assert_ai_categorization_log(transaction_ids: [ txn.id ])
end
- test "bayes handles nothing: raises without LLM provider, same contract as today" do
- # No training data → Bayes no-ops; no LLM provider configured → raises.
+ test "without a provider the LLM raises" do
txn = create_transaction(account: @account, name: "Something new").transaction
error = assert_raises(Family::AutoCategorizer::Error) do
@family.auto_categorize_transactions([ txn.id ])
end
assert_equal "No LLM provider for auto-categorization", error.message
- assert_nil txn.reload.category
end
- test "bayes handles nothing but LLM available: LLM gets all ids and count is unchanged" do
- Provider::Registry.stubs(:preferred_llm_provider).returns(@llm_provider)
+ test "Bayes categorizes the uncategorized, unlocked transactions and logs the count" do
+ train_two_categories
+ Provider::Registry.expects(:preferred_llm_provider).never
+ coffee = create_transaction(account: @account, name: "Starbucks Coffee").transaction
+ novel = create_transaction(account: @account, name: "Novel Shop").transaction
+ locked = create_transaction(account: @account, name: "Starbucks Coffee").transaction
+ locked.lock_attr!(:category_id)
- txn = create_transaction(account: @account, name: "Novel Shop").transaction
- test_category = @family.categories.create!(name: "Test category")
+ assert_equal 1, @family.bayes_categorize_uncategorized
+ assert_equal @coffee, coffee.reload.category
+ assert_nil novel.reload.category
+ assert_nil locked.reload.category
- @llm_provider.expects(:auto_categorize).returns(provider_success_response([
- AutoCategorization.new(transaction_id: txn.id, category_name: test_category.name)
- ])).once
-
- assert_difference [ "DataEnrichment.count", "DebugLogEntry.count" ], 1 do
- assert_equal 1, @family.auto_categorize_transactions([ txn.id ])
- end
- assert_equal test_category, txn.reload.category
-
- assert_ai_categorization_log(transaction_ids: [ txn.id ])
+ log_entry = DebugLogEntry.order(:created_at).last
+ assert_equal "Bayesian categorization categorized 1 of 2 transactions", log_entry.message
+ assert_equal 1, log_entry.metadata["categorized_count"]
end
- test "bayes handles some, LLM handles the rest: modified_count sums" do
+ test "Bayes leaves transfer legs uncategorized" do
train_two_categories
- Provider::Registry.stubs(:preferred_llm_provider).returns(@llm_provider)
+ transfer = create_transaction(account: @account, name: "Starbucks Coffee", kind: "funds_movement").transaction
- bayes_txn = create_transaction(account: @account, name: "Starbucks Coffee").transaction
- llm_txn = create_transaction(account: @account, name: "Novel Shop").transaction
- test_category = @family.categories.create!(name: "Test category")
+ assert_equal 0, @family.bayes_categorize_uncategorized
+ assert_nil transfer.reload.category
+ end
- @llm_provider.expects(:auto_categorize).returns(provider_success_response([
- AutoCategorization.new(transaction_id: llm_txn.id, category_name: test_category.name)
- ])).once
+ test "clearing Bayes locks unlocks only what Bayes locked and still has its pick" do
+ train_two_categories
+ @family.update_bayes_settings!(lock_results: true)
+ kept = create_transaction(account: @account, name: "Starbucks Coffee").transaction
+ changed = create_transaction(account: @account, name: "Starbucks Coffee").transaction
+ @family.bayes_categorize_uncategorized
+ changed.update!(category: @groceries)
+ user_locked = create_transaction(account: @account, name: "Mine", category: @coffee).transaction
+ user_locked.lock_attr!(:category_id)
+
+ assert_equal 1, @family.clear_bayes_locks!
+
+ assert_not kept.reload.locked?(:category_id)
+ assert_equal @coffee, kept.category
+ assert_nil kept.data_enrichments.find_by(attribute_name: "category_id").metadata["locked_by_bayes"]
+ assert changed.reload.locked?(:category_id)
+ assert user_locked.reload.locked?(:category_id)
+ end
- assert_difference "DataEnrichment.count", 2 do
- assert_difference "DebugLogEntry.count", 1 do
- assert_equal 2, @family.auto_categorize_transactions([ bayes_txn.id, llm_txn.id ])
+ test "clearing Bayes locks also unlocks the merchants the matcher locked and still has" do
+ merchant = @family.merchants.create!(name: "Netflix")
+ other = @family.merchants.create!(name: "Hulu")
+ kept, changed = Array.new(2) do
+ create_transaction(account: @account, name: "Netflix com").transaction.tap do |transaction|
+ transaction.enrich_attribute(:merchant_id, merchant.id, source: "similar", metadata: { locked_by_similar: true })
+ transaction.lock_attr!(:merchant_id)
end
end
- assert_equal @coffee, bayes_txn.reload.category
- assert_equal test_category, llm_txn.reload.category
+ changed.update!(merchant: other)
+
+ assert_equal 1, @family.clear_bayes_locks!
+
+ assert_not kept.reload.locked?(:merchant_id)
+ assert_equal merchant, kept.merchant
+ assert_nil kept.data_enrichments.find_by(attribute_name: "merchant_id").metadata["locked_by_similar"]
+ assert changed.reload.locked?(:merchant_id)
+ end
+
+ test "clearing Bayes locks is all or none" do
+ merchant = @family.merchants.create!(name: "Netflix")
+ transaction = create_transaction(account: @account, name: "Netflix com").transaction
+ transaction.enrich_attribute(:merchant_id, merchant.id, source: "similar", metadata: { locked_by_similar: true })
+ transaction.lock_attr!(:merchant_id)
+ ActiveRecord::Relation.any_instance.stubs(:touch_all).raises(ActiveRecord::StatementInvalid, "boom")
+
+ assert_raises(ActiveRecord::StatementInvalid) { @family.clear_bayes_locks! }
- assert_ai_categorization_log(transaction_ids: [ llm_txn.id ])
+ assert transaction.reload.locked?(:merchant_id)
+ assert transaction.data_enrichments.find_by(attribute_name: "merchant_id").metadata["locked_by_similar"]
end
private
diff --git a/test/models/family/bayes_categorizer_test.rb b/test/models/family/bayes_categorizer_test.rb
index 6170d4045e..abb787e80b 100644
--- a/test/models/family/bayes_categorizer_test.rb
+++ b/test/models/family/bayes_categorizer_test.rb
@@ -3,6 +3,28 @@ require "test_helper"
class Family::BayesCategorizerTest < ActiveSupport::TestCase
include EntriesTestHelper
+ # The hand-worked tests below are for a model tuned on one family's
+ # history; the original model has its own test.
+ TUNED = {
+ # A wrong guess isn't fed back in and reinforced.
+ skip_self_labels: true,
+ # Softmax over complement scores is a ranking score, not a probability.
+ threshold: 0.4,
+ word_split: "unicode",
+ # Digit tokens bloated the vocabulary and inflated confidence.
+ drop_numbers: true,
+ # The merchant counts by id instead, so its name isn't double-counted.
+ merchant_name_words: false,
+ amount_field: true,
+ account_field: true,
+ merchant_field: true,
+ # Complement NB with Lidstone 0.1 beat add-1 and 0.5.
+ complement: true,
+ smoothing: 0.1,
+ prior: true,
+ separate_fields: true
+ }.freeze
+
setup do
# Fresh family: fixture families carry categorized transactions (e.g.
# dylan_family's "Starbucks"/"Amazon" → Food & Drink) that would pollute
@@ -13,16 +35,37 @@ class Family::BayesCategorizerTest < ActiveSupport::TestCase
@groceries = @family.categories.create!(name: "Groceries")
@starbucks = @family.merchants.create!(name: "Starbucks")
@safeway = @family.merchants.create!(name: "Safeway")
+ @family.update_bayes_settings!(TUNED)
end
# 10 coffee + 10 groceries = 20 categorized txns over 2 categories, so the
- # training guard passes. Vocabulary = { starbucks, coffee, safeway,
- # groceries }, |V| = 4. Each class has 20 total tokens (10 txns x 2).
+ # training guard passes. Every txn has the same account, direction and
+ # amount. Words field: { starbucks, coffee, safeway, groceries },
+ # |V_words| = 4, 20 word tokens per class (10 txns x 2).
def train_two_categories
10.times { create_transaction(account: @account, name: "Starbucks Coffee", category: @coffee) }
10.times { create_transaction(account: @account, name: "Safeway Groceries", category: @groceries) }
end
+ def tuned(**changes)
+ Family::BayesCategorizer.new(@family, settings: Family::BayesSettings.new(TUNED.merge(changes)))
+ end
+
+ test "the defaults are the original model: add-1 multinomial, uniform prior, merchant name as words" do
+ train_two_categories
+ categorizer = Family::BayesCategorizer.new(@family, settings: Family::BayesSettings.new)
+
+ category_id, confidence = categorizer.classify(create_transaction(account: @account, name: "Starbucks Coffee").transaction)
+
+ # The original's own hand-worked case: 2 × ln(11/24) against 2 × ln(1/24),
+ # softmax ≈ 0.9918.
+ assert_equal @coffee.id, category_id
+ assert_in_delta 0.9918, confidence, 0.001
+ assert_equal @coffee.id, categorizer.classify(create_transaction(account: @account, name: "Purchase", merchant: @starbucks).transaction)&.first
+ assert_nil categorizer.classify(create_transaction(account: @account, name: "Zzyzx Blorptronics").transaction)
+ assert_equal 0.7, categorizer.settings.threshold
+ end
+
test "no-op before enough training data" do
categorizer = Family::BayesCategorizer.new(@family)
@@ -53,14 +96,16 @@ class Family::BayesCategorizerTest < ActiveSupport::TestCase
assert_equal @coffee.id, category_id
- # Hand-worked multinomial NB, Laplace add-1, uniform prior:
- # P(coffee) = 0.5, total tokens = 20, |V| = 4
- # score_coffee = ln(0.5) + ln(11/24) + ln(11/24) ≈ -2.2535
- # score_other = ln(0.5) + ln(1/24) + ln(1/24) ≈ -7.0493
+ # Hand-worked complement NB, α = 0.1, prior = share of txns. With two
+ # categories each one's complement is the other:
+ # P(coffee) = P(other) = 0.5; words: complement total 20, α|V_words| = 0.4
+ # direction, account and the amount score the same in both and cancel (F)
+ # score_coffee = ln(0.5) - 2 ln(0.1/20.4) - F (groceries never says starbucks/coffee)
+ # score_other = ln(0.5) - 2 ln(10.1/20.4) - F
# softmax(coffee) = 1 / (1 + e^(score_other - score_coffee))
- # = 1 / (1 + e^-4.7958) ≈ 0.9918
- assert_in_delta 0.9918, confidence, 0.001
- assert_operator confidence, :>=, Family::BayesCategorizer::CONFIDENCE_THRESHOLD
+ # = 1 / (1 + e^(-2 ln 101)) = 10201/10202 ≈ 0.9999
+ assert_in_delta 0.9999, confidence, 0.0001
+ assert_operator confidence, :>=, Family::BayesSettings::DEFAULTS[:threshold]
end
test "wholly novel tokens stay unclassified even when class corpora are lopsided" do
@@ -126,11 +171,13 @@ class Family::BayesCategorizerTest < ActiveSupport::TestCase
test "mixed case and merchant signals classify and modified_count sums correctly" do
train_two_categories
+ 5.times { create_transaction(account: @account, name: "Card Payment", merchant: @starbucks, category: @coffee) }
+ 5.times { create_transaction(account: @account, name: "Card Payment", merchant: @safeway, category: @groceries) }
categorizer = Family::BayesCategorizer.new(@family)
# Same tokens as "starbucks coffee" — downcase normalization.
txn1 = create_transaction(account: @account, name: "STARBUCKS Coffee")
- # Name is generic but the merchant name carries the signal.
+ # Name is generic but the merchant carries the signal.
txn2 = create_transaction(account: @account, name: "Purchase", merchant: @starbucks)
# Already categorized → outside scope, must not be counted.
txn3 = create_transaction(account: @account, name: "Safeway Groceries", category: @groceries)
@@ -147,6 +194,309 @@ class Family::BayesCategorizerTest < ActiveSupport::TestCase
enrichment = txn1.transaction.data_enrichments.find_by(attribute_name: "category_id")
assert_equal "bayes", enrichment.source
+ assert_in_delta 1.0, enrichment.metadata["confidence"], 0.001
+ assert_equal Family::BayesCategorizer::MODEL_VERSION, enrichment.metadata["model"]
+ assert_equal @family.bayes_settings_object.digest, enrichment.metadata["settings"]
+ end
+
+ test "its own unconfirmed labels do not count as training data" do
+ train_two_categories
+ # 10 more coffee-looking rows that Bayes labels itself.
+ guesses = Array.new(10) { create_transaction(account: @account, name: "Starbucks Coffee").transaction }
+ Family::BayesCategorizer.new(@family).classify_and_apply(guesses.map(&:id))
+ assert guesses.all? { |txn| txn.reload.category == @coffee }
+
+ categorizer = Family::BayesCategorizer.new(@family)
+ assert_equal 20, categorizer.send(:training_transactions).size
+
+ # A user correction makes the row training data again.
+ guesses.first.update!(category: @groceries)
+ assert_equal 21, Family::BayesCategorizer.new(@family).send(:training_transactions).size
+
+ # So does locking the category, or leaving the guess alone long enough.
+ guesses.second.lock_attr!(:category_id)
+ assert_equal 22, Family::BayesCategorizer.new(@family).send(:training_transactions).size
+ travel Family::BayesSettings::DEFAULTS[:self_label_grace_days].days + 1.day do
+ assert_equal 30, Family::BayesCategorizer.new(@family).send(:training_transactions).size
+ end
+ end
+
+ test "non-ASCII descriptions tokenize as whole words" do
+ 10.times { create_transaction(account: @account, name: "Bäckerei Müller", category: @groceries) }
+ 10.times { create_transaction(account: @account, name: "Кофейня Шоколадница", category: @coffee) }
+ categorizer = Family::BayesCategorizer.new(@family)
+
+ german = create_transaction(account: @account, name: "BÄCKEREI MÜLLER")
+ cyrillic = create_transaction(account: @account, name: "КОФЕЙНЯ")
+
+ assert_equal @groceries.id, categorizer.classify(german.transaction)&.first
+ assert_equal @coffee.id, categorizer.classify(cyrillic.transaction)&.first
+ end
+
+ test "numbers are not tokens" do
+ # The card's last-4 appears on every coffee row; it must not let a
+ # description with no merchant words land in Coffee.
+ 10.times { create_transaction(account: @account, name: "Starbucks Coffee 4471", category: @coffee) }
+ 10.times { create_transaction(account: @account, name: "Safeway Groceries 7eleven", category: @groceries) }
+ categorizer = Family::BayesCategorizer.new(@family)
+
+ numbers_only = create_transaction(account: @account, name: "4471")
+ mixed = create_transaction(account: @account, name: "7ELEVEN 0012")
+
+ assert_nil categorizer.classify(numbers_only.transaction)
+ assert_equal @groceries.id, categorizer.classify(mixed.transaction)&.first
+ end
+
+ test "money in or out separates categories the words alone cannot" do
+ refunds = @family.categories.create!(name: "Refunds")
+ 10.times { create_transaction(account: @account, name: "Starbucks Coffee", category: @coffee) }
+ 15.times { create_transaction(account: @account, name: "Woolworths", category: @groceries) }
+ 5.times { create_transaction(account: @account, name: "Woolworths Refund", amount: -100, category: refunds) }
+ categorizer = Family::BayesCategorizer.new(@family)
+
+ # From the words alone both lean Groceries at ~0.79, so the credit would
+ # be filed as Groceries; with money in/out, debit -> Groceries ~0.82 and
+ # credit -> Refunds ~0.99.
+ debit = create_transaction(account: @account, name: "WOOLWORTHS")
+ credit = create_transaction(account: @account, name: "WOOLWORTHS", amount: -100)
+
+ assert_equal @groceries.id, categorizer.classify(debit.transaction)&.first
+ assert_equal refunds.id, categorizer.classify(credit.transaction)&.first
+ end
+
+ test "prior is each category's share of the training transactions" do
+ 15.times { create_transaction(account: @account, name: "Starbucks Coffee", category: @coffee) }
+ 5.times { create_transaction(account: @account, name: "Safeway Groceries", category: @groceries) }
+ categorizer = Family::BayesCategorizer.new(@family)
+
+ assert_in_delta Math.log(0.75), categorizer.send(:log_prior, @coffee.id), 1e-9
+ assert_in_delta Math.log(0.25), categorizer.send(:log_prior, @groceries.id), 1e-9
+ end
+
+ test "direction and size together decide when neither does alone" do
+ # Each category has small and large amounts both ways round, so money
+ # in/out alone or the amount alone would be split evenly; the amount
+ # Gaussians are per direction (small out vs large out), which tells them
+ # apart.
+ 5.times { create_transaction(account: @account, name: "Acme", amount: 20, category: @groceries) }
+ 5.times { create_transaction(account: @account, name: "Acme", amount: -4000, category: @groceries) }
+ 5.times { create_transaction(account: @account, name: "Acme", amount: 4000, category: @coffee) }
+ 5.times { create_transaction(account: @account, name: "Acme", amount: -20, category: @coffee) }
+ categorizer = Family::BayesCategorizer.new(@family)
+
+ small_debit = create_transaction(account: @account, name: "ACME", amount: 20)
+ small_credit = create_transaction(account: @account, name: "ACME", amount: -20)
+
+ # ≈ 0.999 each way.
+ assert_equal @groceries.id, categorizer.classify(small_debit.transaction)&.first
+ assert_equal @coffee.id, categorizer.classify(small_credit.transaction)&.first
+ end
+
+ test "tokens: words of any script, no numbers, single letters, merchant id, account" do
+ txn = create_transaction(account: @account, name: "S/O Müller 4471 Rent", amount: -2000, merchant: @starbucks).transaction
+
+ # "s/o" splits on the symbol and keeps both letters; "4471" is dropped;
+ # the merchant is one id token (its name "Starbucks" is not read);
+ # direction and amount are scored separately, not as tokens.
+ assert_equal [ "s", "o", "müller", "rent", "merchant:#{@starbucks.id}",
+ "account:#{@account.id}" ],
+ Family::BayesCategorizer.new(@family).send(:tokens_for, txn)
+ end
+
+ test "the merchant decides by id, and its name is not read as words" do
+ 10.times { create_transaction(account: @account, name: "Card Payment", merchant: @starbucks, category: @coffee) }
+ 10.times { create_transaction(account: @account, name: "Card Payment", merchant: @safeway, category: @groceries) }
+ categorizer = Family::BayesCategorizer.new(@family)
+
+ generic = create_transaction(account: @account, name: "CARD PAYMENT", merchant: @starbucks)
+ unknown_words = create_transaction(account: @account, name: "Zzyzx", merchant: @safeway)
+ name_only = create_transaction(account: @account, name: "Starbucks")
+
+ # "card payment" is in both; only the merchant tells them apart (~0.99).
+ assert_equal @coffee.id, categorizer.classify(generic.transaction)&.first
+ # The merchant counts as a known word, so it classifies on its own.
+ assert_equal @groceries.id, categorizer.classify(unknown_words.transaction)&.first
+ # Merchant names are not tokens, so the word "starbucks" is unknown.
+ assert_nil categorizer.classify(name_only.transaction)
+ end
+
+ test "complement scoring with more than two categories" do
+ alpha = @family.categories.create!(name: "Alpha")
+ beta = @family.categories.create!(name: "Beta")
+ gamma = @family.categories.create!(name: "Gamma")
+ 10.times { create_transaction(account: @account, name: "Alpha", category: alpha) }
+ 10.times { create_transaction(account: @account, name: "Beta", category: beta) }
+ 30.times { create_transaction(account: @account, name: "Gamma", category: gamma) }
+
+ txn = create_transaction(account: @account, name: "Alpha")
+ category_id, confidence = Family::BayesCategorizer.new(@family).classify(txn.transaction)
+
+ # Each txn: 1 word + the account. Words field: totals 10 / 10 / 30,
+ # |V_words| = 3; account and direction have one value each, so they
+ # score ln(1) = 0, and every amount is the same, so the amount densities
+ # are equal and cancel. Priors 0.2 / 0.2 / 0.6. Each category is scored
+ # against the pooled others:
+ # alpha: ln 0.2 - ln(0.1/40.3)
+ # beta: ln 0.2 - ln(10.1/40.3)
+ # gamma: ln 0.6 - ln(10.1/20.3)
+ # softmax(alpha) ≈ 0.97574 (multinomial NB would give ≈ 0.98039).
+ assert_equal alpha.id, category_id
+ assert_in_delta 0.97574, confidence, 0.00001
+ end
+
+ test "the amount counts by distance: unseen amounts go to the nearer category" do
+ rent = @family.categories.create!(name: "Rent")
+ 10.times { |i| create_transaction(account: @account, name: "Payment", amount: 1900 + i * 20, category: rent) }
+ 10.times { |i| create_transaction(account: @account, name: "Payment", amount: 40 + i * 2, category: @groceries) }
+ categorizer = Family::BayesCategorizer.new(@family)
+
+ # Same words; rent ~$2,000, groceries ~$50. Neither $700 nor $150 was
+ # ever seen, but on a log scale $700 is nearer $2,000 and $150 nearer $50
+ # (bucket tokens gave both 0.5). $700 is past MAX_AMOUNT_Z from groceries.
+ near_rent = create_transaction(account: @account, name: "PAYMENT", amount: 700)
+ near_groceries = create_transaction(account: @account, name: "PAYMENT", amount: 150)
+
+ category_id, confidence = categorizer.classify(near_rent.transaction)
+ assert_equal rent.id, category_id
+ assert_in_delta 0.97240, confidence, 0.00001
+ assert_nil tuned(threshold: 0.98).classify(near_rent.transaction)
+ category_id, confidence = categorizer.classify(near_groceries.transaction)
+ assert_equal @groceries.id, category_id
+ assert_in_delta 0.96802, confidence, 0.00001
+ end
+
+ test "an outlier amount doesn't outvote the merchant" do
+ 10.times { |i| create_transaction(account: @account, name: "Card payment", amount: 4 + i * 0.2, category: @coffee, merchant: @starbucks) }
+ 10.times { |i| create_transaction(account: @account, name: "Card payment", amount: 50 + i * 4, category: @groceries, merchant: @safeway) }
+
+ # $500 is far from both categories, but much further from coffee's ~$5
+ # than from groceries' ~$70. Uncapped, that distance alone gave Groceries
+ # at 0.9999999999.
+ outlier = create_transaction(account: @account, name: "Card payment", amount: 500, merchant: @starbucks)
+
+ category_id, confidence = Family::BayesCategorizer.new(@family).classify(outlier.transaction)
+ assert_equal @coffee.id, category_id
+ assert_in_delta 0.99040, confidence, 0.00001
+ end
+
+ test "amounts are compared within their own currency" do
+ lunch = @family.categories.create!(name: "Lunch")
+ rent = @family.categories.create!(name: "Rent")
+ # The same numbers: ¥900-1,080 lunches and $900-1,080 rent.
+ 10.times { |i| create_transaction(account: @account, name: "Card payment", amount: 900 + i * 20, currency: "JPY", category: lunch) }
+ 10.times { |i| create_transaction(account: @account, name: "Card payment", amount: 900 + i * 20, currency: "USD", category: rent) }
+ categorizer = Family::BayesCategorizer.new(@family)
+
+ # On one shared scale both would score 0.5.
+ category_id, confidence = categorizer.classify(create_transaction(account: @account, name: "Card payment", amount: 1000, currency: "USD").transaction)
+ assert_equal rent.id, category_id
+ assert_in_delta 0.92567, confidence, 0.00001
+ category_id, confidence = categorizer.classify(create_transaction(account: @account, name: "Card payment", amount: 1000, currency: "JPY").transaction)
+ assert_equal lunch.id, category_id
+ assert_in_delta 0.92567, confidence, 0.00001
+ end
+
+ test "settings: tokenizer options" do
+ txn = create_transaction(account: @account, name: "McDonald's 2K4L19 Café a 1234", notes: "Lunch lunch").transaction
+ tokens = ->(**changes) { tuned(merchant_field: false, account_field: false, **changes).send(:tokens_for, txn) }
+
+ assert_equal %w[mcdonald s 2k4l19 café a lunch lunch], tokens.call
+ assert_equal %w[mcdonald's 2k4l19 café a lunch lunch], tokens.call(word_split: "symbols")
+ assert_equal %w[mcdonald s café a lunch lunch], tokens.call(drop_codes: true)
+ assert_equal %w[mcdonald 2k4l19 café lunch lunch], tokens.call(keep_single_chars: false)
+ assert_equal %w[mcdonald s 2k4l19 café a], tokens.call(include_notes: false)
+ assert_equal %w[mcdonald s 2k4l19 caf a lunch lunch], tokens.call(word_split: "ascii")
+ assert_equal %w[mcdonald s 2k4l19 café a 1234 lunch lunch], tokens.call(drop_numbers: false)
+ assert_equal %w[mcdonald s 2k4l19 café a lunch], tokens.call(binary: true)
+ assert_equal [ "mcdonald", "s", "2k4l19", "café", "a", "mcdonald s", "s 2k4l19", "2k4l19 café", "café a" ],
+ tokens.call(include_notes: false, bigrams: true)
+ end
+
+ test "settings: merchant name words and the merchant id" do
+ txn = create_transaction(account: @account, name: "Card payment", merchant: @starbucks).transaction
+
+ assert_equal [ "card", "payment", "starbucks" ], tuned(merchant_name_words: true, merchant_field: false, account_field: false).send(:tokens_for, txn)
+ assert_equal [ "card", "payment", "account:#{@account.id}" ], tuned(merchant_field: false).send(:tokens_for, txn)
+ end
+
+ test "training stops at the as-of date" do
+ train_two_categories
+
+ assert tuned.enough_training_data?
+ assert_not Family::BayesCategorizer.new(@family, as_of: Date.yesterday).enough_training_data?
+ end
+
+ test "settings: training takes the newest by creation, whatever the date, as the original does" do
+ train_two_categories
+ future = create_transaction(account: @account, name: "Safeway Groceries", category: @groceries, date: 1.month.from_now.to_date).transaction
+ backdated = create_transaction(account: @account, name: "Starbucks Coffee", category: @coffee, date: 1.year.ago.to_date).transaction
+
+ assert_equal [ backdated, future ], tuned.send(:training_transactions).first(2)
+ end
+
+ test "settings: excluded categories and their subcategories are left out of training" do
+ train_two_categories
+ food = @family.categories.create!(name: "Food")
+ @coffee.update!(parent: food)
+ rent = @family.categories.create!(name: "Rent")
+ 10.times { create_transaction(account: @account, name: "Landlord", category: rent) }
+
+ assert_equal [ @coffee.id, @groceries.id, rent.id ].sort, tuned.send(:class_models).keys.sort
+ assert_equal [ @groceries.id, rent.id ].sort, tuned(excluded_category_ids: [ food.id ]).send(:class_models).keys.sort
+ end
+
+ test "settings: transfers can be left out of training" do
+ train_two_categories
+ 3.times { create_transaction(account: @account, name: "To savings", category: @groceries, kind: "funds_movement") }
+
+ assert_equal 23, tuned.send(:training_transactions).size
+ assert_equal 20, tuned(exclude_transfers: true).send(:training_transactions).size
+ end
+
+ test "settings: Bayes' own labels count once locked or past their grace period" do
+ train_two_categories
+ guess = create_transaction(account: @account, name: "Starbucks Coffee").transaction
+ tuned.classify_and_apply([ guess.id ])
+
+ travel 91.days do
+ assert_equal 21, tuned.send(:training_transactions).size
+ assert_equal 20, tuned(self_label_grace_days: 100).send(:training_transactions).size
+ assert_equal 21, tuned(skip_self_labels: false).send(:training_transactions).size
+ end
+ end
+
+ test "settings: lock_results locks Bayes' labels without counting them as confirmed" do
+ train_two_categories
+ guess = create_transaction(account: @account, name: "Starbucks Coffee").transaction
+
+ tuned(lock_results: true).classify_and_apply([ guess.id ])
+
+ assert guess.reload.locked?(:category_id)
+ assert guess.data_enrichments.find_by(attribute_name: "category_id").metadata["locked_by_bayes"]
+ assert_equal 20, tuned.send(:training_transactions).size
+ end
+
+ test "the account never decides alone" do
+ train_two_categories
+ other = @family.accounts.create!(name: "Other", balance: 0, currency: "USD", accountable: Depository.new)
+ 5.times { create_transaction(account: other, name: "Starbucks Coffee", category: @coffee) }
+ novel = create_transaction(account: other, name: "Zzyzx").transaction
+
+ # Only the account is known: that isn't enough to classify.
+ assert_nil tuned(account_field: true, prior: true).classify(novel)
+ end
+
+ test "probabilities score every trained category, or none when it doesn't answer" do
+ train_two_categories
+ known = create_transaction(account: @account, name: "Starbucks Coffee").transaction
+ novel = create_transaction(account: @account, name: "Zzyzx").transaction
+
+ probabilities = tuned.probabilities(known)
+ assert_equal [ @coffee.id, @groceries.id ].sort, probabilities.keys.sort
+ assert_in_delta 1.0, probabilities.values.sum
+ assert_equal [ @coffee.id, probabilities[@coffee.id] ], tuned(threshold: 0).classify(known)
+ assert_empty tuned.probabilities(novel)
+ assert_equal [ @coffee.id, @groceries.id ].sort, tuned.category_ids.sort
end
test "classify_and_apply returns categorized_ids and modified_count separately" do
diff --git a/test/models/family/bayes_evaluation_test.rb b/test/models/family/bayes_evaluation_test.rb
new file mode 100644
index 0000000000..b193172b7d
--- /dev/null
+++ b/test/models/family/bayes_evaluation_test.rb
@@ -0,0 +1,365 @@
+require "test_helper"
+
+class Family::BayesEvaluationTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ @family = Family.create!(name: "Evaluation family")
+ @account = @family.accounts.create!(name: "Evaluation", balance: 0, currency: "USD", accountable: Depository.new)
+ @coffee = @family.categories.create!(name: "Coffee")
+ @groceries = @family.categories.create!(name: "Groceries")
+ @today = Date.new(2026, 10, 17)
+ history = Date.new(2026, 1, 15)
+ 10.times { create_transaction(account: @account, name: "Starbucks Coffee", category: @coffee, date: history) }
+ 10.times { create_transaction(account: @account, name: "Safeway Groceries", category: @groceries, date: history) }
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ end
+
+ test "scores the newest months on what came before, without writing anything" do
+ create_transaction(account: @account, name: "Starbucks Coffee", category: @coffee, date: Date.new(2026, 9, 3))
+ create_transaction(account: @account, name: "Safeway Groceries", category: @coffee, date: Date.new(2026, 9, 4))
+ # Still on a Bayes guess, so not a fair test row.
+ guessed = create_transaction(account: @account, name: "Starbucks Coffee", date: Date.new(2026, 9, 5)).transaction
+ guessed.enrich_attribute(:category_id, @coffee.id, source: "bayes")
+
+ result = nil
+ assert_no_difference "DataEnrichment.count" do
+ result = Family::BayesEvaluation.new(@family, today: @today).run!
+ end
+
+ assert_equal %w[2026-08 2026-09], result["months"]
+ assert_equal "test", result["action"]
+ assert_equal 2, result.dig("current", "n")
+ at_threshold = result.dig("current", "sweep").find { |row| row["threshold"] == 0.4 }
+ assert_equal({ "threshold" => 0.4, "right" => 1, "wrong" => 1 }, at_threshold)
+ assert_equal [ [ "Coffee", "Groceries", 1 ] ], result.dig("current", "confusions", 0.7)
+ assert_equal result["current"], result["defaults"]
+ assert_nil result["best"]
+ end
+
+ test "scores the matcher on the same months, by similarity and number agreeing" do
+ netflix = @family.merchants.create!(name: "Netflix")
+ hulu = @family.merchants.create!(name: "Hulu")
+ 2.times { create_transaction(account: @account, name: "NETFLIX.COM 8812", merchant: netflix, date: Date.new(2026, 7, 1)) }
+ create_transaction(account: @account, name: "Netflix com 1203", merchant: netflix, date: Date.new(2026, 9, 2))
+ # Copied from near-duplicates of Netflix, but it's Hulu: one wrong at 1 agreeing.
+ create_transaction(account: @account, name: "NETFLIX COM", merchant: hulu, date: Date.new(2026, 8, 2))
+ # A transfer is neither tested nor copied from.
+ create_transaction(account: @account, name: "Netflix com", merchant: hulu, kind: "funds_movement", date: Date.new(2026, 9, 3))
+
+ matcher = Family::BayesEvaluation.new(@family, today: @today).run!["matcher"]
+
+ assert_equal 2, matcher["n"]
+ assert_equal Family::BayesSettings::STEPS[:similar_common_share], matcher["cutoffs"].keys
+ at = ->(agreeing, similarity) { matcher.dig("cutoffs", 0.2, agreeing).find { |row| row["threshold"] == similarity }.values_at("right", "wrong") }
+ # Aug: Hulu against 2 Netflix → wrong. Sep: Netflix against 2 Netflix and
+ # the Hulu → disagree, so nothing.
+ assert_equal [ 0, 1 ], at.call(1, 0.9)
+ assert_equal [ 0, 1 ], at.call(2, 0.9)
+ assert_equal [ 0, 0 ], at.call(3, 0.9)
+ row = matcher.dig("cutoffs", 0.2, 1).find { |r| r["threshold"] == 0.9 }
+ assert_equal [ [ "Hulu", "Netflix", 1 ] ], row["confusions"]
+ assert_equal [ [ "Netflix", 1 ] ], row["unfilled"]
+ end
+
+ test "the matcher's mistakes are listed for the button pressed last, at that column's similarity" do
+ row = ->(similarity, right, wrong) { { "threshold" => similarity, "right" => right, "wrong" => wrong, "confusions" => [ [ "A", "B", wrong ] ] } }
+ cutoffs = { 0.2 => { 2 => [ row.call(0.8, 5, 1), row.call(0.9, 4, 0) ] }, 0.05 => { 1 => [ row.call(0.65, 20, 2) ] } }
+ settings = Family::BayesSettings.new(similar_threshold: 0.8)
+ mistakes = ->(action) { Family::BayesEvaluation.matcher_mistakes({ "action" => action, "best" => {}, "matcher" => { "cutoffs" => cutoffs } }, settings, 1) }
+
+ assert_equal [ "current", 0.8, cutoffs.dig(0.2, 2, 0) ], mistakes.call("test")
+ assert_equal [ "best", 0.65, cutoffs.dig(0.05, 1, 0) ], mistakes.call("find_best")
+ assert_equal [ "defaults", 0.9, cutoffs.dig(0.2, 2, 1) ], mistakes.call("reset")
+ assert_nil Family::BayesEvaluation.matcher_mistakes({}, settings, 1)
+ end
+
+ test "apply's matcher changes: the one best cell over every cutoff; on a tie the most agreeing, then highest similarity, then cutoff" do
+ row = ->(similarity, right, wrong) { { "threshold" => similarity, "right" => right, "wrong" => wrong } }
+ sweeps = {
+ 1 => [ row.call(0.8, 12, 4), row.call(0.9, 11, 3) ],
+ 2 => [ row.call(0.8, 10, 2), row.call(0.9, 9, 1) ],
+ 3 => [ row.call(0.8, 8, 0), row.call(0.9, 7, 0) ]
+ }
+ result = { "best" => { "changes" => {} },
+ "matcher" => { "cutoffs" => { 0.1 => sweeps, 0.2 => sweeps, 0.4 => sweeps.merge(1 => [ row.call(0.9, 20, 1) ]) } } }
+ settings = Family::BayesSettings.new
+
+ # Cost 1: 0.4's 1-agreeing 0.9 scores 19, beating every other cell.
+ assert_equal [ 0.4, 1, 0.9 ], Family::BayesEvaluation.best_matcher(result, 1)
+ assert_equal({ "similar_common_share" => 0.4, "similar_min_neighbours" => 1 }, Family::BayesEvaluation.matcher_changes(result, settings, 1))
+ # Only after Find best settings, as for the categories.
+ assert_equal({}, Family::BayesEvaluation.apply_changes(result.except("best"), settings, 1))
+ # Too little history for the categories still applies the matcher's, but not when it scored nothing.
+ assert_equal [ "similar_common_share", "similar_min_neighbours" ], Family::BayesEvaluation.apply_changes(result.merge("short_history" => true), settings, 1).keys
+ assert_equal({}, Family::BayesEvaluation.matcher_changes(result.merge("matcher" => result["matcher"].merge("n" => 0)), settings, 1))
+ # Without it, every 1- and 2-agreeing cell and 3 at 0.8 score 8: 3 at 0.8, at the highest cutoff.
+ result["matcher"]["cutoffs"][0.4] = sweeps
+ assert_equal [ 0.4, 3, 0.8 ], Family::BayesEvaluation.best_matcher(result, 1)
+ assert_equal({}, Family::BayesEvaluation.matcher_changes({}, settings, 1))
+ end
+
+ test "the matcher's columns: yours, the best found for the cost after Find best settings, and the defaults" do
+ row = ->(similarity, right, wrong) { { "threshold" => similarity, "right" => right, "wrong" => wrong } }
+ result = { "best" => { "changes" => {} }, "matcher" => { "cutoffs" => {
+ 0.05 => { 1 => [ row.call(0.65, 20, 5), row.call(0.9, 15, 1) ], 2 => [ row.call(0.9, 10, 0) ] },
+ 0.2 => { 2 => [ row.call(0.9, 9, 1) ] }
+ } } }
+ settings = Family::BayesSettings.new(similar_common_share: 0.03)
+
+ columns = ->(weight) { Family::BayesEvaluation.matcher_columns(result, settings, weight).map { |c| c.first(3) } }
+ # Cost 1 or 3, 0.05 with 1 agreeing has the best cell. A cutoff typed in
+ # that wasn't scored has no rows.
+ assert_equal [ [ "current", 0.03, 2 ], [ "best", 0.05, 1 ], [ "defaults", 0.2, 2 ] ], columns.call(1)
+ assert_equal [ "best", 0.05, 1 ], columns.call(3)[1]
+ assert_equal [], Family::BayesEvaluation.matcher_columns(result, settings, 1).first[3]
+ # Best found only after Find best settings.
+ assert_equal %w[current defaults], Family::BayesEvaluation.matcher_columns(result.except("best"), settings, 1).map(&:first)
+ assert_nil Family::BayesEvaluation.matcher_columns({}, settings, 1)
+ end
+
+ test "caches the latest result and compares with the defaults" do
+ create_transaction(account: @account, name: "Starbucks Coffee", category: @coffee, date: Date.new(2026, 9, 3))
+ @family.update_bayes_settings!(threshold: "0.65")
+ settings = @family.bayes_settings_object
+
+ result = Family::BayesEvaluation.new(@family, today: @today).run!
+
+ assert_includes result.dig("current", "sweep").map { |row| row["threshold"] }, 0.65
+ assert_not_includes result.dig("defaults", "sweep").map { |row| row["threshold"] }, 0.65
+ assert_equal result, Family::BayesEvaluation.cached(@family)
+ assert_equal settings.digest, result["digest"]
+ end
+
+ test "the defaults keep the chosen categories, so both score the same transactions" do
+ create_transaction(account: @account, name: "Starbucks Coffee", category: @coffee, date: Date.new(2026, 9, 3))
+ create_transaction(account: @account, name: "Safeway Groceries", category: @groceries, date: Date.new(2026, 9, 4))
+ @family.update_bayes_settings!(excluded_category_ids: [ @groceries.id ], threshold: "0.65")
+
+ result = Family::BayesEvaluation.new(@family, today: @today).run!
+
+ assert_equal 1, result.dig("current", "n")
+ assert_equal 1, result.dig("defaults", "n")
+ assert_equal 0.7, result.dig("defaults", "threshold")
+ end
+
+ test "ROC-AUC ranks each category's rows against the rest, weighted by its rows" do
+ # Coffee's rows score 0.9 and 0.5, the tea row 0.5 for coffee: one win,
+ # one tie of two → 0.75. Tea's one row outranks both coffee rows → 1.0.
+ rows = [ [ "coffee", { "coffee" => 0.9, "tea" => 0.1 } ],
+ [ "coffee", { "coffee" => 0.5, "tea" => 0.5 } ],
+ [ "tea", { "coffee" => 0.5, "tea" => 0.6 } ] ]
+
+ assert_in_delta (2 * 0.75 + 1 * 1.0) / 3, Family::BayesEvaluation.roc_auc(rows)
+ assert_nil Family::BayesEvaluation.roc_auc([ [ "coffee", {} ] ])
+ end
+
+ test "a transaction it doesn't answer counts as no information in the AUC" do
+ create_transaction(account: @account, name: "Starbucks Coffee", category: @coffee, date: Date.new(2026, 9, 3))
+ create_transaction(account: @account, name: "Zzyzx", category: @groceries, date: Date.new(2026, 9, 4))
+ create_transaction(account: @account, name: "Safeway Groceries", category: @coffee, date: Date.new(2026, 9, 5))
+ evaluation = Family::BayesEvaluation.new(@family, today: @today, months: 1)
+
+ # Zzyzx isn't answered, so it scores 0.5 for both. Coffee's rows,
+ # Starbucks (~1) and Safeway (~0), against it: one win, one loss.
+ # Groceries' Zzyzx against Starbucks (~0) and Safeway (~1): the same.
+ report = evaluation.report
+ assert_equal 3, report["n"]
+ assert_equal 2, report["sweep"].first.values_at("right", "wrong").sum
+ assert_in_delta 0.5, report["auc"]
+ assert_equal [ [ "Groceries", 1 ] ], report.dig("uncategorized", 0.7)
+ end
+
+ test "report scores any settings over the chosen months, uncached" do
+ create_transaction(account: @account, name: "Starbucks Coffee", category: @coffee, date: Date.new(2026, 9, 3))
+ evaluation = Family::BayesEvaluation.new(@family, today: @today, months: 1)
+
+ report = evaluation.report(Family::BayesSettings.new(threshold: 0.5))
+
+ assert_equal [ "2026-09" ], evaluation.month_labels
+ assert_equal 1, report["n"]
+ assert_equal [ report["auc"] ], report["month_aucs"]
+ assert_equal 0.5, report["threshold"]
+ assert_nil Family::BayesEvaluation.cached(@family)
+ end
+
+ test "search fixes the features, then the parameters, then the threshold" do
+ evaluation = fake_reports(tuned_evaluation)
+ # Amount and account help only together, so one at a time would never
+ # find them; reading neither the merchant's name nor the notes helps.
+ FakeEvaluation.bonus = ->(settings) {
+ fields = [ settings.amount_field, settings.account_field ].count(true)
+ words = [ settings.merchant_name_words, settings.include_notes ].count(false)
+ { 0 => 0, 1 => -0.01, 2 => 0.03 }[fields] + { 0 => 0, 1 => -0.005, 2 => 0.005 }[words]
+ }
+ tried = []
+
+ best, report = evaluation.search { |changes| tried << changes }
+
+ assert best.amount_field
+ assert best.account_field
+ assert_not best.merchant_field
+ assert_not best.merchant_name_words
+ assert_not best.include_notes
+ # Then by AUC binary +0.02, then dropping the prior +0.01. The threshold
+ # isn't searched; picked afterwards from the result's sweep, it's
+ # binary's 0.8, not the 0.4 the starting settings would pick.
+ assert best.binary
+ assert_not best.prior
+ assert_equal 0.4, best.threshold
+ assert_equal 0.8, Family::BayesEvaluation.best_threshold(report["sweep"], 3)
+
+ assert_includes tried, { amount_field: true, account_field: true }
+ assert_includes tried, { separate_fields: true }
+ assert_includes tried, { smoothing: 0.1 }
+ assert_not_includes tried, { smoothing: 1.0 }
+ features = Family::BayesEvaluation::FEATURE_SETS.flatten
+ first_parameter = tried.index { |changes| (changes.keys & features).empty? }
+ assert tried.drop(first_parameter).none? { |changes| changes.keys.intersect?(features) }, "a feature was tried again after step 1"
+ assert_operator tried.rindex { |changes| changes.key?(:binary) }, :<, tried.index { |changes| changes.key?(:prior) }
+ end
+
+ test "the threshold is the shown table's best row for the cost of a mistake" do
+ # A real Best found, over two months.
+ sweep = [ [ 0.2, 313, 35 ], [ 0.3, 302, 27 ], [ 0.4, 292, 24 ], [ 0.5, 286, 22 ],
+ [ 0.6, 281, 20 ], [ 0.7, 273, 16 ], [ 0.8, 266, 11 ], [ 0.9, 251, 9 ] ]
+ .map { |threshold, right, wrong| { "threshold" => threshold, "right" => right, "wrong" => wrong } }
+ result = { "current" => { "threshold" => 0.7 }, "best" => { "changes" => {}, "report" => { "sweep" => sweep } } }
+
+ assert_equal 0.2, Family::BayesEvaluation.best_changes(result, 1)["threshold"]
+ assert_equal 0.3, Family::BayesEvaluation.best_changes(result, 2)["threshold"]
+ assert_equal 0.8, Family::BayesEvaluation.best_changes(result, 3)["threshold"]
+ end
+
+ test "the threshold is picked for the cost of a mistake, the highest on a tie" do
+ sweep = [ { "threshold" => 0.4, "right" => 120, "wrong" => 20 },
+ { "threshold" => 0.8, "right" => 100, "wrong" => 8 },
+ { "threshold" => 0.9, "right" => 98, "wrong" => 7 } ]
+
+ assert_equal 0.4, Family::BayesEvaluation.best_threshold(sweep, 1)
+ # 84 at both 0.8 and 0.9.
+ assert_equal 0.9, Family::BayesEvaluation.best_threshold(sweep, 2)
+ assert_equal 0.9, Family::BayesEvaluation.best_threshold(sweep, 3)
+ end
+
+ test "search keeps a change only when it's better in all but one month" do
+ evaluation = fake_reports(tuned_evaluation)
+ # Over 6 months: word pairs gain a lot in 3 and lose a little in 3, so
+ # more overall; dropping codes gains in 5 of them.
+ FakeEvaluation.month_bonus = ->(settings, i) {
+ (settings.bigrams ? (i < 3 ? 0.04 : -0.01) : 0) + (settings.drop_codes ? (i < 5 ? 0.01 : -0.01) : 0)
+ }
+
+ best, = evaluation.search
+
+ assert_not best.bigrams
+ assert best.drop_codes
+ end
+
+ test "search doesn't try a setting that does nothing while another is off" do
+ evaluation = fake_reports(tuned_evaluation(amount_field: false))
+ tried = []
+
+ evaluation.search { |changes| tried.concat(changes.keys) }
+
+ assert_includes tried, :amount_field
+ assert_not_includes tried, :amount_by_direction
+ assert_not_includes tried, :separate_fields
+ end
+
+ test "find best searches the older months and scores the best found on the newest, unseen" do
+ evaluation = fake_reports(tuned_evaluation)
+
+ result = evaluation.run!(action: "find_best")
+
+ assert_equal [ %w[2026-04 2026-05 2026-06 2026-07] ], FakeEvaluation.searched
+ assert_equal %w[2026-08 2026-09], result["months"]
+ assert_equal({ "binary" => true, "prior" => false }, result.dig("best", "changes"))
+ assert_equal 0.4, result.dig("current", "threshold")
+ assert_equal({ "binary" => true, "prior" => false, "threshold" => 0.8 }, Family::BayesEvaluation.best_changes(result, 3))
+ end
+
+ test "too little history keeps Apply off: nothing tested, or too few months for the search" do
+ assert Family::BayesEvaluation.new(@family, today: @today).run!["short_history"]
+
+ evaluation = fake_reports(tuned_evaluation)
+ settings = evaluation.send(:settings)
+ result = evaluation.run!(action: "find_best")
+ assert result["short_history"]
+ assert_equal({}, Family::BayesEvaluation.apply_changes(result, settings, 1))
+
+ # Three of the four searched months, each with history before it: enough.
+ [ 4, 5, 6 ].each { |month| create_transaction(account: @account, name: "Starbucks Coffee", category: @coffee, date: Date.new(2026, month, 3)) }
+ result = evaluation.run!(action: "find_best")
+ assert_not result["short_history"]
+ assert_not_empty Family::BayesEvaluation.apply_changes(result, settings, 1)
+ end
+
+ test "apply leaves the threshold alone when it's already the one picked" do
+ result = { "current" => { "threshold" => 0.8 },
+ "best" => { "changes" => { "binary" => true }, "report" => { "sweep" => [ { "threshold" => 0.8, "right" => 5, "wrong" => 0 } ] } } }
+
+ assert_equal({ "binary" => true }, Family::BayesEvaluation.best_changes(result, 2))
+ end
+
+ test "the page lists the mistakes of whichever button was pressed last" do
+ report = ->(threshold) { { "threshold" => threshold, "sweep" => [], "confusions" => { threshold => [ [ "A", "B", 1 ] ] } } }
+ best = { "changes" => {}, "report" => report.call(0.4).merge("sweep" => [ { "threshold" => 0.4, "right" => 1, "wrong" => 0 },
+ { "threshold" => 0.8, "right" => 1, "wrong" => 0 } ]) }
+ result = { "current" => report.call(0.4), "defaults" => report.call(0.7), "best" => best }
+
+ assert_equal [ "current", result["current"], 0.4 ], Family::BayesEvaluation.mistakes(result.merge("action" => "test"), 1)
+ assert_equal [ "best", best["report"], 0.8 ], Family::BayesEvaluation.mistakes(result.merge("action" => "find_best"), 1)
+ assert_equal [ "defaults", result["defaults"], 0.7 ], Family::BayesEvaluation.mistakes(result.merge("action" => "reset"), 1)
+ end
+
+ test "a cached result of an older shape is ignored" do
+ Rails.cache.write(Family::BayesEvaluation.cache_key(@family), { "digest" => "old" })
+
+ assert_nil Family::BayesEvaluation.cached(@family)
+ end
+
+ test "running flag clears when the run ends" do
+ Family::BayesEvaluation.mark_running!(@family)
+ assert Family::BayesEvaluation.running?(@family)
+
+ Family::BayesEvaluation.new(@family, today: @today).run!
+
+ assert_not Family::BayesEvaluation.running?(@family)
+ end
+
+ private
+ def tuned_evaluation(**changes)
+ Family::BayesEvaluation.new(@family, today: @today, settings: Family::BayesSettings.new(threshold: 0.4, prior: true, **changes))
+ end
+
+ def fake_reports(evaluation)
+ FakeEvaluation.searched = []
+ FakeEvaluation.bonus = ->(_) { 0 }
+ FakeEvaluation.month_bonus = ->(_, _) { 0 }
+ FakeEvaluation.new(@family, today: @today, settings: evaluation.send(:settings))
+ end
+
+ # Reports by rule, for any months: binary +10 right and +0.02 AUC, no
+ # prior +3 right and +0.01 AUC; at 0.4, 10 more right than at 0.8 and 2
+ # more wrong, or 10 with binary; bonus adds to the AUC, month_bonus to
+ # one month's (and so to the mean, the overall AUC). Records the months
+ # each search ran over.
+ class FakeEvaluation < Family::BayesEvaluation
+ cattr_accessor :searched, :bonus, :month_bonus
+
+ def report(settings = self.settings)
+ right = (settings.binary ? 100 : 90) + (settings.prior ? 0 : 3)
+ auc = 0.8 + (settings.binary ? 0.02 : 0) + (settings.prior ? 0 : 0.01) + bonus.call(settings)
+ month_aucs = month_labels.each_index.map { |i| auc + month_bonus.call(settings, i) }
+ { "n" => 200, "threshold" => settings.threshold, "auc" => month_aucs.sum / month_aucs.size, "month_aucs" => month_aucs, "confusions" => [],
+ "sweep" => [ { "threshold" => 0.4, "right" => right + 10, "wrong" => settings.binary ? 20 : 12 },
+ { "threshold" => 0.8, "right" => right, "wrong" => 10 } ] }
+ end
+
+ def search(&)
+ searched << month_labels
+ super
+ end
+ end
+end
diff --git a/test/models/family/bayes_settings_test.rb b/test/models/family/bayes_settings_test.rb
new file mode 100644
index 0000000000..69abfe12f3
--- /dev/null
+++ b/test/models/family/bayes_settings_test.rb
@@ -0,0 +1,74 @@
+require "test_helper"
+
+class Family::BayesSettingsTest < ActiveSupport::TestCase
+ test "defaults when nothing is stored" do
+ settings = Family::BayesSettings.new
+
+ assert_equal 0.7, settings.threshold
+ assert_not settings.complement
+ assert_equal [], settings.excluded_category_ids
+ assert settings.default?
+ assert_equal({}, settings.to_stored)
+ end
+
+ test "coerces form values, clamps numbers and drops unknown keys" do
+ settings = Family::BayesSettings.new(
+ "threshold" => "2", "smoothing" => "not a number", "skip_self_labels" => "0", "bigrams" => "1",
+ "max_training_transactions" => "7", "word_split" => "klingon", "bogus" => "1",
+ "excluded_category_ids" => [ "b", "a", "a", "" ]
+ )
+
+ assert_equal 0.99, settings.threshold
+ assert_equal 1.0, settings.smoothing
+ assert_equal false, settings.skip_self_labels
+ assert_equal true, settings.bigrams
+ assert_equal 100, settings.max_training_transactions
+ assert_equal "ascii", settings.word_split
+ assert_equal %w[a b], settings.excluded_category_ids
+ assert_not settings.values.key?(:bogus)
+ end
+
+ test "the matcher's numbers stay within what the page offers" do
+ settings = Family::BayesSettings.new("similar_threshold" => "1.5", "similar_min_neighbours" => "9", "similar_common_share" => "0")
+
+ assert_equal 0.99, settings.similar_threshold
+ assert_equal 3, settings.similar_min_neighbours
+ assert_equal 0.01, settings.similar_common_share
+ assert_equal 0.5, Family::BayesSettings.new("similar_threshold" => "0.1").similar_threshold
+ end
+
+ test "stores only differences from the defaults" do
+ settings = Family::BayesSettings.new(threshold: 0.7, bigrams: true, smoothing: 0.1)
+
+ assert_equal({ "bigrams" => true, "smoothing" => 0.1 }, settings.to_stored)
+ assert_equal settings.values, Family::BayesSettings.new(settings.to_stored).values
+ end
+
+ test "digest is stable and follows the values" do
+ assert_equal Family::BayesSettings.new.digest, Family::BayesSettings.new(threshold: "0.7").digest
+ assert_not_equal Family::BayesSettings.new.digest, Family::BayesSettings.new(threshold: 0.5).digest
+ end
+
+ test "merge keeps earlier changes" do
+ settings = Family::BayesSettings.new(bigrams: true).merge(threshold: "0.6")
+
+ assert settings.bigrams
+ assert_equal 0.6, settings.threshold
+ end
+
+ test "family update merges and resets blank numbers" do
+ family = Family.create!(name: "Settings family")
+ category = family.categories.create!(name: "Mine")
+
+ family.update_bayes_settings!(excluded_category_ids: [ category.id ], threshold: "0.6")
+ family.update_bayes_settings!(bigrams: "1")
+
+ settings = family.reload.bayes_settings_object
+ assert_equal [ category.id.to_s ], settings.excluded_category_ids
+ assert_equal 0.6, settings.threshold
+ assert settings.bigrams
+
+ family.update_bayes_settings!(threshold: "")
+ assert_equal 0.7, family.reload.bayes_settings_object.threshold
+ end
+end
diff --git a/test/models/family/classifier_rules_test.rb b/test/models/family/classifier_rules_test.rb
new file mode 100644
index 0000000000..bb8b81361e
--- /dev/null
+++ b/test/models/family/classifier_rules_test.rb
@@ -0,0 +1,103 @@
+require "test_helper"
+
+class Family::ClassifierRulesTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ @family = Family.create!(name: "Classifier rules family")
+ @account = @family.accounts.create!(name: "Rules test", balance: 100, currency: "USD", accountable: Depository.new)
+ @coffee = @family.categories.create!(name: "Coffee")
+ @groceries = @family.categories.create!(name: "Groceries")
+ @tag = @family.tags.create!(name: "Review")
+ end
+
+ test "a new family gets the matcher and Bayes at the top of its rules, on" do
+ rules = @family.rules.ordered.includes(:actions)
+
+ assert_equal [ [ "Merchant matcher", 1, true, "fill_similar_merchants" ], [ "Category classifier", 2, true, "bayes_categorize" ] ],
+ rules.map { |rule| [ rule.name, rule.position, rule.active?, rule.actions.sole.action_type ] }
+ assert rules.all? { |rule| rule.conditions.none? }
+ end
+
+ test "an added rule goes in at the top, the others moving down" do
+ mine = name_rule("Mine", "Starbucks", tags: [ @tag ])
+ @family.classifier_rules("bayes_categorize").destroy_all
+ @family.classifier_rules("fill_similar_merchants").destroy_all
+
+ @family.add_classifier_rule!("bayes_categorize")
+ @family.add_classifier_rule!("fill_similar_merchants")
+ @family.classifier_rules("bayes_categorize").destroy_all
+ @family.add_classifier_rule!("bayes_categorize")
+
+ # A deleted rule leaves a gap in the numbers, as any does; the order holds.
+ assert_equal [ "Category classifier", "Merchant matcher", "Mine" ], @family.rules.ordered.map(&:name)
+ assert_equal [ 1, 2 ], @family.rules.ordered.first(2).map(&:position)
+ assert_operator mine.reload.position, :>, 2
+ end
+
+ test "the switch is whether the rule is on" do
+ @family.set_classifier_rule_active!("bayes_categorize", false)
+
+ assert_not @family.classifier_rule_active?("bayes_categorize")
+ assert @family.classifier_rule_active?("fill_similar_merchants")
+ @family.classifier_rules("bayes_categorize").destroy_all
+ assert_not @family.classifier_rule_active?("bayes_categorize")
+ end
+
+ test "Bayes categorizes in the rule run, and a rule below it can still change its pick" do
+ train_two_categories
+ picked = uncategorized("Starbucks Coffee")
+ corrected = uncategorized("Starbucks Coffee beans")
+ name_rule("Beans", "beans", category: @groceries)
+
+ ApplyRulesJob.perform_now(@family)
+
+ assert_equal @coffee, picked.reload.category
+ assert_equal "bayes", picked.data_enrichments.find_by(attribute_name: "category_id").source
+ assert_equal @groceries, corrected.reload.category
+ end
+
+ test "a rule moved above Bayes that stops processing keeps Bayes off its transactions" do
+ train_two_categories
+ held = uncategorized("Starbucks Coffee")
+ exception = name_rule("Hold for review", "Starbucks", tags: [ @tag ], stop_processing: true)
+ Rule.update_positions!(@family, [ exception.id ] + (@family.rules.ordered.ids - [ exception.id ]))
+
+ ApplyRulesJob.perform_now(@family)
+
+ assert_nil held.reload.category
+ assert_includes held.tags, @tag
+ end
+
+ test "applying a rule below them runs the matcher and Bayes first" do
+ train_two_categories
+ transaction = uncategorized("Starbucks Coffee")
+ tagging = name_rule("Tag coffee", "Starbucks", tags: [ @tag ])
+
+ RuleJob.perform_now(tagging)
+
+ assert_equal @coffee, transaction.reload.category
+ assert_includes transaction.tags, @tag
+ end
+
+ private
+ # 10 coffee + 10 groceries, so the Bayes training guard passes (as in
+ # AutoCategorizeTransactionsTest).
+ def train_two_categories
+ 10.times { create_transaction(account: @account, name: "Starbucks Coffee", category: @coffee) }
+ 10.times { create_transaction(account: @account, name: "Safeway Groceries", category: @groceries) }
+ end
+
+ def uncategorized(name)
+ create_transaction(account: @account, name: name).transaction
+ end
+
+ def name_rule(name, match, category: nil, tags: nil, stop_processing: false)
+ actions = []
+ actions << Rule::Action.new(action_type: "set_transaction_category", value: category.id) if category
+ actions << Rule::Action.new(action_type: "set_transaction_tags", value: tags.map(&:id)) if tags
+ @family.rules.create!(name: name, resource_type: "transaction", active: true, stop_processing: stop_processing,
+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: match) ],
+ actions: actions)
+ end
+end
diff --git a/test/models/family/similar_matcher_test.rb b/test/models/family/similar_matcher_test.rb
new file mode 100644
index 0000000000..e9c89e9a20
--- /dev/null
+++ b/test/models/family/similar_matcher_test.rb
@@ -0,0 +1,56 @@
+require "test_helper"
+
+class Family::SimilarMatcherTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ @family = Family.create!(name: "Similar family")
+ @account = @family.accounts.create!(name: "Similar", balance: 0, currency: "USD", accountable: Depository.new)
+ @streaming = @family.categories.create!(name: "Streaming")
+ @groceries = @family.categories.create!(name: "Groceries")
+ @netflix = @family.merchants.create!(name: "Netflix")
+ end
+
+ def transaction(name, **attributes)
+ create_transaction(account: @account, name: name, **attributes).transaction
+ end
+
+ def matcher(pool, threshold: 0.8, min_neighbours: 2)
+ Family::SimilarMatcher.new(pool, threshold: threshold, min_neighbours: min_neighbours, common_share: 0.2)
+ end
+
+ test "matches the same description written differently, ignoring numbers and codes" do
+ pool = [ transaction("NETFLIX.COM 8812 REF 4K22X9"), transaction("Safeway Groceries 0042") ]
+
+ neighbours = matcher(pool).neighbours(transaction("Netflix com 1203 REF 7Q91Z3"))
+
+ assert_equal [ pool.first ], neighbours.map(&:first)
+ assert_in_delta 1.0, neighbours.first.last, 0.001
+ end
+
+ test "agrees only when enough neighbours have one value and none another" do
+ pool = [ transaction("Netflix com", category: @streaming, merchant: @netflix),
+ transaction("NETFLIX.COM", category: @streaming),
+ transaction("Netflix.com", merchant: @netflix) ]
+ query = transaction("NETFLIX COM")
+
+ assert_equal @streaming.id, matcher(pool).agreed(query, :category_id)
+ assert_equal @netflix.id, matcher(pool).agreed(query, :merchant_id)
+ assert_nil matcher(pool, min_neighbours: 3).agreed(query, :category_id)
+
+ pool << transaction("Netflix com", category: @groceries)
+ assert_nil matcher(pool).agreed(query, :category_id)
+ end
+
+ test "a different shop isn't a neighbour" do
+ pool = [ transaction("Safeway Groceries"), transaction("Trader Joes Groceries") ]
+
+ assert_equal [], matcher(pool).neighbours(transaction("Whole Foods Groceries")).map(&:first)
+ end
+
+ test "never matches the transaction itself" do
+ own = transaction("Netflix com", category: @streaming)
+
+ assert_equal [], matcher([ own ], min_neighbours: 1).neighbours(own)
+ end
+end
diff --git a/test/models/family/similar_merchant_filler_test.rb b/test/models/family/similar_merchant_filler_test.rb
new file mode 100644
index 0000000000..d63017bde5
--- /dev/null
+++ b/test/models/family/similar_merchant_filler_test.rb
@@ -0,0 +1,106 @@
+require "test_helper"
+
+class Family::SimilarMerchantFillerTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ @family = Family.create!(name: "Merchant fill family")
+ @account = @family.accounts.create!(name: "Merchant fill", balance: 0, currency: "USD", accountable: Depository.new)
+ @netflix = @family.merchants.create!(name: "Netflix")
+ @hulu = @family.merchants.create!(name: "Hulu")
+ end
+
+ def transaction(name, **attributes)
+ create_transaction(account: @account, name: name, **attributes).transaction
+ end
+
+ # A copy the matcher made and locked itself.
+ def fill_from_hulu(transaction)
+ transaction.enrich_attribute(:merchant_id, @hulu.id, source: "similar", metadata: { locked_by_similar: true })
+ transaction.lock_attr!(:merchant_id)
+ end
+
+ def fill(*transactions, **settings)
+ Family::SimilarMerchantFiller.new(@family, settings: Family::BayesSettings.new(settings)).fill(transactions.map(&:id))
+ end
+
+ test "copies the merchant two near-duplicates agree on, as a similar enrichment" do
+ 2.times { transaction("NETFLIX.COM 8812", merchant: @netflix) }
+ missing = transaction("Netflix com 1203")
+
+ assert_equal 1, fill(missing)
+ assert_equal @netflix.id, missing.reload.merchant_id
+ assert_equal "similar", missing.data_enrichments.find_by(attribute_name: "merchant_id").source
+ end
+
+ test "leaves it alone with one near-duplicate, a disagreement or a lock" do
+ transaction("NETFLIX.COM 8812", merchant: @netflix)
+ missing = transaction("Netflix com 1203")
+
+ assert_equal 0, fill(missing)
+
+ transaction("Netflix com", merchant: @hulu)
+ transaction("NETFLIX COM", merchant: @netflix)
+ assert_equal 0, fill(missing)
+
+ locked = transaction("Hulu LLC")
+ locked.lock_attr!(:merchant_id)
+ 2.times { transaction("HULU LLC", merchant: @hulu) }
+ assert_equal 0, fill(locked)
+ assert_nil locked.reload.merchant_id
+ end
+
+ test "an AI merchant is copied, but not its own unconfirmed copy" do
+ 2.times { transaction("NETFLIX.COM 8812").tap { |t| t.enrich_attribute(:merchant_id, @netflix.id, source: "ai") } }
+ missing = transaction("Netflix com 1203")
+
+ assert_equal 1, fill(missing)
+
+ copies = Array.new(2) { transaction("HULU LLC 77").tap { |t| t.enrich_attribute(:merchant_id, @hulu.id, source: "similar") } }
+ hulu = transaction("Hulu LLC 12")
+ assert_equal 0, fill(hulu)
+
+ copies.each { |copy| copy.lock_attr!(:merchant_id) }
+ assert_equal 1, fill(hulu)
+ end
+
+ test "with lock_similar_merchants it locks what it fills, without that counting as confirmed" do
+ 2.times { transaction("NETFLIX.COM 8812", merchant: @netflix) }
+ missing = transaction("Netflix com 1203")
+
+ assert_equal 1, fill(missing, lock_similar_merchants: true)
+ assert missing.reload.locked?(:merchant_id)
+ assert missing.data_enrichments.find_by(attribute_name: "merchant_id").metadata["locked_by_similar"]
+
+ copies = Array.new(2) { transaction("Hulu LLC 77").tap { |t| fill_from_hulu(t) } }
+ assert copies.all? { |copy| copy.reload.locked?(:merchant_id) }
+ assert_equal 0, fill(transaction("HULU LLC 12"))
+ end
+
+ test "its own copies count when that check is off" do
+ 2.times { transaction("HULU LLC 77").tap { |t| t.enrich_attribute(:merchant_id, @hulu.id, source: "similar") } }
+ assert_equal 1, fill(transaction("Hulu LLC 12"), similar_skip_self: false)
+ end
+
+ test "transfers neither give nor get merchants" do
+ bank = @family.merchants.create!(name: "CBA")
+ 2.times { transaction("Savings top-up", merchant: bank, kind: "funds_movement") }
+ transfer = transaction("Savings top up", kind: "funds_movement")
+ missing = transaction("Savings top-up")
+
+ assert_equal 0, fill(transfer, missing)
+ end
+
+ test "the family fills only the missing merchants in scope, and Bayes fills none" do
+ 2.times { transaction("NETFLIX.COM 8812", merchant: @netflix) }
+ missing = transaction("Netflix com 1203")
+ elsewhere = transaction("Netflix com 5531")
+
+ @family.bayes_categorize_uncategorized
+ assert_nil missing.reload.merchant_id
+
+ assert_equal 1, @family.fill_similar_merchants(@family.transactions.where(id: missing.id))
+ assert_equal @netflix.id, missing.reload.merchant_id
+ assert_nil elsewhere.reload.merchant_id
+ end
+end
diff --git a/test/models/import_session_test.rb b/test/models/import_session_test.rb
index 2707a1aaf1..45525aaa88 100644
--- a/test/models/import_session_test.rb
+++ b/test/models/import_session_test.rb
@@ -576,6 +576,8 @@ class ImportSessionTest < ActiveSupport::TestCase
test "session mode imports rule records exported by Sure packages" do
source_family = Family.create!(name: "Rule Export Source", currency: "USD", locale: "en")
+ # Without the matcher and Bayes rules a new family starts with.
+ source_family.rules.destroy_all
category = source_family.categories.create!(
name: "Exported Category",
color: "#00AA00",
diff --git a/test/models/rule/registry/transaction_resource_test.rb b/test/models/rule/registry/transaction_resource_test.rb
index f1a4b209e1..b6368bcdb1 100644
--- a/test/models/rule/registry/transaction_resource_test.rb
+++ b/test/models/rule/registry/transaction_resource_test.rb
@@ -49,6 +49,17 @@ class Rule::Registry::TransactionResourceTest < ActiveSupport::TestCase
assert_includes keys, "auto_detect_merchants"
end
+ test "the matcher and Bayes are offered without any provider" 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_includes keys, "fill_similar_merchants"
+ assert_includes keys, "bayes_categorize"
+ end
+
private
def build_rule(action_type:)
@family.rules.create!(
diff --git a/test/models/rule_position_concurrency_test.rb b/test/models/rule_position_concurrency_test.rb
index 8c1817dd11..e5551dd385 100644
--- a/test/models/rule_position_concurrency_test.rb
+++ b/test/models/rule_position_concurrency_test.rb
@@ -11,6 +11,8 @@ class RulePositionConcurrencyTest < ActiveSupport::TestCase
setup do
@family = Family.create!(name: "Rule Position Race", currency: "USD")
+ # Without the matcher and Bayes rules a new family starts with.
+ @family.rules.destroy_all
end
teardown do
diff --git a/test/models/transaction/reassign_category_concurrency_test.rb b/test/models/transaction/reassign_category_concurrency_test.rb
index db6548c7fd..c505fa848d 100644
--- a/test/models/transaction/reassign_category_concurrency_test.rb
+++ b/test/models/transaction/reassign_category_concurrency_test.rb
@@ -33,6 +33,7 @@ class Transaction::ReassignCategoryConcurrencyTest < ActiveSupport::TestCase
Category.where(family_id: @family.id).delete_all if @family
Account.where(id: @account.id).delete_all if @account
Depository.where(id: @account.accountable_id).delete_all if @account
+ Rule.where(family_id: @family.id).destroy_all if @family
Family.where(id: @family.id).delete_all if @family
end
diff --git a/test/models/transaction_test.rb b/test/models/transaction_test.rb
index bf07722836..ddc3c1fb74 100644
--- a/test/models/transaction_test.rb
+++ b/test/models/transaction_test.rb
@@ -564,6 +564,26 @@ class TransactionTest < ActiveSupport::TestCase
assert_equal [ tags(:one).id, tags(:two).id ].sort, transaction.reload.tag_ids.sort
end
+ test "category_from finds categories still set by a given source" do
+ family = families(:empty)
+ account = family.accounts.create!(name: "Category from", balance: 0, currency: "USD", accountable: Depository.new)
+ coffee = family.categories.create!(name: "Coffee")
+ tea = family.categories.create!(name: "Tea")
+ ai_guess = create_transaction(account: account, name: "Guess").transaction
+ ai_guess.enrich_attribute(:category_id, coffee.id, source: "ai", metadata: { confidence: 0.9 })
+ changed = create_transaction(account: account, name: "Changed").transaction
+ changed.enrich_attribute(:category_id, coffee.id, source: "ai")
+ changed.update!(category: tea)
+ scope = family.transactions
+
+ assert_equal [ ai_guess.id ], scope.category_from("ai").pluck(:id)
+ assert_equal [ ai_guess.id ], scope.category_from("bayes", "ai").pluck(:id)
+ assert_empty scope.category_from("bayes").pluck(:id)
+ assert_empty scope.category_from("ai", since: 1.minute.from_now).pluck(:id)
+ assert_equal [ ai_guess.id ], scope.category_from("ai", metadata: { confidence: 0.9 }).pluck(:id)
+ assert_empty scope.category_from("ai", metadata: { confidence: 0.5 }).pluck(:id)
+ end
+
private
# Whether each SQL form of "is this transaction pending?" says it is.
def sql_pending_answers(transaction)