The personal finance app for everyone (by everyone)
Ruby
Settle resolution_pending placeholders instead of duplicating them (#5436)
Jason316a0d0e00dd
diff --git a/app/jobs/security_placeholder_settlement_job.rb b/app/jobs/security_placeholder_settlement_job.rbnew file mode 100644index 0000000000..068c6f6b2e--- /dev/null+++ b/app/jobs/security_placeholder_settlement_job.rb@@ -0,0 +1,15 @@+# Merges a blank-MIC "resolution_pending" placeholder into the listed security+# a later search found for its ticker. It runs after the resolving transaction+# commits, so records an import built in memory against the placeholder are+# already saved when their security row goes away.+class SecurityPlaceholderSettlementJob < ApplicationJob+ def perform(placeholder_id, security_id)+ placeholder = Security.find_by(id: placeholder_id)+ security = Security.find_by(id: security_id)+ return unless placeholder && security++ Security::Merger.new(from: placeholder, into: security).merge!(+ condition: ->(source) { source.exchange_operating_mic.blank? && source.offline? && source.offline_reason == "resolution_pending" }+ )+ end+enddiff --git a/app/models/security/merger.rb b/app/models/security/merger.rbnew file mode 100644index 0000000000..447ffa058c--- /dev/null+++ b/app/models/security/merger.rb@@ -0,0 +1,96 @@+# Folds one security row into another that stands for the same instrument and+# deletes it, moving everything that references it: holdings, trades, lots,+# prices, splits and tags. Rows the target already has for the same key win,+# except holdings, where the most recently written row for an+# (account, date, currency) is kept. Accounts that referenced the merged row+# are synced afterwards so their holdings and balances are rebuilt on one row.+class Security::Merger+ def initialize(from:, into:)+ @from = from+ @into = into+ end++ # `condition` is checked against the locked source row, for callers whose+ # reason to merge could have changed since they last read it.+ def merge!(condition: nil)+ return into if from.id == into.id++ account_ids = Security.transaction do+ locked = Security.where(id: [ from.id, into.id ]).order(:id).lock.to_a+ source = locked.find { |security| security.id == from.id }+ # A concurrent merge already removed the row.+ next [] unless locked.size == 2+ next [] if condition && !condition.call(source)++ referencing_account_ids.tap do+ now = Time.current+ move_holdings!(now)+ Trade.where(security_id: from.id).update_all(security_id: into.id, updated_at: now)+ move_lots!(now)+ move_unless_target_has(Security::Price, :date, :currency)+ move_unless_target_has(Security::Split, :ex_date)+ move_taggings!+ into.update!(name: from.name) if into.name.blank? && from.name.present?+ source.reload.destroy!+ end+ end++ Account.where(id: account_ids).find_each(&:sync_later)+ into+ end++ private+ attr_reader :from, :into++ def referencing_account_ids+ trade_entries = Entry.where(entryable_type: "Trade", entryable_id: Trade.where(security_id: from.id).select(:id))+ lots = HoldingLot.where(security_id: from.id).or(HoldingLot.where(origin_security_id: from.id))+ holdings = Holding.where(security_id: from.id).or(Holding.where(provider_security_id: from.id))++ [ holdings, trade_entries, lots ].flat_map { |scope| scope.distinct.pluck(:account_id) }.uniq+ end++ def move_holdings!(now)+ collisions = Holding.where(security_id: from.id)+ .joins(Holding.sanitize_sql_array([ <<~SQL, into.id ]))+ INNER JOIN holdings kept ON kept.security_id = ?+ AND kept.account_id = holdings.account_id+ AND kept.date = holdings.date+ AND kept.currency = holdings.currency+ SQL+ .pluck("holdings.id", "holdings.updated_at", "kept.id", "kept.updated_at")++ stale_ids = collisions.map { |id, updated_at, kept_id, kept_updated_at| updated_at > kept_updated_at ? kept_id : id }+ Holding.where(id: stale_ids).delete_all++ Holding.where(security_id: from.id).update_all(security_id: into.id, updated_at: now)+ Holding.where(provider_security_id: from.id).update_all(provider_security_id: into.id, updated_at: now)+ # A holding remapped away from a provider security that is now the+ # security it points to is no longer remapped.+ Holding.where(security_id: into.id, provider_security_id: into.id)+ .update_all(provider_security_id: nil, security_locked: false, updated_at: now)+ end++ def move_lots!(now)+ lots = HoldingLot.where(security_id: from.id)+ HoldingLot.move!(derived: lots.derived, opening: lots.opening, to: into)+ HoldingLot.where(origin_security_id: from.id).update_all(origin_security_id: into.id, updated_at: now)+ end++ def move_unless_target_has(model, *key_columns)+ table = model.arel_table+ kept = table.alias("kept")+ same_key = key_columns.map { |column| kept[column].eq(table[column]) }.reduce(:and)+ kept_row = Arel::SelectManager.new.from(kept).project(Arel.sql("1")).where(kept[:security_id].eq(into.id).and(same_key))++ rows = model.where(security_id: from.id)+ rows.where(kept_row.exists).delete_all+ rows.update_all(security_id: into.id, updated_at: Time.current)+ end++ def move_taggings!+ taggings = Tagging.where(taggable_type: "Security", taggable_id: from.id)+ taggings.where(tag_id: Tagging.where(taggable_type: "Security", taggable_id: into.id).select(:tag_id)).delete_all+ taggings.update_all(taggable_id: into.id, updated_at: Time.current)+ end+enddiff --git a/app/models/security/resolver.rb b/app/models/security/resolver.rbindex b40b2c83aa..c614189b6e 100644--- a/app/models/security/resolver.rb+++ b/app/models/security/resolver.rb@@ -17,6 +17,7 @@ class Security::Resolverexact_match_from_db ||exact_match_from_provider ||close_match_from_provider ||+ db_match_held_for_retry ||offline_security(reason: provider_search_technical_failure? ? "resolution_pending" : nil)end@@ -96,13 +97,36 @@ class Security::Resolverreturn nil unless security+ # Without an exchange, the lookup above returns whichever row for the+ # ticker sorts first. While a placeholder exists, retry the provider so+ # a successful search can fold it into the listed row, and fall back to+ # the listed row if the search fails or finds nothing.+ if exchange_operating_mic.blank? && (placeholder = pending_placeholder_for(symbol))+ @db_match_held_for_retry = resolution_pending?(security) ? listed_row_besides(placeholder) : security+ return nil+ end+# A "resolution_pending" record means the last provider search failed# technically (rate limit/timeout), not that the security is a# confirmed no-match. Skip the DB fast path so this resolution attempt# actually retries the provider instead of returning the same stale# offline record forever.- return nil if security.offline? && security.offline_reason == "resolution_pending"+ return nil if resolution_pending?(security)++ use_db_match(security)+ end++ def listed_row_besides(placeholder)+ scope = Security.where("UPPER(ticker) = ?", symbol).where.not(id: placeholder.id).order(:id)+ scope = scope.where(country_code: country_code) if country_code.present?+ scope.detect { |security| !resolution_pending?(security) }+ end++ def db_match_held_for_retry+ use_db_match(@db_match_held_for_retry) if @db_match_held_for_retry+ end+ def use_db_match(security)# When the caller provides an explicit provider (e.g. user selected from# search results), honor that choice. Automated syncs (Plaid, SimpleFIN)# pass price_provider: nil and will not overwrite.@@ -165,6 +189,9 @@ class Security::Resolvermatch = sorted_candidates.firstreturn nil unless match+ # The row held back from the DB fast path is an exact ticker match;+ # a search that only offers other tickers does not replace it.+ return nil if @db_match_held_for_retry && match.ticker&.upcase.to_s != symbolfind_or_create_provider_match!(match)end@@ -174,6 +201,7 @@ class Security::Resolverticker: match.ticker,exchange_operating_mic: match.exchange_operating_mic)+ security = settle_pending_placeholder(security, match)security.country_code = match.country_code@@ -205,6 +233,38 @@ class Security::Resolversecurityend+ # A search that fails technically for a ticker without an exchange leaves+ # a blank-MIC "resolution_pending" placeholder. Once an exchange-less+ # lookup, the kind that created it, finds the ticker on an exchange, the+ # placeholder is that instrument: it becomes the listed row, or is merged+ # into it after commit when one already exists. Left alone, it would keep+ # receiving holdings whenever a later search failed, splitting one+ # position across two securities. A lookup for an explicit exchange says nothing about+ # which listing the placeholder stood for.+ def settle_pending_placeholder(security, match)+ return security if exchange_operating_mic.present? || security.exchange_operating_mic.blank?++ placeholder = pending_placeholder_for(match.ticker)+ return security unless placeholder++ if security.new_record?+ placeholder.exchange_operating_mic = security.exchange_operating_mic+ placeholder+ else+ SecurityPlaceholderSettlementJob.perform_later(placeholder.id, security.id)+ security+ end+ end++ def pending_placeholder_for(ticker)+ placeholder = Security.find_by_ticker_and_exchange(ticker: ticker, match_blank_mic: true)+ placeholder if placeholder && resolution_pending?(placeholder)+ end++ def resolution_pending?(security)+ security.offline? && security.offline_reason == "resolution_pending"+ end+# If a security was marked offline, bring it back online whenever we have# a good reason to trust it can now be priced: either its provider was# temporarily disabled and is available again ("provider_disabled"), ordiff --git a/test/jobs/security_placeholder_settlement_job_test.rb b/test/jobs/security_placeholder_settlement_job_test.rbnew file mode 100644index 0000000000..7b10dce6c0--- /dev/null+++ b/test/jobs/security_placeholder_settlement_job_test.rb@@ -0,0 +1,28 @@+require "test_helper"++class SecurityPlaceholderSettlementJobTest < ActiveJob::TestCase+ setup do+ @placeholder = Security.create!(ticker: "STLX", offline: true, offline_reason: "resolution_pending")+ @listed = Security.create!(ticker: "STLX", exchange_operating_mic: "XNAS")+ end++ test "merges a pending placeholder into the listed security" do+ SecurityPlaceholderSettlementJob.perform_now(@placeholder.id, @listed.id)++ assert_not Security.exists?(@placeholder.id)+ end++ test "skips a placeholder that was settled another way before the job ran" do+ @placeholder.update!(offline: false, offline_reason: nil)++ SecurityPlaceholderSettlementJob.perform_now(@placeholder.id, @listed.id)++ assert Security.exists?(@placeholder.id)+ end++ test "does nothing when either security is gone" do+ @placeholder.destroy!++ assert_nothing_raised { SecurityPlaceholderSettlementJob.perform_now(@placeholder.id, @listed.id) }+ end+enddiff --git a/test/models/security/merger_test.rb b/test/models/security/merger_test.rbnew file mode 100644index 0000000000..98ce6bb419--- /dev/null+++ b/test/models/security/merger_test.rb@@ -0,0 +1,109 @@+require "test_helper"++class Security::MergerTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @account = accounts(:investment)+ @placeholder = Security.create!(ticker: "MRGX", offline: true, offline_reason: "resolution_pending")+ @listed = Security.create!(ticker: "MRGX", exchange_operating_mic: "XNAS", name: "Merge Co")+ end++ test "moves holdings, trades, prices, splits and tags onto the target and deletes the source" do+ only_on_placeholder = create_holding(@placeholder, date: 3.days.ago.to_date, qty: 2)+ newer_on_placeholder = create_holding(@placeholder, date: 2.days.ago.to_date, qty: 5)+ older_on_listed = create_holding(@listed, date: 2.days.ago.to_date, qty: 3)+ older_on_placeholder = create_holding(@placeholder, date: 1.day.ago.to_date, qty: 7)+ newer_on_listed = create_holding(@listed, date: 1.day.ago.to_date, qty: 4)+ older_on_listed.update_columns(updated_at: 1.hour.ago)+ older_on_placeholder.update_columns(updated_at: 1.hour.ago)++ trade_entry = create_trade(@placeholder, account: @account, qty: 1, date: 3.days.ago.to_date, price: 10)++ moved_price = Security::Price.create!(security: @placeholder, date: 3.days.ago.to_date, price: 10, currency: "USD")+ Security::Price.create!(security: @placeholder, date: 2.days.ago.to_date, price: 11, currency: "USD")+ kept_price = Security::Price.create!(security: @listed, date: 2.days.ago.to_date, price: 12, currency: "USD")++ moved_split = Security::Split.create!(security: @placeholder, ex_date: 10.days.ago.to_date, numerator: 2, denominator: 1, source: "manual")+ Security::Split.create!(security: @placeholder, ex_date: 20.days.ago.to_date, numerator: 3, denominator: 1, source: "manual")+ kept_split = Security::Split.create!(security: @listed, ex_date: 20.days.ago.to_date, numerator: 4, denominator: 1, source: "manual")++ Tagging.create!(tag: tags(:one), taggable: @placeholder)+ Tagging.create!(tag: tags(:one), taggable: @listed)+ Tagging.create!(tag: tags(:two), taggable: @placeholder)++ Account.any_instance.expects(:sync_later).once++ assert_equal @listed, Security::Merger.new(from: @placeholder, into: @listed).merge!++ assert_not Security.exists?(@placeholder.id)++ assert_equal @listed.id, only_on_placeholder.reload.security_id+ assert_equal @listed.id, newer_on_placeholder.reload.security_id+ assert_not Holding.exists?(older_on_listed.id)+ assert_not Holding.exists?(older_on_placeholder.id)+ assert_equal @listed.id, newer_on_listed.reload.security_id+ assert_equal [ 2, 5, 4 ], @account.holdings.where(security: @listed).order(:date).pluck(:qty).map(&:to_i)++ assert_equal @listed.id, trade_entry.reload.trade.security_id++ assert_equal [ moved_price.id, kept_price.id ].sort, @listed.prices.ids.sort+ assert_equal [ moved_split.id, kept_split.id ].sort, @listed.splits.ids.sort+ assert_equal [ tags(:one).id, tags(:two).id ].sort, Tagging.where(taggable: @listed).pluck(:tag_id).sort+ end++ test "repoints provider securities and drops remaps onto the security itself" do+ other = Security.create!(ticker: "MRGY", exchange_operating_mic: "XNAS")+ remapped_to_listed = create_holding(@listed, date: Date.current, qty: 1, provider_security: @placeholder, security_locked: true)+ remapped_elsewhere = create_holding(other, date: Date.current, qty: 1, provider_security: @placeholder, security_locked: true)++ Security::Merger.new(from: @placeholder, into: @listed).merge!++ remapped_to_listed.reload+ assert_nil remapped_to_listed.provider_security_id+ assert_not remapped_to_listed.security_locked++ remapped_elsewhere.reload+ assert_equal @listed.id, remapped_elsewhere.provider_security_id+ assert remapped_elsewhere.security_locked+ end++ test "combines opening lots and repoints lot origins" do+ HoldingLot.create!(account: @account, security: @placeholder, origin_security: @placeholder, qty: 2, currency: "USD")+ listed_lot = HoldingLot.create!(account: @account, security: @listed, origin_security: @listed, qty: 3, currency: "USD")++ Security::Merger.new(from: @placeholder, into: @listed).merge!++ lots = HoldingLot.where(account: @account, security: @listed)+ assert_equal [ listed_lot.id ], lots.ids+ assert_equal 5, listed_lot.reload.qty+ assert_not HoldingLot.where(origin_security_id: @placeholder.id).exists?+ end++ test "leaves both rows alone when the condition no longer holds under the lock" do+ @placeholder.update!(offline: false, offline_reason: nil)++ Security::Merger.new(from: @placeholder, into: @listed).merge!(condition: ->(source) { source.offline? })++ assert Security.exists?(@placeholder.id)+ end++ test "is a no-op when the source is the target" do+ Account.any_instance.expects(:sync_later).never++ assert_equal @listed, Security::Merger.new(from: @listed, into: @listed).merge!+ assert Security.exists?(@listed.id)+ end++ test "returns the target when the source was already merged" do+ stale = Security.find(@placeholder.id)+ Security::Merger.new(from: @placeholder, into: @listed).merge!++ assert_equal @listed, Security::Merger.new(from: stale, into: @listed).merge!+ end++ private+ def create_holding(security, date:, qty:, **attributes)+ @account.holdings.create!(security: security, date: date, qty: qty, price: 10, amount: qty * 10, currency: "USD", **attributes)+ end+enddiff --git a/test/models/security/resolver_test.rb b/test/models/security/resolver_test.rbindex 2753a2b677..a504bfa94e 100644--- a/test/models/security/resolver_test.rb+++ b/test/models/security/resolver_test.rb@@ -3,6 +3,7 @@ require "ostruct"class Security::ResolverTest < ActiveSupport::TestCaseinclude ProviderTestHelper+ include ActiveJob::TestHelpertest "resolves DB security" do# Given an existing security in the DB that exactly matches the lookup params@@ -526,4 +527,143 @@ class Security::ResolverTest < ActiveSupport::TestCaseassert_instance_of Provider::TwelveData, resolved.price_data_providerendend++ test "a successful search settles a resolution_pending placeholder in place" do+ placeholder = Security.create!(ticker: "PNDX", offline: true, offline_reason: "resolution_pending")+ stub_listed_search("PNDX")++ assert_no_difference "Security.count" do+ resolved = Security::Resolver.new("PNDX").resolve++ assert_equal placeholder, resolved+ resolved.reload+ assert_equal "XNAS", resolved.exchange_operating_mic+ assert_equal "US", resolved.country_code+ assert_equal "Pending Co", resolved.name+ refute resolved.offline?+ assert_nil resolved.offline_reason+ end+ end++ test "a ticker resolved through a failed, a successful and a failed search stays one security" do+ failing = mock("failing_provider")+ failing.stubs(:class).returns(Provider::YahooFinance)+ failing.stubs(:search_securities).raises(StandardError, "rate limited")+ Security.stubs(:providers).returns([ failing ])+ Security.stubs(:enabled_securities_providers).returns([ "yahoo_finance" ])++ placeholder = Security::Resolver.new("PNDU").resolve+ assert_equal "resolution_pending", placeholder.offline_reason++ Security.unstub(:providers)+ stub_listed_search("PNDU")+ assert_equal placeholder, Security::Resolver.new("PNDU").resolve++ Security.unstub(:search_provider)+ Security.stubs(:providers).returns([ failing ])+ assert_equal placeholder, Security::Resolver.new("PNDU").resolve+ assert_equal 1, Security.where(ticker: "PNDU").count+ end++ test "a successful search returns the listed security and settles the placeholder after commit" do+ placeholder = Security.create!(ticker: "PNDY", offline: true, offline_reason: "resolution_pending")+ listed = Security.create!(ticker: "PNDY", exchange_operating_mic: "XNAS", country_code: "US", price_provider: "yahoo_finance")+ holding = accounts(:investment).holdings.create!(security: placeholder, date: Date.current, qty: 1, price: 10, amount: 10, currency: "USD")+ stub_listed_search("PNDY")++ assert_enqueued_with(job: SecurityPlaceholderSettlementJob, args: [ placeholder.id, listed.id ]) do+ assert_equal listed, Security::Resolver.new("PNDY").resolve+ end+ assert Security.exists?(placeholder.id), "Records built in memory against the placeholder must still be insertable"++ Account.any_instance.expects(:sync_later).once+ perform_enqueued_jobs(only: SecurityPlaceholderSettlementJob)++ assert_not Security.exists?(placeholder.id)+ assert_equal listed.id, holding.reload.security_id+ end++ test "keeps the exact ticker held back for a placeholder when the search offers only other tickers" do+ listed = Security.create!(ticker: "PNDR", exchange_operating_mic: "XNAS", country_code: "US", price_provider: "yahoo_finance")+ Security.create!(ticker: "PNDR", offline: true, offline_reason: "resolution_pending")+ stub_listed_search("PNDR", match_ticker: "PNDRX")++ assert_no_difference "Security.count" do+ assert_equal listed, Security::Resolver.new("PNDR").resolve+ end+ end++ test "retries the provider for a ticker with a placeholder even when the listed row sorts first" do+ listed = Security.create!(id: "00000000-0000-4000-8000-000000000001", ticker: "PNDZ", exchange_operating_mic: "XNAS", country_code: "US", price_provider: "yahoo_finance")+ placeholder = Security.create!(id: "ffffffff-ffff-4fff-bfff-ffffffffffff", ticker: "PNDZ", offline: true, offline_reason: "resolution_pending")+ stub_listed_search("PNDZ")++ assert_enqueued_with(job: SecurityPlaceholderSettlementJob, args: [ placeholder.id, listed.id ]) do+ assert_equal listed, Security::Resolver.new("PNDZ").resolve+ end+ end++ test "falls back to the listed row when the retry for a placeholder fails" do+ listed = Security.create!(ticker: "PNDT", exchange_operating_mic: "XNAS", country_code: "US", price_provider: "yahoo_finance")+ placeholder = Security.create!(ticker: "PNDT", offline: true, offline_reason: "resolution_pending")++ failing = mock("failing_provider")+ failing.stubs(:class).returns(Provider::YahooFinance)+ failing.expects(:search_securities).raises(StandardError, "rate limited")+ Security.stubs(:providers).returns([ failing ])+ Security.stubs(:enabled_securities_providers).returns([ "yahoo_finance" ])++ assert_equal listed, Security::Resolver.new("PNDT").resolve++ refute listed.reload.offline?+ assert_nil listed.offline_reason+ assert_equal "resolution_pending", placeholder.reload.offline_reason+ end++ test "a lookup for an explicit exchange leaves the placeholder for exchange-less lookups to settle" do+ placeholder = Security.create!(ticker: "PNDS", offline: true, offline_reason: "resolution_pending")+ stub_listed_search("PNDS")++ resolved = Security::Resolver.new("PNDS", exchange_operating_mic: "XNAS").resolve++ assert_not_equal placeholder, resolved+ assert_equal "XNAS", resolved.exchange_operating_mic+ placeholder.reload+ assert_nil placeholder.exchange_operating_mic+ assert_equal "resolution_pending", placeholder.offline_reason+ end++ test "leaves a confirmed no-match blank-MIC security alone when a search later lists the ticker" do+ unlisted = Security.create!(ticker: "PNDW", offline: true)+ stub_listed_search("PNDW")++ assert_difference "Security.count", 1 do+ resolved = Security::Resolver.new("PNDW", exchange_operating_mic: "XNAS").resolve++ assert_not_equal unlisted, resolved+ assert_equal "XNAS", resolved.exchange_operating_mic+ end+ assert unlisted.reload.offline?+ end++ test "does not settle a placeholder for a different ticker than the search matched" do+ placeholder = Security.create!(ticker: "PNDV", offline: true, offline_reason: "resolution_pending")+ stub_listed_search("PNDV", match_ticker: "PNDVX")++ resolved = Security::Resolver.new("PNDV").resolve++ assert_equal "PNDVX", resolved.ticker+ placeholder.reload+ assert_nil placeholder.exchange_operating_mic+ assert_equal "resolution_pending", placeholder.offline_reason+ end++ private+ def stub_listed_search(symbol, match_ticker: symbol)+ provider = mock("listed_provider")+ Security.stubs(:provider_for).with("yahoo_finance").returns(provider)+ Security.stubs(:search_provider).with { |query, **| query == symbol }.returns([+ Security.new(ticker: match_ticker, name: "Pending Co", exchange_operating_mic: "XNAS", country_code: "US", price_provider: "yahoo_finance")+ ])+ endend