The personal finance app for everyone (by everyone)
Ruby
Add a per-account repair for split SnapTrade securities (#4404)
jaysbeekay0c4411e15e66
diff --git a/app/models/snaptrade_account/split_security_repair.rb b/app/models/snaptrade_account/split_security_repair.rbnew file mode 100644index 0000000000..a20326d148--- /dev/null+++ b/app/models/snaptrade_account/split_security_repair.rb@@ -0,0 +1,340 @@+# Repairs one account's SnapTrade positions whose holdings and trades sit on+# different Security rows of the same ticker.+#+# Before #3999, resolve_security looked a ticker up with no exchange and no+# ORDER BY, so a position's holdings and trades could land on different rows. Every cost-basis reader filters on security_id, so such a+# holding shows "No cost basis". The deterministic lookup keeps a position on+# the row it already holds, which keeps an existing split in place rather than+# healing it.+#+# The repair moves this account's rows only. It never destroys a Security,+# never moves a Security::Price (prices are shared by every family holding the+# security), and leaves other providers' holdings and other accounts alone.+# The target is the row held_security_for returns -- the one the next sync+# resolves to -- so the repaired position stays put.+#+# Only rows of one listing are merged. Security uniqueness is scoped to+# exchange_operating_mic, so the same ticker on two exchanges is two real+# instruments; a ticker whose rows name more than one exchange is skipped and+# reported in #conflicts for review by hand.+#+# A dry run (the default) reports what it would do and writes nothing. A live+# run refuses, writing nothing, when a source row has a split the target lacks,+# or when the moved history would have dates priced on a source row but not on+# the target, unless allow_price_gaps is set, and while a SnapTrade sync or+# activities fetch for the account is pending or running. A live run that+# fails is rolled back and recorded in the debug log.+class SnaptradeAccount::SplitSecurityRepair+ include SnaptradeAccount::DataHelpers++ class Refused < StandardError; end+ class PriceGapsRefused < Refused; end+ class SplitHistoryRefused < Refused; end+ class SyncInProgress < Refused; end++ # Rows reached a source security while the repair ran; it rolled back.+ class ConcurrentChange < StandardError; end++ Result = Data.define(+ :account, :ticker, :target_id, :target_source, :source_ids,+ :trades_moved, :holdings_moved, :holdings_dropped, :holdings_replaced, :dropped_snapshots,+ :price_gap_dates, :unmatched_split_dates+ )++ def self.accounts+ Account.where(id: AccountProvider.where(provider_type: "SnaptradeAccount").select(:account_id))+ end++ def initialize(account, dry_run: true, allow_price_gaps: false)+ @account = account+ @dry_run = dry_run+ @allow_price_gaps = allow_price_gaps+ end++ def dry_run?+ @dry_run+ end++ def snaptrade_linked?+ snaptrade_provider_id.present?+ end++ # { "TICKER" => [[security_id, exchange], ...] } for tickers the last run+ # skipped because their rows name more than one exchange.+ def conflicts+ @conflicts ||= {}+ end++ def run+ @conflicts = {}+ return [] unless snaptrade_provider_id++ plans = split_tickers.filter_map { |ticker, security_ids| plan_for(ticker, security_ids) }+ return [] if plans.empty?++ return plans.map { |plan| plan[:result] } if dry_run?++ refuse_unmatched_splits!(plans)+ refuse_price_gaps!(plans) unless @allow_price_gaps++ begin+ ActiveRecord::Base.transaction do+ hold_off_syncs!+ plans.each { |plan| apply(plan) }+ refuse_concurrent_change!(plans)+ Balance::Materializer.new(+ account, strategy: :reverse, security_ids: plans.map { |plan| plan[:result].target_id }+ ).materialize_balances+ end+ rescue Refused+ raise+ rescue StandardError => e+ capture_failure(e, plans)+ raise+ end++ plans.map { |plan| plan[:result] }+ end++ private+ attr_reader :account++ def snaptrade_provider_id+ @snaptrade_provider_id ||= account.account_providers.find_by(provider_type: "SnaptradeAccount")&.id+ end++ def snaptrade_account+ @snaptrade_account ||= AccountProvider.find(snaptrade_provider_id).provider+ end++ # A SnapTrade sync resolves each position's security before it writes,+ # so one running alongside the repair can write to a source row after+ # refuse_concurrent_change! has looked, and the position stays split.+ # Syncable#sync_later creates a sync under a row lock on its syncable, so+ # holding the connection's and the account's rows until the repair+ # commits keeps a new sync from starting in the meantime. A writer that+ # is already under way -- an incomplete sync on either, or the activities+ # fetch a sync leaves behind -- refuses the repair instead.+ def hold_off_syncs!+ item = SnaptradeItem.lock.find(snaptrade_account.snaptrade_item_id)+ locked_account = Account.lock.find(account.id)++ busy = []+ busy << "the SnapTrade connection has a sync pending or running" if item.syncs.incomplete.exists?+ busy << "the account has a sync pending or running" if locked_account.syncs.incomplete.exists?+ busy << "an activities fetch is pending" if SnaptradeAccount.where(id: snaptrade_account.id).pick(:activities_fetch_pending)+ return if busy.empty?++ raise SyncInProgress, "#{busy.join('; ')}; run it again once the sync has finished"+ end++ # SnapTrade's own holdings and those with no provider (materialized from+ # the account's trades). Another provider's holding is that provider's.+ def repairable_holdings+ account.holdings.where(account_provider_id: [ snaptrade_provider_id, nil ])+ end++ # { "TICKER" => [security_id, ...] } for tickers spread over more than one+ # row of one listing. The split this repairs is a SnapTrade-created row+ # (its exchange in exchange_mic, exchange_operating_mic nil) beside a row+ # with exchange_operating_mic set, so a row's exchange is its operating+ # MIC, else its exchange_mic. A row with neither fits any group; two+ # different exchanges mean two listings, and the ticker goes to conflicts.+ def split_tickers+ security_ids = (account.trades.distinct.pluck(:security_id) + repairable_holdings.distinct.pluck(:security_id)).uniq++ groups = Security.where(id: security_ids)+ .pluck(:id, :ticker, :exchange_operating_mic, :exchange_mic)+ .group_by { |_id, ticker, _operating_mic, _mic| ticker.to_s.upcase.strip }+ .select { |ticker, rows| ticker.present? && rows.size > 1 }+ .transform_values do |rows|+ rows.map do |id, _ticker, operating_mic, mic|+ [ id, Security.canonical_exchange_operating_mic(operating_mic.presence || mic.presence) ]+ end.sort+ end++ groups.each_with_object({}) do |(ticker, rows), splits|+ if rows.filter_map(&:last).uniq.size > 1+ conflicts[ticker] = rows+ else+ splits[ticker] = rows.map(&:first)+ end+ end.sort.to_h+ end++ def plan_for(ticker, security_ids)+ target_id, target_source = target_for(ticker, security_ids)+ source_ids = security_ids - [ target_id ]+ return nil if source_ids.empty?++ trades = account.trades.where(security_id: source_ids)+ moves, drops, replaced = holding_moves(target_id, source_ids)++ {+ trades: trades,+ moves: moves,+ drops: drops + replaced,+ result: Result.new(+ account: account,+ ticker: ticker,+ target_id: target_id,+ target_source: target_source,+ source_ids: source_ids,+ trades_moved: trades.count,+ holdings_moved: moves.size,+ holdings_dropped: drops.size,+ holdings_replaced: replaced.size,+ dropped_snapshots: dropped_snapshots(drops),+ price_gap_dates: price_gap_dates(target_id, source_ids),+ unmatched_split_dates: unmatched_split_dates(target_id, source_ids)+ )+ }+ end++ # The row the next sync resolves to, or, with no holding to name one, the+ # row with the most trades. provider_row stays false, as for trades: the+ # position's trades follow the row its holdings sit on, which for a+ # same-ticker remap is the chosen row, not provider_security_id.+ def target_for(ticker, security_ids)+ held = held_security_for(account, ticker, snaptrade_provider_id)+ return [ held.id, :held ] if held++ counts = account.trades.where(security_id: security_ids).group(:security_id).count+ [ security_ids.max_by { |id| [ counts.fetch(id, 0), -security_ids.index(id) ] }, :most_trades ]+ end++ # One holding per date and currency survives, never a sum. The target+ # keeps what it already has, except that a calculated target row gives way+ # to a SnapTrade snapshot: the re-materialization rebuilds calculated rows+ # from the trades, but the snapshot is the only record of that day's+ # provider cost basis. Provider rows go first, so where two non-target rows+ # share a date the provider's snapshot is the one kept.+ #+ # Returns [moves, drops, replaced]: source holdings to move, source+ # holdings to delete, and calculated target holdings a snapshot replaces.+ def holding_moves(target_id, source_ids)+ calculated_on_target = account.holdings.where(security_id: target_id, account_provider_id: nil)+ .pluck(:date, :currency, :id).to_h { |date, currency, id| [ [ date, currency ], id ] }+ taken = account.holdings.where(security_id: target_id).pluck(:date, :currency).to_set+ moves = []+ drops = []+ replaced = []++ repairable_holdings.where(security_id: source_ids)+ .order(:date, Arel.sql("account_provider_id IS NULL"), :id)+ .each do |holding|+ key = [ holding.date, holding.currency ]+ if holding.account_provider_id == snaptrade_provider_id && calculated_on_target.key?(key)+ replaced << calculated_on_target.delete(key)+ moves << holding.id+ elsif taken.include?(key)+ drops << holding.id+ else+ taken << key+ moves << holding.id+ end+ end++ [ moves, drops, replaced ]+ end++ # [date, cost_basis] of the SnapTrade snapshots a same-day collision+ # drops, so a dry run shows which provider cost basis a live run discards.+ def dropped_snapshots(drop_ids)+ Holding.where(id: drop_ids, account_provider_id: snaptrade_provider_id).order(:date, :id).pluck(:date, :cost_basis)+ end++ # Dates in the account's history with a price on another row and none on+ # the target. Prices are not moved, so these days can go unpriced in the+ # moved history until market data fills the target.+ def price_gap_dates(target_id, source_ids)+ dates = account.start_date..Date.current+ target_dates = Security::Price.where(security_id: target_id, date: dates).distinct.pluck(:date)++ (Security::Price.where(security_id: source_ids, date: dates).distinct.pluck(:date) - target_dates).sort+ end++ # Ex-dates of the source rows' splits that the target has no split of the+ # same ratio for. The holding calculators load splits by security_id, so+ # trades moved onto the target would replay without them. A split only+ # the target has is left alone: it is the same instrument's history.+ def unmatched_split_dates(target_id, source_ids)+ on_target = Security::Split.where(security_id: target_id).pluck(:ex_date, :numerator, :denominator).to_set++ Security::Split.where(security_id: source_ids)+ .pluck(:ex_date, :numerator, :denominator)+ .reject { |split| on_target.include?(split) }+ .map(&:first).uniq.sort+ end++ # Not overridable: moving the split onto the target is a market-data+ # change for every family holding it, which this repair never makes.+ def refuse_unmatched_splits!(plans)+ unmatched = plans.map { |plan| plan[:result] }.select { |result| result.unmatched_split_dates.any? }+ return if unmatched.empty?++ summary = unmatched.map { |result| "#{result.ticker}: #{result.unmatched_split_dates.map(&:iso8601).join(', ')}" }.join("; ")+ raise SplitHistoryRefused,+ "splits on a source row but not the target (#{summary}); record them on the target first"+ end++ def capture_failure(error, plans)+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "SnapTrade split security repair failed and was rolled back: #{error.class}: #{error.message}",+ source: self.class.name,+ provider_key: "snaptrade",+ account: account,+ account_provider_id: snaptrade_provider_id,+ metadata: {+ error_class: error.class.name,+ tickers: plans.map { |plan| plan[:result].ticker },+ backtrace: error.backtrace&.first(5)+ }+ )+ end++ # The plans are built before the transaction opens, and a sync can add a+ # holding or trade to a source row in between (or a user can, after apply+ # read the trades). Moving the rest and leaving that row behind would+ # re-split the position, so roll back and let the task be run again. A+ # holding another provider owns stays on its row by design and is not+ # counted.+ def refuse_concurrent_change!(plans)+ changed = plans.map { |plan| plan[:result] }.select do |result|+ repairable_holdings.where(security_id: result.source_ids).exists? ||+ account.trades.where(security_id: result.source_ids).exists?+ end+ return if changed.empty?++ raise ConcurrentChange,+ "rows reached a source security during the repair (#{changed.map(&:ticker).join(', ')}); run it again"+ end++ def refuse_price_gaps!(plans)+ gapped = plans.map { |plan| plan[:result] }.select { |result| result.price_gap_dates.any? }+ return if gapped.empty?++ summary = gapped.map { |result| "#{result.ticker}: #{result.price_gap_dates.size} date(s)" }.join(", ")+ raise PriceGapsRefused,+ "price gaps on the target row (#{summary}); backfill its prices or allow price gaps for this account"+ end++ def apply(plan)+ target_id = plan[:result].target_id++ now = Time.current+ Holding.where(id: plan[:drops]).delete_all if plan[:drops].any?+ Holding.where(id: plan[:moves]).update_all(security_id: target_id, updated_at: now) if plan[:moves].any?++ # Report caches key on the latest entry updated_at+ # (Family#entries_cache_version), and update_all bypasses that, so the+ # moved trades' entries are stamped too.+ trade_ids = plan[:trades].pluck(:id)+ return if trade_ids.empty?++ Trade.where(id: trade_ids).update_all(security_id: target_id, updated_at: now)+ Entry.where(entryable_type: "Trade", entryable_id: trade_ids).update_all(updated_at: now)+ end+enddiff --git a/app/models/snaptrade_item/importer.rb b/app/models/snaptrade_item/importer.rbindex 967839fdf7..0d0d4d057c 100644--- a/app/models/snaptrade_item/importer.rb+++ b/app/models/snaptrade_item/importer.rb@@ -206,14 +206,37 @@ class SnaptradeItem::Importer"dispatching background fetch job (SnapTrade may still be syncing)")- SnaptradeActivitiesFetchJob.set(wait: 10.seconds).perform_later(- snaptrade_account,- start_date: start_date- )-- # Mark the account as having pending activities- # The background job will clear this flag when done+ # Mark the account as having pending activities before queueing the+ # job, so the job never runs unflagged if this write fails. The job+ # clears the flag when done; SyncCleanerJob clears one left stuck.snaptrade_account.update!(activities_fetch_pending: true)++ # A fetch that never queued has nothing to clear the flag, so it is+ # cleared here. Active Job raises some enqueue failures and reports+ # an adapter's EnqueueError by returning false.+ begin+ queued = SnaptradeActivitiesFetchJob.set(wait: 10.seconds).perform_later(+ snaptrade_account,+ start_date: start_date+ )+ rescue StandardError+ snaptrade_account.update!(activities_fetch_pending: false)+ raise+ end++ unless queued+ snaptrade_account.update!(activities_fetch_pending: false)+ DebugLogEntry.capture(+ category: "provider_sync",+ level: "error",+ message: "Could not queue the background SnapTrade activities fetch",+ source: self.class.name,+ provider_key: "snaptrade",+ family: snaptrade_item.family,+ account_provider: snaptrade_account.account_provider,+ metadata: { snaptrade_account_id: snaptrade_account.id, start_date: start_date.to_s }+ )+ endendenddiff --git a/lib/tasks/snaptrade.rake b/lib/tasks/snaptrade.rakenew file mode 100644index 0000000000..3e583bab8b--- /dev/null+++ b/lib/tasks/snaptrade.rake@@ -0,0 +1,111 @@+namespace :snaptrade do+ # Repairs SnapTrade positions split across two Security rows of one ticker+ # before #3999: moves each account's trades and holdings onto the row the+ # account holds, then re-materializes. Per account, never+ # destroys a Security and never moves a price.+ #+ # bin/rails snaptrade:repair_split_securities # dry run, every SnapTrade account+ # bin/rails "snaptrade:repair_split_securities[ACCOUNT_ID]" # dry run, one account+ # DRY_RUN=false bin/rails snaptrade:repair_split_securities # writes+ #+ # A ticker whose rows name different exchanges is two listings, so it is+ # skipped and listed for review. A live run refuses an account whose target+ # row lacks a split its source rows have, one whose target row lacks+ # prices its source rows have, and one with a SnapTrade sync or activities+ # fetch pending or running. ALLOW_PRICE_GAPS=true overrides the price+ # check only, and only with an account id:+ # DRY_RUN=false ALLOW_PRICE_GAPS=true bin/rails "snaptrade:repair_split_securities[ACCOUNT_ID]"+ #+ # The task exits non-zero when any account was refused or failed, or when+ # it is run with ALLOW_PRICE_GAPS and no account id. A failure inside the+ # repair rolls that account back; one while reporting on it comes after the+ # repair has committed, and says so.+ desc "Repair SnapTrade holdings and trades split across duplicate security rows (dry run unless DRY_RUN=false)"+ task :repair_split_securities, [ :account_id ] => :environment do |_, args|+ dry_run = ENV["DRY_RUN"].to_s.strip.downcase != "false"+ allow_price_gaps = ENV["ALLOW_PRICE_GAPS"].to_s.strip.downcase == "true"+ if allow_price_gaps && args[:account_id].blank?+ abort "ALLOW_PRICE_GAPS needs an account id: run it for one reviewed account at a time. Nothing written."+ end+ accounts = if args[:account_id].present?+ Account.where(id: args[:account_id])+ else+ SnaptradeAccount::SplitSecurityRepair.accounts+ end++ puts dry_run ? "DRY RUN: nothing will be written. Set DRY_RUN=false to apply." : "Applying repairs."++ describe = lambda do |securities, id|+ security = securities[id]+ exchange = security && (security.exchange_operating_mic.presence || security.exchange_mic.presence)+ "#{id} (#{exchange || 'no exchange'}, #{security&.name})"+ end++ refusals = []+ failures = []+ accounts.find_each do |account|+ repair = SnaptradeAccount::SplitSecurityRepair.new(account, dry_run: dry_run, allow_price_gaps: allow_price_gaps)+ unless repair.snaptrade_linked?+ puts "Account #{account.id} (#{account.name}): not a SnapTrade-linked account"+ next+ end++ repair_returned = false+ results = repair.run+ repair_returned = true+ securities = Security.where(id: results.flat_map { |result| [ result.target_id, *result.source_ids ] }).index_by(&:id)++ if results.empty? && repair.conflicts.empty?+ puts "Account #{account.id} (#{account.name}): no split securities"+ next+ end++ puts "Account #{account.id} (#{account.name}):"+ results.each do |result|+ sources = result.source_ids.map { |id| describe.call(securities, id) }.join(", ")+ puts " #{result.ticker}: target #{describe.call(securities, result.target_id)} [#{result.target_source}], from #{sources}"+ puts " trades moved: #{result.trades_moved}, holdings moved: #{result.holdings_moved}, " \+ "holdings dropped (target already had the date): #{result.holdings_dropped}, " \+ "calculated target holdings replaced by a SnapTrade snapshot: #{result.holdings_replaced}"++ if result.dropped_snapshots.any?+ dropped = result.dropped_snapshots.map { |date, cost_basis| "#{date.iso8601} (cost basis #{cost_basis || 'none'})" }+ puts " SnapTrade snapshots dropped: #{dropped.join(', ')}"+ end++ if result.unmatched_split_dates.any?+ puts " split history: source splits the target lacks, on #{result.unmatched_split_dates.map(&:iso8601).join(', ')}"+ end++ gaps = result.price_gap_dates+ next if gaps.empty?++ shown = gaps.first(10).map(&:iso8601).join(", ")+ shown += ", ..." if gaps.size > 10+ puts " price gap: #{gaps.size} date(s) priced on another row but not the target: #{shown}"+ end++ repair.conflicts.each do |ticker, rows|+ listed = rows.map { |id, exchange| "#{id} (#{exchange || 'no exchange'})" }.join(", ")+ puts " #{ticker}: skipped, rows on different exchanges are separate listings: #{listed}"+ end+ rescue SnaptradeAccount::SplitSecurityRepair::Refused => e+ puts "Account #{account.id} (#{account.name}): refused, nothing written: #{e.message}"+ refusals << account.id+ rescue StandardError => e+ outcome = if repair_returned+ dry_run ? "reporting failed, nothing written" : "repair applied, but reporting failed"+ else+ dry_run ? "failed, nothing written" : "failed, rolled back"+ end+ puts "Account #{account.id}: #{outcome}: #{e.class}: #{e.message}"+ Rails.logger.error("SnapTrade split security repair failed for account #{account.id}\n#{e.full_message(highlight: false)}")+ failures << account.id+ end++ problems = []+ problems << "Refused: #{refusals.size} account(s): #{refusals.join(', ')}" if refusals.any?+ problems << "Failed: #{failures.size} account(s): #{failures.join(', ')}" if failures.any?+ abort problems.join("; ") if problems.any?+ end+enddiff --git a/test/models/snaptrade_account/split_security_repair_test.rb b/test/models/snaptrade_account/split_security_repair_test.rbnew file mode 100644index 0000000000..4ee8b91ff4--- /dev/null+++ b/test/models/snaptrade_account/split_security_repair_test.rb@@ -0,0 +1,700 @@+require "test_helper"++RakeTaskTestHelper.load_task("snaptrade:repair_split_securities", "snaptrade")++# A SnapTrade position whose holdings and trades sit on two Security rows of+# the same ticker, the state left behind by the ticker-only lookup that+# #3999 replaced. Row A is the one SnapTrade created (exchange in+# exchange_mic); row B is the one a CSV import or ticker search created+# (exchange in exchange_operating_mic). A is the older row, so the oldest-row+# and preferred-row fallbacks both pick A; only the held position points at B.+class SnaptradeAccount::SplitSecurityRepairTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ RakeTaskTestHelper.prepare("snaptrade:repair_split_securities")++ @family = families(:dylan_family)+ @snaptrade_account = snaptrade_accounts(:fidelity_401k)+ @account = @family.accounts.create!(+ name: "Stake US",+ balance: 6000,+ cash_balance: 0,+ currency: "USD",+ accountable: Investment.new+ )+ @snaptrade_account.ensure_account_provider!(@account)+ @provider_id = @snaptrade_account.reload.account_provider.id++ @row_a = Security.create!(ticker: "SPLT", name: "Split Co", exchange_mic: "XNYS", created_at: 2.days.ago)+ @row_b = Security.create!(ticker: "SPLT", name: "Split Co", exchange_operating_mic: "XNYS", created_at: 1.day.ago)+ end++ test "repair moves the duplicate row's trades onto the held row and restores avg_cost" do+ holding = seed_observed_split++ assert_nil holding.avg_cost, "precondition: the split hides the trades from the holding"++ result = repair!.sole++ assert_equal Money.new(150, "USD"), holding.reload.avg_cost+ assert_equal @row_b.id, holding.security_id+ assert_equal 2, result.trades_moved+ end++ # Report caches key on Family#entries_cache_version (the latest entry+ # updated_at). Moving trades with update_all touches no entry, so a figure+ # cached before the repair would keep grouping the trades under the old row.+ test "a live repair moves the family's entries cache version" do+ seed_observed_split+ before = @family.reload.entries_cache_version++ travel 1.minute do+ repair!+ end++ assert_not_equal before, @family.reload.entries_cache_version+ end++ test "repair resolves to the row resolve_security keeps picking" do+ seed_observed_split+ resolver = SnaptradeAccount::HoldingsProcessor.new(@snaptrade_account)+ assert_equal @row_b, resolver.send(:resolve_security, "SPLT", {}, account: @account, account_provider_id: @provider_id),+ "precondition: sync resolves the ticker to the held row, not the older one"++ result = repair!.sole++ assert_equal @row_b.id, result.target_id+ assert_equal :held, result.target_source+ assert_equal 2, @account.trades.where(security_id: @row_b.id).count+ assert_equal 0, @account.trades.where(security_id: @row_a.id).count+ assert_equal 0, @account.holdings.where(security_id: @row_a.id).count+ assert_equal @row_b, resolver.send(:resolve_security, "SPLT", {}, account: @account.reload, account_provider_id: @provider_id)+ end++ test "repair handles a duplicate row that has trades but no holding" do+ create_trade(@row_a, account: @account, qty: 10, date: 20.days.ago.to_date, price: 100)+ create_trade(@row_a, account: @account, qty: 10, date: 10.days.ago.to_date, price: 200)+ create_trade(@row_b, account: @account, qty: 5, date: 5.days.ago.to_date, price: 300)+ assert_equal 0, @account.holdings.count, "precondition: no holding names a target"++ result = repair!.sole++ assert_equal @row_a.id, result.target_id+ assert_equal :most_trades, result.target_source+ assert_equal 1, result.trades_moved+ assert_equal 3, @account.trades.where(security_id: @row_a.id).count+ assert_equal 0, @account.trades.where(security_id: @row_b.id).count+ end++ test "repair keeps the target holding on a same-day collision without summing qty" do+ seed_observed_split+ yesterday = 1.day.ago.to_date+ snaptrade_holding(@row_b, date: yesterday, qty: 20)+ duplicate = snaptrade_holding(@row_a, date: yesterday, qty: 20)++ result = repair!.sole++ assert_equal [ 20 ], @account.holdings.where(security_id: @row_b.id, date: yesterday).pluck(:qty).map(&:to_i)+ assert_not Holding.exists?(duplicate.id)+ assert_equal 1, result.holdings_dropped+ end++ # Two SnapTrade snapshots on one date: the target's survives, so the dry run+ # names the source snapshot it would drop, with its cost basis.+ test "a same-day collision between two SnapTrade snapshots keeps the target's and reports the dropped one" do+ seed_observed_split+ yesterday = 1.day.ago.to_date+ kept = snaptrade_holding(@row_b, date: yesterday, qty: 20)+ kept.update!(cost_basis: 0, cost_basis_source: "provider")+ dropped = snaptrade_holding(@row_a, date: yesterday, qty: 20)+ dropped.update!(cost_basis: 150, cost_basis_source: "provider")++ planned = SnaptradeAccount::SplitSecurityRepair.new(@account).run.sole+ assert_equal [ [ yesterday, BigDecimal("150") ] ], planned.dropped_snapshots++ repair!+ assert_equal [ kept.id ], @account.holdings.where(date: yesterday).pluck(:id)+ assert_not Holding.exists?(dropped.id)+ end++ test "a dropped calculated holding is not reported as a SnapTrade snapshot" do+ seed_observed_split+ yesterday = 1.day.ago.to_date+ snaptrade_holding(@row_b, date: yesterday, qty: 20)+ @account.holdings.create!(security: @row_a, date: yesterday, qty: 20, price: 300, amount: 6000, currency: "USD")++ result = SnaptradeAccount::SplitSecurityRepair.new(@account).run.sole++ assert_equal 1, result.holdings_dropped+ assert_empty result.dropped_snapshots+ end++ # A calculated row is rebuilt from the trades by the re-materialization; a+ # SnapTrade snapshot is the only record of that day's provider cost basis.+ test "a calculated target row gives way to the SnapTrade snapshot on a same-day collision" do+ seed_observed_split+ yesterday = 1.day.ago.to_date+ calculated = @account.holdings.create!(security: @row_b, date: yesterday, qty: 20, price: 300, amount: 6000, currency: "USD")+ snapshot = snaptrade_holding(@row_a, date: yesterday, qty: 20)+ snapshot.update!(cost_basis: 123, cost_basis_source: "provider")++ result = repair!.sole++ kept = @account.holdings.find_by!(security_id: @row_b.id, date: yesterday, currency: "USD")+ assert_equal snapshot.id, kept.id+ assert_equal @provider_id, kept.account_provider_id+ assert_equal 123, kept.cost_basis.to_i+ assert_not Holding.exists?(calculated.id)+ assert_equal [ 1, 1 ], [ result.holdings_moved, result.holdings_replaced ]+ end++ test "a live repair re-materializes the account for the target rows" do+ seed_observed_split+ materializer = mock("materializer")+ materializer.expects(:materialize_balances).once+ Balance::Materializer.expects(:new)+ .with(@account, strategy: :reverse, security_ids: [ @row_b.id ])+ .returns(materializer)++ repair!+ end++ test "a failure while re-materializing rolls back the moved rows" do+ holding = seed_observed_split+ before = account_state+ Balance::Materializer.any_instance.stubs(:materialize_balances).raises(StandardError, "boom")++ assert_raises(StandardError) { repair! }++ assert_equal before, account_state+ assert_nil holding.reload.avg_cost+ end++ test "dry run changes nothing" do+ holding = seed_observed_split+ before = account_state++ result = SnaptradeAccount::SplitSecurityRepair.new(@account).run.sole++ assert_equal 2, result.trades_moved, "the dry run still reports what it would move"+ assert_equal before, account_state+ assert_nil holding.reload.avg_cost+ end++ test "another account's holdings and trades on the duplicate row are untouched" do+ seed_observed_split+ other = @family.accounts.create!(name: "Other", balance: 1000, cash_balance: 0, currency: "USD", accountable: Investment.new)+ create_trade(@row_a, account: other, qty: 3, date: 4.days.ago.to_date, price: 100)+ other_holding = other.holdings.create!(security: @row_a, date: Date.current, qty: 3, price: 100, amount: 300, currency: "USD")++ repair!++ assert_equal [ @row_a.id ], other.trades.pluck(:security_id)+ assert_equal @row_a.id, other_holding.reload.security_id+ end++ test "another provider's holding on the same account is untouched" do+ seed_observed_split+ coinstats_item = @family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")+ coinstats_account = coinstats_item.coinstats_accounts.create!(name: "Brokerage", currency: "USD")+ other_provider = AccountProvider.create!(account: @account, provider: coinstats_account)+ foreign = @account.holdings.create!(security: @row_a, date: 3.days.ago.to_date, qty: 7, price: 100, amount: 700,+ currency: "USD", account_provider_id: other_provider.id)++ repair!++ assert_equal @row_a.id, foreign.reload.security_id+ assert_equal 7, foreign.qty.to_i+ end++ test "a non-SnapTrade account is skipped" do+ manual = @family.accounts.create!(name: "Manual", balance: 6000, cash_balance: 0, currency: "USD", accountable: Investment.new)+ create_trade(@row_a, account: manual, qty: 10, date: 20.days.ago.to_date, price: 100)+ manual.holdings.create!(security: @row_b, date: Date.current, qty: 10, price: 300, amount: 3000, currency: "USD")+ before = [ manual.trades.pluck(:security_id), manual.holdings.pluck(:security_id) ]++ assert_empty SnaptradeAccount::SplitSecurityRepair.new(manual, dry_run: false).run+ assert_equal before, [ manual.trades.pluck(:security_id), manual.holdings.pluck(:security_id) ]+ assert_not_includes SnaptradeAccount::SplitSecurityRepair.accounts, manual+ assert_includes SnaptradeAccount::SplitSecurityRepair.accounts, @account+ end++ test "a ticker with one row is a no-op" do+ create_trade(@row_b, account: @account, qty: 10, date: 20.days.ago.to_date, price: 100)+ holding = snaptrade_holding(@row_b, date: Date.current, qty: 10)+ before = account_state++ assert_empty repair!+ assert_equal before, account_state+ assert_equal Money.new(100, "USD"), holding.reload.avg_cost+ end++ test "a different ticker is unaffected" do+ seed_observed_split+ other_ticker = Security.create!(ticker: "OTHR", name: "Other Co", exchange_mic: "XNYS")+ create_trade(other_ticker, account: @account, qty: 4, date: 6.days.ago.to_date, price: 50)+ other_holding = snaptrade_holding(other_ticker, date: Date.current, qty: 4)++ results = repair!++ assert_equal [ "SPLT" ], results.map(&:ticker)+ assert_equal [ other_ticker.id ], @account.trades.joins(:security).where(securities: { ticker: "OTHR" }).pluck(:security_id)+ assert_equal other_ticker.id, other_holding.reload.security_id+ end++ test "no Security row is destroyed and no price is moved" do+ seed_observed_split+ price_a = Security::Price.create!(security: @row_a, date: 12.days.ago.to_date, price: 190, currency: "USD")+ price_b = Security::Price.create!(security: @row_b, date: 11.days.ago.to_date, price: 195, currency: "USD")++ # Row A's price is a gap on B; allowed here, since the point is what moves.+ assert_no_difference -> { Security.count } do+ repair!(allow_price_gaps: true)+ end++ assert Security.exists?(@row_a.id)+ assert_equal @row_a.id, price_a.reload.security_id+ assert_equal @row_b.id, price_b.reload.security_id+ end++ test "moved holdings are not security_locked and carry no provider_security_id" do+ seed_observed_split+ moved = snaptrade_holding(@row_a, date: 5.days.ago.to_date, qty: 20)++ result = repair!.sole++ moved.reload+ assert_equal @row_b.id, moved.security_id+ assert_not moved.security_locked?+ assert_nil moved.provider_security_id+ assert_equal 1, result.holdings_moved+ end++ test "a live repair that would leave price gaps is refused and writes nothing" do+ holding = seed_observed_split+ Security::Price.create!(security: @row_a, date: 15.days.ago.to_date, price: 180, currency: "USD")+ before = account_state++ error = assert_raises(SnaptradeAccount::SplitSecurityRepair::PriceGapsRefused) { repair! }++ assert_match(/SPLT: 1 date/, error.message)+ assert_equal before, account_state+ assert_nil holding.reload.avg_cost+ end++ # The observed split has the held row carrying the prices. Here the held+ # row has only one price, on a date the other row also has, and the other+ # row has the rest, so the moved history can only be priced on those dates+ # once market data fills the held row; the repair says so.+ test "a split in the opposite direction keeps today's value and reports the price gap" do+ holding = seed_observed_split+ gap_dates = [ 15.days.ago.to_date, 8.days.ago.to_date ]+ gap_dates.each { |date| Security::Price.create!(security: @row_a, date: date, price: 180, currency: "USD") }+ shared_date = 12.days.ago.to_date+ Security::Price.create!(security: @row_a, date: shared_date, price: 185, currency: "USD")+ Security::Price.create!(security: @row_b, date: shared_date, price: 185, currency: "USD")+ # Before the account's first entry, so outside its history.+ Security::Price.create!(security: @row_a, date: 40.days.ago.to_date, price: 150, currency: "USD")+ prices_before = Security::Price.where(security_id: [ @row_a.id, @row_b.id ]).order(:id).pluck(:id, :security_id)++ result = repair!(allow_price_gaps: true).sole++ holding.reload+ assert_equal [ 20, 6000 ], [ holding.qty.to_i, holding.amount.to_i ]+ assert_equal Date.current, holding.date+ assert_equal prices_before, Security::Price.where(security_id: [ @row_a.id, @row_b.id ]).order(:id).pluck(:id, :security_id)+ assert_equal gap_dates.sort, result.price_gap_dates+ end++ # The plan is built before the transaction opens, so a sync can add a row+ # to a source security in between. Moving the trades and leaving that row+ # behind would re-split the position, so the repair rolls back instead.+ test "a live repair rolls back when a holding lands on a source row after planning" do+ holding = seed_observed_split+ before = account_state+ repair = SnaptradeAccount::SplitSecurityRepair.new(@account, dry_run: false, allow_price_gaps: true)+ account, row_a = @account, @row_a+ repair.define_singleton_method(:apply) do |plan|+ account.holdings.create!(security: row_a, date: 3.days.ago.to_date, qty: 20, price: 300, amount: 6000, currency: "USD")+ super(plan)+ end++ error = assert_raises(SnaptradeAccount::SplitSecurityRepair::ConcurrentChange) { repair.run }++ assert_match(/SPLT/, error.message)+ assert_equal before, account_state+ assert_nil holding.reload.avg_cost+ end++ test "a live repair rolls back when a trade lands on a source row after it moved the trades" do+ holding = seed_observed_split+ before = account_state+ repair = SnaptradeAccount::SplitSecurityRepair.new(@account, dry_run: false, allow_price_gaps: true)+ test_case, account, row_a = self, @account, @row_a+ repair.define_singleton_method(:apply) do |plan|+ super(plan)+ test_case.create_trade(row_a, account: account, qty: 1, date: 2.days.ago.to_date, price: 250)+ end++ assert_raises(SnaptradeAccount::SplitSecurityRepair::ConcurrentChange) { repair.run }++ assert_equal before, account_state+ assert_nil holding.reload.avg_cost+ end++ # A sync resolves a position's security before it writes, so one running+ # alongside the repair can write to a source row after the check above.+ # Each SnapTrade writer is visible before it starts: an incomplete Sync on+ # the connection or the account, or the activities fetch flag.+ # Each case asserts its own reason: every refusal message ends "run it+ # again once the sync has finished", so matching /sync/ alone would pass+ # whichever writer was detected.+ {+ "the SnapTrade connection has a sync running" => [ ->(test) { test.snaptrade_item.syncs.create!(status: "syncing") }, "the SnapTrade connection has a sync pending or running" ],+ "the SnapTrade connection has a sync pending" => [ ->(test) { test.snaptrade_item.syncs.create!(status: "pending") }, "the SnapTrade connection has a sync pending or running" ],+ "the account has a sync pending" => [ ->(test) { test.account.syncs.create!(status: "pending") }, "the account has a sync pending or running" ],+ "an activities fetch is pending" => [ ->(test) { test.snaptrade_account.update!(activities_fetch_pending: true) }, "an activities fetch is pending" ]+ }.each do |situation, (arrange, reason)|+ test "a live repair is refused, writing nothing, when #{situation}" do+ holding = seed_observed_split+ arrange.call(self)+ before = account_state++ error = assert_no_difference -> { DebugLogEntry.count } do+ assert_raises(SnaptradeAccount::SplitSecurityRepair::SyncInProgress) { repair!(allow_price_gaps: true) }+ end++ assert_equal "#{reason}; run it again once the sync has finished", error.message+ assert_equal before, account_state+ assert_nil holding.reload.avg_cost+ end+ end++ test "finished syncs do not hold the repair off" do+ holding = seed_observed_split+ %w[completed failed stale].each do |status|+ snaptrade_item.syncs.create!(status: status)+ @account.syncs.create!(status: status)+ end++ repair!(allow_price_gaps: true)++ assert_equal Money.new(150, "USD"), holding.reload.avg_cost+ end++ test "a sync pending on another account does not hold the repair off" do+ holding = seed_observed_split+ accounts(:depository).syncs.create!(status: "pending")++ repair!(allow_price_gaps: true)++ assert_equal Money.new(150, "USD"), holding.reload.avg_cost+ end++ # Syncable#sync_later creates a sync under a row lock on its syncable, so+ # holding the connection's and the account's rows until the repair commits+ # keeps a new sync from starting in the meantime.+ test "a live repair locks the SnapTrade connection and account rows while it applies" do+ seed_observed_split+ locks = []+ subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") do |*, payload|+ locks << payload[:sql] if payload[:sql].include?("FOR UPDATE")+ end++ repair!(allow_price_gaps: true)++ assert locks.any? { |sql| sql.include?(%("snaptrade_items")) }, "locks the SnapTrade connection row"+ assert locks.any? { |sql| sql.include?(%("accounts")) }, "locks the account row"+ ensure+ ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber+ end++ test "the rake task is a dry run unless DRY_RUN is false" do+ holding = seed_observed_split++ output, = with_env_overrides("DRY_RUN" => nil) do+ capture_io { Rake::Task["snaptrade:repair_split_securities"].invoke(@account.id) }+ end+ assert_match(/DRY RUN/, output)+ assert_match(/SPLT/, output)+ assert_nil holding.reload.avg_cost++ Rake::Task["snaptrade:repair_split_securities"].reenable+ with_env_overrides("DRY_RUN" => "false") do+ capture_io { Rake::Task["snaptrade:repair_split_securities"].invoke(@account.id) }+ end+ assert_equal Money.new(150, "USD"), holding.reload.avg_cost+ end++ test "the rake task says when the account is not SnapTrade-linked" do+ manual = @family.accounts.create!(name: "Manual", balance: 0, cash_balance: 0, currency: "USD", accountable: Investment.new)++ output, = with_env_overrides("DRY_RUN" => nil) do+ capture_io { Rake::Task["snaptrade:repair_split_securities"].invoke(manual.id) }+ end++ assert_match(/Account #{manual.id} \(Manual\): not a SnapTrade-linked account/, output)+ assert_no_match(/no split securities/, output)+ end++ test "the rake dry run lists the SnapTrade snapshots it would drop" do+ seed_observed_split+ yesterday = 1.day.ago.to_date+ snaptrade_holding(@row_b, date: yesterday, qty: 20)+ snaptrade_holding(@row_a, date: yesterday, qty: 20).update!(cost_basis: 150, cost_basis_source: "provider")++ output, = with_env_overrides("DRY_RUN" => nil) do+ capture_io { Rake::Task["snaptrade:repair_split_securities"].invoke(@account.id) }+ end++ assert_match(/SnapTrade snapshots dropped: #{yesterday.iso8601} \(cost basis 150\.0\)/, output)+ end++ test "the rake task refuses a live repair with price gaps unless ALLOW_PRICE_GAPS names one account" do+ holding = seed_observed_split+ Security::Price.create!(security: @row_a, date: 15.days.ago.to_date, price: 180, currency: "USD")+ task = Rake::Task["snaptrade:repair_split_securities"]++ output, error = invoke_task_expecting_exit({ "DRY_RUN" => "false", "ALLOW_PRICE_GAPS" => nil }, @account.id)+ assert_not error.success?, "a refused live repair exits non-zero"+ assert_match(/refused, nothing written/, output)+ assert_match(/Refused: 1 account\(s\): #{@account.id}/, output)+ assert_nil holding.reload.avg_cost++ task.reenable+ output, error = invoke_task_expecting_exit("DRY_RUN" => "false", "ALLOW_PRICE_GAPS" => "true")+ assert_not error.success?, "a rejected invocation exits non-zero"+ assert_match(/needs an account id/, output)+ assert_nil holding.reload.avg_cost++ task.reenable+ with_env_overrides("DRY_RUN" => "false", "ALLOW_PRICE_GAPS" => "true") { capture_io { task.invoke(@account.id) } }+ assert_equal Money.new(150, "USD"), holding.reload.avg_cost+ end++ # Security uniqueness is scoped to exchange_operating_mic, so one ticker can+ # be two real listings. Holding both is not the split this repairs.+ test "a ticker held on two different exchanges is left alone and reported" do+ shop_us = Security.create!(ticker: "SHOP", name: "Shopify", exchange_operating_mic: "XNYS")+ shop_ca = Security.create!(ticker: "SHOP", name: "Shopify", exchange_operating_mic: "XTSE")+ create_trade(shop_us, account: @account, qty: 5, date: 9.days.ago.to_date, price: 100)+ create_trade(shop_ca, account: @account, qty: 7, date: 8.days.ago.to_date, price: 130)+ snaptrade_holding(shop_us, date: Date.current, qty: 5)+ snaptrade_holding(shop_ca, date: Date.current, qty: 7)+ before = account_state+ repair = SnaptradeAccount::SplitSecurityRepair.new(@account, dry_run: false)++ assert_empty repair.run+ assert_equal before, account_state+ assert_equal({ "SHOP" => [ [ shop_us.id, "XNYS" ], [ shop_ca.id, "XTSE" ] ].sort }, repair.conflicts)+ end++ test "a SnapTrade row on another exchange than the second row is not merged" do+ seed_observed_split+ @row_a.update_columns(exchange_mic: "XTSE")+ before = account_state+ repair = SnaptradeAccount::SplitSecurityRepair.new(@account, dry_run: false)++ assert_empty repair.run+ assert_equal before, account_state+ assert_equal [ "SPLT" ], repair.conflicts.keys+ end++ test "a row with no exchange at all is merged with the row that has one" do+ holding = seed_observed_split+ @row_a.update_columns(exchange_mic: nil)++ repair = SnaptradeAccount::SplitSecurityRepair.new(@account, dry_run: false)+ repair.run++ assert_equal Money.new(150, "USD"), holding.reload.avg_cost+ assert_empty repair.conflicts+ end++ # The holding calculators load splits by security_id, so trades moved onto+ # a target that lacks the source's split would replay without it.+ test "a live repair is refused when the source row has a split the target lacks" do+ holding = seed_observed_split+ @row_a.splits.create!(ex_date: 15.days.ago.to_date, numerator: 2, denominator: 1, source: "manual")+ before = account_state++ error = assert_raises(SnaptradeAccount::SplitSecurityRepair::SplitHistoryRefused) { repair!(allow_price_gaps: true) }++ assert_match(/SPLT: #{15.days.ago.to_date.iso8601}/, error.message)+ assert_equal before, account_state+ assert_nil holding.reload.avg_cost+ end++ test "a dry run reports the source splits the target lacks" do+ seed_observed_split+ ex_date = 15.days.ago.to_date+ @row_a.splits.create!(ex_date: ex_date, numerator: 2, denominator: 1, source: "manual")+ @row_a.splits.create!(ex_date: 5.days.ago.to_date, numerator: 3, denominator: 1, source: "manual")+ # Same date and ratio on the target: matched, so not reported.+ @row_b.splits.create!(ex_date: 5.days.ago.to_date, numerator: 3, denominator: 1, source: "manual")++ result = SnaptradeAccount::SplitSecurityRepair.new(@account).run.sole++ assert_equal [ ex_date ], result.unmatched_split_dates+ end++ test "a source split with a different ratio on the target is unmatched" do+ seed_observed_split+ ex_date = 15.days.ago.to_date+ @row_a.splits.create!(ex_date: ex_date, numerator: 2, denominator: 1, source: "manual")+ @row_b.splits.create!(ex_date: ex_date, numerator: 3, denominator: 1, source: "manual")++ assert_equal [ ex_date ], SnaptradeAccount::SplitSecurityRepair.new(@account).run.sole.unmatched_split_dates+ end++ test "a live repair goes ahead when the target carries the same split" do+ holding = seed_observed_split+ [ @row_a, @row_b ].each do |row|+ row.splits.create!(ex_date: 15.days.ago.to_date, numerator: 2, denominator: 1, source: "manual")+ end++ result = repair!.sole++ assert_empty result.unmatched_split_dates+ assert_equal @row_b.id, holding.reload.security_id+ assert_equal 0, @account.trades.where(security_id: @row_a.id).count+ end++ test "a failed live repair is recorded in the debug log" do+ seed_observed_split+ Balance::Materializer.any_instance.stubs(:materialize_balances).raises(StandardError, "boom")++ assert_difference -> { DebugLogEntry.count }, 1 do+ assert_raises(StandardError) { repair! }+ end++ entry = DebugLogEntry.order(:created_at).last+ assert_equal [ "provider_sync_error", "error", "snaptrade" ], [ entry.category, entry.level, entry.provider_key ]+ assert_equal [ @account.id, @family.id, @provider_id ], [ entry.account_id, entry.family_id, entry.account_provider_id ]+ assert_equal "StandardError", entry.metadata["error_class"]+ assert_match(/boom/, entry.message)+ end++ test "a refusal is not recorded in the debug log" do+ seed_observed_split+ Security::Price.create!(security: @row_a, date: 15.days.ago.to_date, price: 180, currency: "USD")++ assert_no_difference -> { DebugLogEntry.count } do+ assert_raises(SnaptradeAccount::SplitSecurityRepair::PriceGapsRefused) { repair! }+ end+ end++ test "the rake task exits non-zero when an account fails" do+ seed_observed_split+ Balance::Materializer.any_instance.stubs(:materialize_balances).raises(StandardError, "boom")+ SnaptradeAccount::SplitSecurityRepair.stubs(:accounts).returns(Account.where(id: @account.id))++ output, error = invoke_task_expecting_exit("DRY_RUN" => "false")++ assert_not error.success?+ assert_match(/Account #{@account.id}: failed, rolled back: StandardError: boom/, output)+ assert_equal [ @row_a.id ], @account.trades.distinct.pluck(:security_id), "the failed account rolled back"+ end++ # The repair's transaction has committed by the time the task reports on+ # it, so a failure while reporting must not claim a rollback.+ test "a failure while reporting a live repair does not claim a rollback" do+ holding = seed_observed_split+ SnaptradeAccount::SplitSecurityRepair.stubs(:accounts).returns(Account.where(id: @account.id))+ SnaptradeAccount::SplitSecurityRepair.any_instance.stubs(:conflicts).raises(StandardError, "report boom")++ output, error = invoke_task_expecting_exit("DRY_RUN" => "false")++ assert_not error.success?+ assert_equal Money.new(150, "USD"), holding.reload.avg_cost, "the repair committed before reporting failed"+ assert_match(/Account #{@account.id}: repair applied, but reporting failed: StandardError: report boom/, output)+ assert_no_match(/rolled back/, output)+ end++ test "a failure while reporting a dry run says nothing was written" do+ holding = seed_observed_split+ SnaptradeAccount::SplitSecurityRepair.stubs(:accounts).returns(Account.where(id: @account.id))+ SnaptradeAccount::SplitSecurityRepair.any_instance.stubs(:conflicts).raises(StandardError, "report boom")++ output, error = invoke_task_expecting_exit("DRY_RUN" => nil)++ assert_not error.success?+ assert_nil holding.reload.avg_cost+ assert_match(/Account #{@account.id}: reporting failed, nothing written: StandardError: report boom/, output)+ assert_no_match(/rolled back/, output)+ end++ test "the rake dry run names each row's exchange and the conflicting tickers" do+ seed_observed_split+ Security.create!(ticker: "SHOP", name: "Shopify", exchange_operating_mic: "XNYS").tap do |row|+ create_trade(row, account: @account, qty: 5, date: 9.days.ago.to_date, price: 100)+ end+ Security.create!(ticker: "SHOP", name: "Shopify", exchange_operating_mic: "XTSE").tap do |row|+ create_trade(row, account: @account, qty: 7, date: 8.days.ago.to_date, price: 130)+ end++ output, = with_env_overrides("DRY_RUN" => nil) do+ capture_io { Rake::Task["snaptrade:repair_split_securities"].invoke(@account.id) }+ end++ assert_match(/target #{@row_b.id} \(XNYS, Split Co\)/, output)+ assert_match(/#{@row_a.id} \(XNYS, Split Co\)/, output)+ assert_match(/SHOP: skipped, rows on different exchanges/, output)+ end++ attr_reader :account, :snaptrade_account++ def snaptrade_item+ @snaptrade_account.snaptrade_item+ end++ private+ # Runs the task (for every account unless an id is given) and returns its+ # stdout and stderr together, with the SystemExit its abort raises.+ def invoke_task_expecting_exit(env, *task_args)+ original_stdout, original_stderr = $stdout, $stderr+ $stdout = $stderr = StringIO.new+ error = assert_raises(SystemExit) do+ with_env_overrides(env) { Rake::Task["snaptrade:repair_split_securities"].invoke(*task_args) }+ end+ [ $stdout.string, error ]+ ensure+ $stdout, $stderr = original_stdout, original_stderr+ end+++ def repair!(allow_price_gaps: false)+ SnaptradeAccount::SplitSecurityRepair.new(@account, dry_run: false, allow_price_gaps: allow_price_gaps).run+ end++ # The #3988 state: buys on A, the current provider holding+ # on B with an unknown (zero) provider cost basis.+ def seed_observed_split+ create_trade(@row_a, account: @account, qty: 10, date: 20.days.ago.to_date, price: 100)+ create_trade(@row_a, account: @account, qty: 10, date: 10.days.ago.to_date, price: 200)+ holding = snaptrade_holding(@row_b, date: Date.current, qty: 20)+ holding.update!(cost_basis: 0, cost_basis_source: "provider")+ holding+ end++ def snaptrade_holding(security, date:, qty:)+ @account.holdings.create!(+ security: security,+ date: date,+ qty: qty,+ price: 300,+ amount: qty * 300,+ currency: "USD",+ account_provider_id: @provider_id+ )+ end++ def account_state+ [+ @account.trades.order(:id).pluck(:id, :security_id),+ @account.holdings.order(:id).pluck(:id, :security_id, :qty, :updated_at),+ @account.balances.count+ ]+ end+enddiff --git a/test/models/snaptrade_item/importer_test.rb b/test/models/snaptrade_item/importer_test.rbnew file mode 100644index 0000000000..2ce222a52a--- /dev/null+++ b/test/models/snaptrade_item/importer_test.rb@@ -0,0 +1,79 @@+require "test_helper"++class SnaptradeItem::ImporterTest < ActiveSupport::TestCase+ include ActiveJob::TestHelper++ setup do+ @snaptrade_account = snaptrade_accounts(:fidelity_401k)+ @provider = mock("snaptrade_provider")+ @provider.stubs(:get_account_activities).returns([])+ @provider.stubs(:get_activities).returns([])+ @importer = SnaptradeItem::Importer.new(snaptrade_items(:configured_item), snaptrade_provider: @provider)+ end++ # The flag is how anything outside the job chain (the item's syncing state,+ # SnaptradeAccount::SplitSecurityRepair) sees that a fetch is on its way,+ # so the job must never be queued without it.+ test "a fresh account with no activities is flagged and queues a background fetch" do+ assert_not @snaptrade_account.activities_fetch_pending?++ assert_enqueued_with(job: SnaptradeActivitiesFetchJob) do+ @importer.send(:import_activities, @snaptrade_account)+ end++ assert @snaptrade_account.reload.activities_fetch_pending?+ end++ test "no background fetch is queued when the pending flag cannot be set" do+ @snaptrade_account.stubs(:update!).with(activities_fetch_pending: true).raises(ActiveRecord::ActiveRecordError, "boom")++ assert_no_enqueued_jobs(only: SnaptradeActivitiesFetchJob) do+ assert_raises(ActiveRecord::ActiveRecordError) { @importer.send(:import_activities, @snaptrade_account) }+ end+ end++ # Set before the enqueue, the flag would otherwise outlive a fetch that was+ # never queued, holding the item in "syncing" until SyncCleanerJob clears it.+ test "the pending flag is cleared again when queueing the fetch raises" do+ queue = mock("configured_job")+ queue.stubs(:perform_later).raises(RuntimeError, "queue down")+ SnaptradeActivitiesFetchJob.stubs(:set).returns(queue)++ assert_raises(RuntimeError) { @importer.send(:import_activities, @snaptrade_account) }++ assert_not @snaptrade_account.reload.activities_fetch_pending?+ end++ # Active Job reports an adapter's EnqueueError by returning false, not by+ # raising.+ test "the pending flag is cleared again when the queue refuses the fetch" do+ queue = mock("configured_job")+ queue.stubs(:perform_later).returns(false)+ SnaptradeActivitiesFetchJob.stubs(:set).returns(queue)++ @importer.send(:import_activities, @snaptrade_account)++ assert_not @snaptrade_account.reload.activities_fetch_pending?+ end++ # A refused enqueue raises nothing, so support only learns of it from+ # /settings/debug.+ test "a refused fetch is logged against this connection" do+ family = families(:dylan_family)+ account = family.accounts.create!(name: "Linked 401k", balance: 0, currency: "USD", accountable: Investment.new)+ @snaptrade_account.ensure_account_provider!(account)+ @snaptrade_account.reload++ queue = mock("configured_job")+ queue.stubs(:perform_later).returns(false)+ SnaptradeActivitiesFetchJob.stubs(:set).returns(queue)++ assert_difference -> { DebugLogEntry.where(provider_key: "snaptrade", level: "error").count }, 1 do+ @importer.send(:import_activities, @snaptrade_account)+ end++ entry = DebugLogEntry.order(:created_at).last+ assert_equal [ "SnaptradeItem::Importer", "provider_sync", family, @snaptrade_account.account_provider, @snaptrade_account.id ],+ [ entry.source, entry.category, entry.family, entry.account_provider, entry.metadata["snaptrade_account_id"] ]+ end+end