The personal finance app for everyone (by everyone)
Ruby
perf(accounts): kill sidebar/sparkline N+1s and cache the sidebar (#1683)
GermanDZ7e1de420cae7
diff --git a/app/controllers/accountable_sparklines_controller.rb b/app/controllers/accountable_sparklines_controller.rbindex 9ba69ff560..e325007737 100644--- a/app/controllers/accountable_sparklines_controller.rb+++ b/app/controllers/accountable_sparklines_controller.rb@@ -43,8 +43,14 @@ class AccountableSparklinesController < ApplicationController).balance_seriesend+ # balance_type is derived purely from accountable_type, so only Investment/Crypto+ # can yield :investment. Short-circuit to avoid an N+1 `account.linked?` check+ # on every account for non-investment accountable types (loan, credit_card, etc).+ # The `Account.linked` scope is the SQL-level mirror of `Account#linked?`.def requires_normalized_aggregation?- accounts.any? { |account| account.linked? && account.balance_type == :investment }+ return false unless %w[Investment Crypto].include?(@accountable.name)++ accounts.linked.exists?enddef aggregate_normalized_seriesdiff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rbindex f7a4510be1..efe9bec08c 100644--- a/app/controllers/accounts_controller.rb+++ b/app/controllers/accounts_controller.rb@@ -10,6 +10,7 @@ class AccountsController < ApplicationController@manual_accounts = family.accounts.listable_manual.where(id: @accessible_account_ids)+ .includes(:accountable, :account_providers, :plaid_account, :simplefin_account).order(:name)@plaid_items = visible_provider_items(family.plaid_items.ordered.includes(:syncs, :plaid_accounts))@simplefin_items = visible_provider_items(family.simplefin_items.ordered.includes(:syncs))diff --git a/app/helpers/accounts_helper.rb b/app/helpers/accounts_helper.rbindex 99ef891ce2..a119246fda 100644--- a/app/helpers/accounts_helper.rb+++ b/app/helpers/accounts_helper.rb@@ -8,4 +8,41 @@ module AccountsHelper# Always use the account sync path, which handles syncing all providerssync_account_path(account)end++ # Returns the account id segment from `/accounts/<id>(/...)?`, or nil.+ # Used as a cache-key component so the sidebar's active-link styling is+ # correct without busting the cache for every unrelated path change.+ def sidebar_active_account_id+ match = request.path.match(%r{\A/accounts/([\w-]+)})+ match && match[1]+ end++ # Cache key for `accounts/_account_sidebar_tabs.html.erb`.+ # Kept here (not in the ERB) so the partial stays render-only.+ #+ # `shares_version` includes both row count and `max(updated_at)` because+ # deleting a non-most-recent share would not move `max(updated_at)` and+ # could otherwise serve stale fragments to a user who lost access.+ # Both are pulled in a single SQL round-trip via `pick`. Note: Rails+ # returns the values as Strings for raw SQL fragments — that's fine+ # since they only feed into a cache key (concat-stable, never coerced).+ def account_sidebar_tabs_cache_key(family:, active_tab:, mobile:)+ shares_version =+ if Current.user+ count, max_at = AccountShare+ .where(user_id: Current.user.id)+ .pick(Arel.sql("count(*)"), Arel.sql("max(updated_at)"))+ "#{count}-#{max_at}"+ end++ [+ family.build_cache_key("account_sidebar_tabs_v1", invalidate_on_data_updates: true),+ Current.user&.id,+ shares_version,+ active_tab,+ mobile,+ I18n.locale,+ sidebar_active_account_id+ ]+ endenddiff --git a/app/models/account/linkable.rb b/app/models/account/linkable.rbindex d3830ddda2..b91d4ed833 100644--- a/app/models/account/linkable.rb+++ b/app/models/account/linkable.rb@@ -8,6 +8,17 @@ module Account::Linkable# Legacy provider associations - kept for backward compatibility during migrationbelongs_to :plaid_account, optional: truebelongs_to :simplefin_account, optional: true++ # SQL-level mirror of `linked?`. Use this for set-based checks (e.g. bulk+ # `EXISTS`) so both definitions stay in sync. If `linked?` adds a new+ # provider source, update this scope too.+ scope :linked, -> {+ left_outer_joins(:account_providers)+ .where(+ "account_providers.id IS NOT NULL OR accounts.plaid_account_id IS NOT NULL OR accounts.simplefin_account_id IS NOT NULL"+ )+ .distinct+ }end# A "linked" account gets transaction and balance data from a third party like Plaid or SimpleFindiff --git a/app/models/balance_sheet/account_totals.rb b/app/models/balance_sheet/account_totals.rbindex d033404238..5c767687f7 100644--- a/app/models/balance_sheet/account_totals.rb+++ b/app/models/balance_sheet/account_totals.rb@@ -27,7 +27,14 @@ class BalanceSheet::AccountTotalsdef visible_accounts@visible_accounts ||= begin- scope = family.accounts.visible.with_attached_logo.includes(:account_shares)+ scope = family.accounts.visible.with_attached_logo+ .includes(+ :account_shares,+ :accountable,+ :plaid_account,+ :simplefin_account,+ account_providers: :provider+ )scope = scope.accessible_by(user) if userscopeenddiff --git a/app/views/accounts/_account_sidebar_tabs.html.erb b/app/views/accounts/_account_sidebar_tabs.html.erbindex ae6f793d8d..653a64c857 100644--- a/app/views/accounts/_account_sidebar_tabs.html.erb+++ b/app/views/accounts/_account_sidebar_tabs.html.erb@@ -1,5 +1,6 @@<%# locals: (family:, active_tab:, mobile: false) %>+<% cache account_sidebar_tabs_cache_key(family: family, active_tab: active_tab, mobile: mobile), expires_in: 12.hours do %><div id="account-sidebar-tabs"><% if family.missing_data_provider? %><details class="group bg-yellow-tint-10 rounded-lg p-2 text-yellow-600 mb-3 text-xs">@@ -88,3 +89,4 @@<% end %><% end %></div>+<% end %>diff --git a/app/views/accounts/index/_account_groups.erb b/app/views/accounts/index/_account_groups.erbindex 05aa2709f2..79709142e2 100644--- a/app/views/accounts/index/_account_groups.erb+++ b/app/views/accounts/index/_account_groups.erb@@ -1,6 +1,11 @@<%# locals: (accounts:) %>-<% ActiveRecord::Associations::Preloader.new(records: accounts, associations: :account_shares).call if accounts.any? %>+<% if accounts.any? %>+ <% ActiveRecord::Associations::Preloader.new(+ records: accounts,+ associations: [ :account_shares, :accountable, :plaid_account, :simplefin_account, { account_providers: :provider } ]+ ).call %>+<% end %><% accounts.group_by(&:accountable_type).sort_by { |group, _| group }.each do |group, accounts| %><div class="bg-container-inset p-1 rounded-xl"><div class="flex items-center px-4 py-2 text-xs font-medium text-secondary">diff --git a/test/models/account/linkable_test.rb b/test/models/account/linkable_test.rbindex a02453c39c..560cb56495 100644--- a/test/models/account/linkable_test.rb+++ b/test/models/account/linkable_test.rb@@ -66,4 +66,45 @@ class Account::LinkableTest < ActiveSupport::TestCaseassert @account.can_delete_holdings?end++ # The `linked` scope mirrors `linked?` at the SQL level. These tests pin+ # all three link types so a future schema or `linked?` change breaks the+ # test instead of silently diverging (e.g. wrong sparkline aggregation).+ test "linked scope matches accounts linked via account_providers" do+ plaid_account = plaid_accounts(:one)+ AccountProvider.create!(account: @account, provider: plaid_account)++ assert_includes Account.linked, @account+ end++ test "linked scope matches accounts with legacy plaid_account_id" do+ plaid_account = plaid_accounts(:one)+ @account.update!(plaid_account: plaid_account)++ assert_includes Account.linked, @account+ end++ test "linked scope matches accounts with legacy simplefin_account_id" do+ simplefin_item = SimplefinItem.create!(+ family: @family,+ name: "Test SimpleFin",+ access_url: "https://example.com/access_token"+ )+ simplefin_account = SimplefinAccount.create!(+ simplefin_item: simplefin_item,+ name: "Test Account",+ account_id: "test-acct",+ currency: "USD",+ account_type: "checking",+ current_balance: 0+ )+ @account.update!(simplefin_account: simplefin_account)++ assert_includes Account.linked, @account+ end++ test "linked scope excludes manual accounts" do+ assert @account.unlinked?+ refute_includes Account.linked, @account+ endend