Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Speed up the rules list: preload actions, share option lists (#4686)

GFR54ac78c2ef80
diff --git a/app/controllers/rules_controller.rb b/app/controllers/rules_controller.rb
index d51d9e7b32..95811f67ef 100644
--- a/app/controllers/rules_controller.rb
+++ b/app/controllers/rules_controller.rb
@@ -5,7 +5,8 @@ class RulesController < ApplicationController
before_action :set_rule, only: [ :edit, :update, :destroy, :apply, :confirm ]
def index
- @rules = Current.family.rules.includes(conditions: :sub_conditions).ordered
+ @rules = Current.family.rules.includes(:actions, conditions: :sub_conditions).ordered.to_a
+ Rule.share_option_lists(@rules)
# Fetch recent rule runs with pagination
recent_runs_scope = RuleRun
diff --git a/app/models/rule.rb b/app/models/rule.rb
index 6ac6c43217..bf54956eeb 100644
--- a/app/models/rule.rb
+++ b/app/models/rule.rb
@@ -294,6 +294,33 @@ class Rule < ApplicationRecord
displayable_conditions.first
end
+ # The action the rule list shows: the saved one `actions.first` loads (lowest
+ # id), picked from preloaded actions without a query.
+ def displayed_action
+ actions.select(&:persisted?).min_by(&:id)
+ end
+
+ # Option lists (categories, merchants, accounts) that conditions and actions
+ # look their values up in, loaded once per key. They depend only on the family
+ # and the current user, so rules listed together share one cache
+ # (.share_option_lists).
+ attr_writer :option_lists
+
+ def option_list(key)
+ @option_lists ||= {}
+ @option_lists.fetch(key) { @option_lists[key] = yield }
+ end
+
+ def self.share_option_lists(rules)
+ option_lists = {}
+ rules.each { |rule| rule.option_lists = option_lists }
+ end
+
+ def reload(*)
+ @option_lists = nil
+ super
+ end
+
def additional_displayable_conditions_count
[ displayable_conditions.size - 1, 0 ].max
end
diff --git a/app/models/rule/action.rb b/app/models/rule/action.rb
index 8989ed1654..5969e1eb0f 100644
--- a/app/models/rule/action.rb
+++ b/app/models/rule/action.rb
@@ -94,7 +94,7 @@ class Rule::Action < ApplicationRecord
end
def options
- executor.options
+ rule.option_list([ :action, action_type ]) { executor.options }
end
def claimed_attributes
diff --git a/app/models/rule/condition.rb b/app/models/rule/condition.rb
index 4132c522ae..7df22a71f4 100644
--- a/app/models/rule/condition.rb
+++ b/app/models/rule/condition.rb
@@ -95,7 +95,7 @@ class Rule::Condition < ApplicationRecord
end
def options
- filter.options
+ rule.option_list([ :condition, condition_type ]) { filter.options }
end
def operators
diff --git a/app/models/rule/registry/transaction_resource.rb b/app/models/rule/registry/transaction_resource.rb
index a6053ac120..1b8877467b 100644
--- a/app/models/rule/registry/transaction_resource.rb
+++ b/app/models/rule/registry/transaction_resource.rb
@@ -52,13 +52,34 @@ class Rule::Registry::TransactionResource < Rule::Registry
end
end
+ # Single lookups build only the class asked for, once per registry: listing
+ # every filter or executor checks the AI providers on each call, and a rule
+ # list looks up each condition and action several times.
+ def get_filter!(key)
+ @filters_by_key ||= {}
+ @filters_by_key[key] ||= begin
+ filter_class = CONDITION_FILTER_CLASSES.find { |klass| klass.key == key }
+ raise UnsupportedConditionError, "Unsupported condition type: #{key}" unless filter_class
+ filter_class.new(rule)
+ end
+ end
+
+ def get_executor!(key)
+ @executors_by_key ||= {}
+ @executors_by_key[key] ||= begin
+ executor_class = ACTION_EXECUTOR_CLASSES.find { |klass| klass.key == key }
+ raise UnsupportedActionError, "Unsupported action type: #{key}" unless executor_class && offered?(executor_class)
+ executor_class.new(rule)
+ end
+ end
+
private
def offered?(executor_class)
case executor_class.key
when "auto_categorize"
- auto_categorization_enabled? || existing_action?("auto_categorize")
+ existing_action?("auto_categorize") || auto_categorization_enabled?
when "auto_detect_merchants"
- auto_merchant_detection_enabled? || existing_action?("auto_detect_merchants")
+ existing_action?("auto_detect_merchants") || auto_merchant_detection_enabled?
else
true
end
diff --git a/app/views/rules/_rule.html.erb b/app/views/rules/_rule.html.erb
index 27ce6e52ed..112d601641 100644
--- a/app/views/rules/_rule.html.erb
+++ b/app/views/rules/_rule.html.erb
@@ -39,18 +39,19 @@
</div>
<p class="flex min-w-0 items-center flex-wrap gap-x-1.5 gap-y-1 m-0">
<span class="max-w-full truncate px-2 py-1 border border-secondary rounded-full">
- <% if rule.actions.first.nil? %>
+ <% displayed_action = rule.displayed_action %>
+ <% if displayed_action.nil? %>
<%= t("rules.no_action") %>
<% else %>
- <% if rule.actions.first.value && rule.actions.first.options %>
- <%= t(".action_label_to", label: rule.actions.first.executor.label, value: rule.actions.first.value_display) %>
+ <% if displayed_action.value && displayed_action.options %>
+ <%= t(".action_label_to", label: displayed_action.executor.label, value: displayed_action.value_display) %>
<% else %>
- <%= rule.actions.first.executor.label %>
+ <%= displayed_action.executor.label %>
<% end %>
<% end %>
</span>
- <% if rule.actions.count > 1 %>
- <%= t(".and_more_actions", count: rule.actions.count - 1) %>
+ <% if rule.actions.size > 1 %>
+ <%= t(".and_more_actions", count: rule.actions.size - 1) %>
<% end %>
</p>
</div>
diff --git a/test/controllers/rules_controller_test.rb b/test/controllers/rules_controller_test.rb
index 9c3cc43d50..2a0ccdb7eb 100644
--- a/test/controllers/rules_controller_test.rb
+++ b/test/controllers/rules_controller_test.rb
@@ -319,6 +319,28 @@ class RulesControllerTest < ActionDispatch::IntegrationTest
assert_equal ordered_ids, css_select("[data-sortable-list-target='item']").map { |item| item["data-sortable-list-id"] }
end
+ test "index runs the same number of queries however many rules it lists" do
+ family = @user.family
+ create_listed_rule = lambda do
+ family.rules.create!(resource_type: "transaction",
+ conditions: [ Rule::Condition.new(condition_type: "transaction_merchant", operator: "=", value: merchants(:netflix).id) ],
+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: categories(:food_and_drink).id),
+ Rule::Action.new(action_type: "exclude_transaction") ])
+ end
+ 2.times { create_listed_rule.call }
+
+ # Each capture follows a write, which clears the query cache tests keep
+ # across requests.
+ queries_with_few = capture_sql_queries { get rules_url }.size
+
+ 4.times { create_listed_rule.call }
+ queries_with_more = capture_sql_queries { get rules_url }.size
+
+ assert_response :success
+ assert_equal queries_with_few, queries_with_more
+ assert_select "span", text: /Netflix/, minimum: 6
+ end
+
test "reorder saves the new order" do
family = @user.family
second = family.rules.create!(resource_type: "transaction",
diff --git a/test/models/rule/registry/transaction_resource_test.rb b/test/models/rule/registry/transaction_resource_test.rb
index b6368bcdb1..a399669a6a 100644
--- a/test/models/rule/registry/transaction_resource_test.rb
+++ b/test/models/rule/registry/transaction_resource_test.rb
@@ -60,6 +60,41 @@ class Rule::Registry::TransactionResourceTest < ActiveSupport::TestCase
assert_includes keys, "bayes_categorize"
end
+ test "get_executor! refuses an auto action that is not offered" do
+ rule = build_rule(action_type: "exclude_transaction")
+ @family.stubs(:resolved_categorization_provider).returns(nil)
+ Provider::Registry.stubs(:preferred_llm_provider).returns(nil)
+
+ assert_raises(Rule::Registry::UnsupportedActionError) { rule.registry.get_executor!("auto_categorize") }
+ assert_raises(Rule::Registry::UnsupportedActionError) { rule.registry.get_executor!("unknown") }
+ assert_instance_of Rule::ActionExecutor::ExcludeTransaction, rule.registry.get_executor!("exclude_transaction")
+ end
+
+ test "get_filter! builds only the requested filter and reuses it" do
+ rule = build_rule(action_type: "exclude_transaction")
+
+ filter = rule.registry.get_filter!("transaction_merchant")
+
+ assert_instance_of Rule::ConditionFilter::TransactionMerchant, filter
+ assert_same filter, rule.registry.get_filter!("transaction_merchant")
+ assert_raises(Rule::Registry::UnsupportedConditionError) { rule.registry.get_filter!("unknown") }
+ end
+
+ test "looking up an ordinary action does not check the AI providers" do
+ rule = build_rule(action_type: "exclude_transaction")
+ @family.expects(:resolved_categorization_provider).never
+ Provider::Registry.expects(:preferred_llm_provider).never
+
+ assert_instance_of Rule::ActionExecutor::ExcludeTransaction, rule.actions.first.executor
+ end
+
+ test "an existing auto action is looked up without checking the providers" do
+ rule = build_rule(action_type: "auto_categorize")
+ @family.expects(:resolved_categorization_provider).never
+
+ assert_instance_of Rule::ActionExecutor::AutoCategorize, rule.actions.first.executor
+ end
+
private
def build_rule(action_type:)
@family.rules.create!(
diff --git a/test/models/rule_test.rb b/test/models/rule_test.rb
index 5d1780588e..55721be837 100644
--- a/test/models/rule_test.rb
+++ b/test/models/rule_test.rb
@@ -10,6 +10,21 @@ class RuleTest < ActiveSupport::TestCase
@groceries_category = @family.categories.create!(name: "Groceries")
end
+ test "displayed_action skips an unsaved action and option lists reset on reload" do
+ rule = @family.rules.create!(resource_type: "transaction",
+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @groceries_category.id) ])
+ saved = rule.actions.first
+ rule.actions.build(action_type: "exclude_transaction")
+
+ assert_equal saved, rule.displayed_action
+
+ assert_equal "Groceries", saved.value_display
+ @groceries_category.update!(name: "Food")
+ rule.reload
+
+ assert_equal "Food", rule.actions.first.value_display
+ end
+
test "rejects a null byte in the rule name" do
rule = @family.rules.build(name: "bad\0name", resource_type: "transaction")
rule.actions.build(action_type: "exclude_transaction")