The personal finance app for everyone (by everyone)
Ruby
fix(trade-republic): stop bond rescale migration reading later item columns (#5685)
Simone41a19a1c0680
diff --git a/db/migrate/20261008090000_rescale_trade_republic_bond_holding_prices.rb b/db/migrate/20261008090000_rescale_trade_republic_bond_holding_prices.rbindex f3e0d50555..a40e494f66 100644--- a/db/migrate/20261008090000_rescale_trade_republic_bond_holding_prices.rb+++ b/db/migrate/20261008090000_rescale_trade_republic_bond_holding_prices.rb@@ -24,7 +24,8 @@# prices are rescaled under the same check.## Balances and the account's current value were computed from the inflated-# prices too; the item sync scheduled at the end refreshes them.+# prices too; RefreshTradeRepublicBalancesAfterBondRescale schedules their+# refresh after the later item schema migrations have committed.class RescaleTradeRepublicBondHoldingPrices < ActiveRecord::Migration[8.1]PERCENT_QUOTE_RATIO = 10SHARED_BOND_TICKER = "BOND"@@ -36,7 +37,6 @@ class RescaleTradeRepublicBondHoldingPrices < ActiveRecord::Migration[8.1]def upbond_security_ids = Security.where(ticker: SHARED_BOND_TICKER, exchange_operating_mic: SHARED_BOND_MIC).pluck(:id)- item_ids = []TradeRepublicAccount.where(kind: "portfolio").includes(:account_provider).find_each do |trade_republic_account|# Account can require columns added by later migrations. Read its ID@@ -60,10 +60,7 @@ class RescaleTradeRepublicBondHoldingPrices < ActiveRecord::Migration[8.1]next if rescaled.zero? && !payload_rescaledsay "Rescaled #{rescaled} Trade Republic bond holdings on account #{provider.account_id}"- item_ids << trade_republic_account.trade_republic_item_idend-- schedule_syncs(item_ids.uniq)end# The old prices were wrong; restoring them would bring back the 100x error.@@ -101,14 +98,6 @@ class RescaleTradeRepublicBondHoldingPrices < ActiveRecord::Migration[8.1]changedend- def schedule_syncs(item_ids)- TradeRepublicItem.syncable.where(id: item_ids).find_each do |item|- item.sync_later- rescue => e- say "Could not schedule a sync for Trade Republic item #{item.id} (#{e.message}); it refreshes on its next sync"- end- end-def parse_decimal(value)return nil if value.blank?diff --git a/db/migrate/20261123210000_refresh_trade_republic_balances_after_bond_rescale.rb b/db/migrate/20261123210000_refresh_trade_republic_balances_after_bond_rescale.rbnew file mode 100644index 0000000000..31e14dd97f--- /dev/null+++ b/db/migrate/20261123210000_refresh_trade_republic_balances_after_bond_rescale.rb@@ -0,0 +1,27 @@+# frozen_string_literal: true++# Workers can run alongside db:prepare. Do not enqueue this refresh from the+# October price correction: device_id and session_expires_at do not exist yet.+# Refresh all linked portfolios once, including installations that already ran+# the correction (or whose earlier refresh failed). The old migration did not+# persist the affected item IDs, and corrected prices cannot identify them now.+class RefreshTradeRepublicBalancesAfterBondRescale < ActiveRecord::Migration[8.1]+ # This migration only schedules refreshes. Commit each item inside the rescue+ # so an after-commit enqueue failure cannot abort the entire migration.+ disable_ddl_transaction!++ def up+ TradeRepublicItem.reset_column_information+ item_ids = TradeRepublicAccount.where(kind: "portfolio").joins(:account_provider).select(:trade_republic_item_id)++ TradeRepublicItem.syncable.where(id: item_ids).find_each do |item|+ item.sync_later+ rescue => e+ say "Could not schedule a sync for Trade Republic item #{item.id} (#{e.message}); it refreshes on its next sync"+ end+ end++ def down+ # A refresh does not need to be undone.+ end+enddiff --git a/test/migrations/rescale_trade_republic_bond_holding_prices_migration_test.rb b/test/migrations/rescale_trade_republic_bond_holding_prices_migration_test.rbindex 916389523a..5fba589c9b 100644--- a/test/migrations/rescale_trade_republic_bond_holding_prices_migration_test.rb+++ b/test/migrations/rescale_trade_republic_bond_holding_prices_migration_test.rb@@ -3,7 +3,11 @@require "test_helper"require Rails.root.join("db/migrate/20261008090000_rescale_trade_republic_bond_holding_prices")+require Rails.root.join("db/migrate/20261123210000_refresh_trade_republic_balances_after_bond_rescale")+class RescaleTradeRepublicBondHoldingPricesMigrationTest < ActiveSupport::TestCase+ include ActiveJob::TestHelper+BOND_ISIN = "IT0005377152"STOCK_ISIN = "US0378331005"INTEREST_ISIN = "LU0000000001"@@ -30,7 +34,10 @@ class RescaleTradeRepublicBondHoldingPricesMigrationTest < ActiveSupport::TestCa@tr_account.reloadend- teardown { Account.reset_column_information }+ teardown do+ Account.reset_column_information+ TradeRepublicItem.reset_column_information+ endtest "rescales holdings before the account logo selection column exists" doholding = create_snapshot(BOND_ISIN, Date.current, qty: "2677.95", price: "84.04", cost_basis: "0.93")@@ -40,7 +47,7 @@ class RescaleTradeRepublicBondHoldingPricesMigrationTest < ActiveSupport::TestCaAccount.connection.remove_column(:accounts, :logo_selection)Account.reset_column_information- assert_difference -> { @item.syncs.count }, 1 do+ assert_no_difference -> { @item.syncs.count } dorun_migrationend@@ -49,6 +56,24 @@ class RescaleTradeRepublicBondHoldingPricesMigrationTest < ActiveSupport::TestCaassert_equal "0.8404", @tr_account.reload.raw_positions_payload.first["price"]end+ test "does not schedule a sync before later Trade Republic item columns exist" do+ holding = create_snapshot(BOND_ISIN, Date.current, qty: "2677.95", price: "84.04", cost_basis: "0.93")++ # Upgrades from before these migrations run this one first. PostgreSQL+ # restores the columns when the test transaction rolls back.+ connection = TradeRepublicItem.connection+ %i[timeline_cursors device_id session_expires_at].each do |column|+ connection.remove_column(:trade_republic_items, column)+ end+ TradeRepublicItem.reset_column_information++ assert_no_difference -> { Sync.where(syncable: @item).count } do+ run_migration+ end++ assert_equal BigDecimal("0.8404"), holding.reload.price+ end+test "rescales bond snapshots stored at percent of par" doolder = create_snapshot(BOND_ISIN, 3.days.ago.to_date, qty: "2677.95", price: "83.10", cost_basis: "0.93")latest = create_snapshot(BOND_ISIN, Date.current, qty: "2677.95", price: "84.04", cost_basis: "0.93")@@ -117,10 +142,10 @@ class RescaleTradeRepublicBondHoldingPricesMigrationTest < ActiveSupport::TestCaassert_equal "84.04", @tr_account.reload.raw_positions_payload.first["price"]end- test "schedules a sync only for items with rescaled holdings" do+ test "leaves sync scheduling to the later migration even when rerun" docreate_snapshot(BOND_ISIN, Date.current, qty: "2677.95", price: "84.04", cost_basis: "0.93")- assert_difference -> { @item.syncs.count }, 1 do+ assert_no_difference -> { @item.syncs.count } dorun_migrationendassert_no_difference -> { @item.syncs.count } do@@ -128,6 +153,67 @@ class RescaleTradeRepublicBondHoldingPricesMigrationTest < ActiveSupport::TestCaendend+ test "refreshes corrected portfolios only after the item schema migrations" do+ connection = TradeRepublicItem.connection+ %i[device_id session_expires_at].each do |column|+ connection.remove_column(:trade_republic_items, column)+ end+ TradeRepublicItem.reset_column_information++ assert_no_enqueued_jobs only: SyncJob do+ run_migration+ end+ assert_equal "0.8404", @tr_account.reload.raw_positions_payload.first["price"]++ connection.add_column(:trade_republic_items, :device_id, :uuid, default: -> { "gen_random_uuid()" }, null: false)+ connection.add_column(:trade_republic_items, :session_expires_at, :datetime)+ # Deliberately keep the migration process's stale model cache.+ assert_enqueued_jobs 1, only: SyncJob do+ run_refresh+ end+ assert @item.reload.ready_for_sync?+ assert @item.device_id.present?+ assert_no_difference -> { @item.syncs.count } do+ run_refresh+ end+ end++ test "refresh continues after an item cannot enqueue its sync" do+ failed_item = mock("item whose queue is unavailable")+ failed_item.stubs(:id).returns(@item.id)+ failed_item.expects(:sync_later).raises(RuntimeError, "queue down")+ next_item = mock("next eligible item")+ next_item.expects(:sync_later).once+ items = mock("eligible linked items")+ items.expects(:find_each).multiple_yields([ failed_item ], [ next_item ])+ TradeRepublicItem.stubs(:syncable).returns(items)+ items.stubs(:where).returns(items)++ migration = RefreshTradeRepublicBalancesAfterBondRescale.new+ migration.expects(:say).with(regexp_matches(/Could not schedule a sync.*queue down/))+ migration.up+ end++ test "refresh skips expired and disconnected items and unlinked portfolios" do+ @item.update_columns(session_expires_at: 1.hour.ago)+ assert_no_enqueued_jobs only: SyncJob do+ run_refresh+ end+ @item.update_columns(session_expires_at: nil, status: "requires_update")+ assert_no_enqueued_jobs only: SyncJob do+ run_refresh+ end+ @item.update_columns(status: "good", scheduled_for_deletion: true)+ assert_no_enqueued_jobs only: SyncJob do+ run_refresh+ end+ @item.update_columns(scheduled_for_deletion: false)+ @tr_account.account_provider.destroy!+ assert_no_enqueued_jobs only: SyncJob do+ run_refresh+ end+ end+privatedef create_snapshot(isin, date, qty:, price:, cost_basis:, **attributes)@@ -145,9 +231,44 @@ class RescaleTradeRepublicBondHoldingPricesMigrationTest < ActiveSupport::TestCa}.merge(attributes))end+ def run_refresh+ ActiveRecord::Migration.suppress_messages do+ RefreshTradeRepublicBalancesAfterBondRescale.new.up+ end+ end+def run_migrationActiveRecord::Migration.suppress_messages doRescaleTradeRepublicBondHoldingPrices.new.upendendend++# Exercise the real after-commit enqueue boundary without a fixture transaction.+class TradeRepublicBalanceRefreshEnqueueTest < ActiveSupport::TestCase+ self.use_transactional_tests = false+ self.fixture_table_names = []++ Item = Struct.new(:id) do+ def sync_later+ ActiveRecord::Base.transaction { SyncJob.perform_later(id) }+ end+ end++ test "an after-commit queue failure does not abort the migration or skip later items" do+ items = mock("eligible linked items")+ TradeRepublicItem.stubs(:syncable).returns(items)+ items.stubs(:where).returns(items)+ items.expects(:find_each).multiple_yields([ Item.new("failed") ], [ Item.new("next") ])+ SyncJob.queue_adapter.expects(:enqueue).with { |job| job.arguments == [ "failed" ] }.raises(RuntimeError, "queue down")+ SyncJob.queue_adapter.expects(:enqueue).with { |job| job.arguments == [ "next" ] }.once++ migration = RefreshTradeRepublicBalancesAfterBondRescale.new+ migration.expects(:say).with(regexp_matches(/Could not schedule a sync.*queue down/))+ # Use Rails' transaction wrapper, not just migration.up: the error otherwise+ # happens after up has returned, outside its per-item rescue.+ migrator = ActiveRecord::Migrator.allocate+ migrator.stubs(:connection).returns(ActiveRecord::Base.connection)+ migrator.send(:ddl_transaction, migration) { migration.up }+ end+end