The personal finance app for everyone (by everyone)
Ruby
Mark carried-forward prices and keep them out of freshness (#5627)
jaysbeekayd2282d04916d
diff --git a/app/controllers/api/v1/security_prices_controller.rb b/app/controllers/api/v1/security_prices_controller.rbindex f72d89dce3..45b9972386 100644--- a/app/controllers/api/v1/security_prices_controller.rb+++ b/app/controllers/api/v1/security_prices_controller.rb@@ -124,6 +124,9 @@ class Api::V1::SecurityPricesController < Api::V1::BaseControllerprovisional = parse_boolean_filter_param(:provisional)query = query.where(provisional: provisional)end+ if params.key?(:carried_forward)+ query = query.where(carried_forward: parse_boolean_filter_param(:carried_forward))+ endqueryendenddiff --git a/app/models/investment_statement.rb b/app/models/investment_statement.rbindex c1801ed941..d95763ae73 100644--- a/app/models/investment_statement.rb+++ b/app/models/investment_statement.rb@@ -889,7 +889,7 @@ class InvestmentStatement# Latest price date per held security on or before as_of, so a price# recorded after as_of cannot make a past check look fresh.# The last quote on or before `as_of` per held security: a real price row- # (not a provisional one carried forward, nor a zero placeholder, which+ # (not a carried-forward or provisional row, nor a zero placeholder, which# the price importer skips too), or the date of a holding a provider# synced with its own price, whichever is later.def latest_quote_dates(as_of)@@ -901,7 +901,7 @@ class InvestmentStatementsecurity_ids = current_holdings.map(&:security_id).uniqpriced = Security::Price.where(security_id: security_ids)- .where(date: ..as_of, provisional: false)+ .where(date: ..as_of, carried_forward: false, provisional: false).where("price > 0").group(:security_id).maximum(:date)diff --git a/app/models/security/manual_price_import.rb b/app/models/security/manual_price_import.rbindex 62cdd22006..538849ea96 100644--- a/app/models/security/manual_price_import.rb+++ b/app/models/security/manual_price_import.rb@@ -173,9 +173,9 @@ class Security::ManualPriceImport# xmax is 0 only on a row this statement inserted, so the counts hold# even when another request writes the same dates concurrently.inserted = Security::Price.upsert_all(- parsed.map { |row| { security_id: security.id, date: row.date, price: row.price, currency: currency, provisional: false } },+ parsed.map { |row| { security_id: security.id, date: row.date, price: row.price, currency: currency, provisional: false, carried_forward: false } },unique_by: %i[security_id date currency],- update_only: %i[price provisional],+ update_only: %i[price provisional carried_forward],returning: Arel.sql("(xmax = 0) AS inserted")).rows.flattencreated = inserted.count(true)diff --git a/app/models/security/price.rb b/app/models/security/price.rbindex 4feb765a71..e1af77b991 100644--- a/app/models/security/price.rb+++ b/app/models/security/price.rb@@ -1,3 +1,9 @@+# carried_forward: the importer filled this date by repeating an earlier+# price; a real quote is carried_forward: false. provisional: a recent+# carried-forward price the importer asks the provider for again. Every+# provisional row is carried forward (provisional rows stored before the+# column existed were backfilled), so readers of real quotes filter on+# carried_forward alone.class Security::Price < ApplicationRecordbelongs_to :securitydiff --git a/app/models/security/price/importer.rb b/app/models/security/price/importer.rbindex ebe93ee6b6..1365ec4002 100644--- a/app/models/security/price/importer.rb+++ b/app/models/security/price/importer.rb@@ -91,12 +91,14 @@ class Security::Price::Importer# stored history before its first price is kept.replace_db_price = clear_cache && earliest_provider_price.present? && date >= earliest_provider_price.date+ kept_db_price = falsechosen_price, chosen_currency = if replace_db_price || is_provisional# For provisional/cache clear: only use provider price, let gap-fill handle missing# This ensures stale DB values don't persist when provider has no weekend data[ provider_price_value, provider_currency ]elsif has_db_price# For non-provisional with valid DB price: preserve existing value (user edits)+ kept_db_price = true[ db_price_value, db_price&.currency ]else# Fill gaps with provider data@@ -126,7 +128,10 @@ class Security::Price::Importerdate: date,price: chosen_price,currency: chosen_currency || "USD",- provisional: provisional+ provisional: provisional,+ # A kept row keeps its own mark; any other row is carried forward+ # exactly when it repeats an earlier price.+ carried_forward: kept_db_price ? db_price.carried_forward : used_locf}end@@ -317,15 +322,17 @@ class Security::Price::Importerreturn provider_price_value if provider_price_value.present? && provider_price_value.to_f > 0- # Fall back to most recent DB price before cutoff+ # Fall back to the most recent real DB price before cutoff, or the most+ # recent carried-forward one when there is no real one. Without any, the+ # caller would take the stored history for pre-listing and advance+ # first_provider_price_on past it.currency = prev_price_currency || db_price_currencySecurity::Price.where(security_id: security.id).where("date < ?", cutoff_date).where("price > 0")- .where(provisional: false).then { |q| currency.present? ? q.where(currency: currency) : q }- .order(date: :desc)+ .order(carried_forward: :asc, date: :desc).limit(1).pick(:price)enddiff --git a/app/views/api/v1/security_prices/_security_price.json.jbuilder b/app/views/api/v1/security_prices/_security_price.json.jbuilderindex 9804493bbe..0bd65cfeee 100644--- a/app/views/api/v1/security_prices/_security_price.json.jbuilder+++ b/app/views/api/v1/security_prices/_security_price.json.jbuilder@@ -6,6 +6,7 @@ json.price Money.new(security_price.price, security_price.currency).formatjson.price_amount format("%.4f", security_price.price.to_d)json.currency security_price.currencyjson.provisional security_price.provisional+json.carried_forward security_price.carried_forwardjson.security dojson.id security_price.security.iddiff --git a/db/migrate/20261121100000_add_carried_forward_to_security_prices.rb b/db/migrate/20261121100000_add_carried_forward_to_security_prices.rbnew file mode 100644index 0000000000..e3ed20fcc9--- /dev/null+++ b/db/migrate/20261121100000_add_carried_forward_to_security_prices.rb@@ -0,0 +1,5 @@+class AddCarriedForwardToSecurityPrices < ActiveRecord::Migration[8.1]+ def change+ add_column :security_prices, :carried_forward, :boolean, default: false, null: false+ end+enddiff --git a/db/migrate/20261121100100_backfill_carried_forward_on_security_prices.rb b/db/migrate/20261121100100_backfill_carried_forward_on_security_prices.rbnew file mode 100644index 0000000000..0609974cc1--- /dev/null+++ b/db/migrate/20261121100100_backfill_carried_forward_on_security_prices.rb@@ -0,0 +1,48 @@+# Prices the importer carried forward before carried_forward existed are+# stored false. The ones that can be proven are the provisional rows: the+# importer marks a row provisional only when it carried the price forward.+# Older carried rows cannot be told from a quote that did not move (a pegged+# fund, a crypto weekend, a no-trade day), so they are left as they are;+# clear_cache rebuilds a security's prices.+#+# Batched outside a transaction so a large table is not locked in one+# statement. Rows already marked are skipped, so it can run more than once.+# The outer update repeats the predicate so a row a refresh made real after+# the subquery read it is skipped. Such a skip can empty a whole batch, so the+# loop ends only when no eligible row is left.+class BackfillCarriedForwardOnSecurityPrices < ActiveRecord::Migration[8.1]+ disable_ddl_transaction!++ def up+ loop do+ updated = exec_update(<<~SQL)+ UPDATE security_prices+ SET carried_forward = true+ WHERE id IN (+ SELECT id FROM security_prices+ WHERE provisional = true AND carried_forward = false+ LIMIT #{batch_size}+ )+ AND provisional = true AND carried_forward = false+ SQL+ break if updated.zero? && !eligible_rows_remain?+ end+ end++ # The column itself is removed by rolling back the migration that added it.+ def down+ end++ private+ def batch_size+ 10_000+ end++ # Uncached: the updates do not clear the query cache, so a cached answer+ # would keep the loop running.+ def eligible_rows_remain?+ connection.uncached do+ connection.select_value("SELECT 1 FROM security_prices WHERE provisional = true AND carried_forward = false LIMIT 1").present?+ end+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex a9f7304c4e..f45334ca0d 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -2412,6 +2412,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_23_220100) doendcreate_table "security_prices", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.boolean "carried_forward", default: false, null: falset.datetime "created_at", null: falset.string "currency", default: "USD", null: falset.date "date", null: falsediff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex 78d0f06027..ba52c8f55c 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -3519,6 +3519,7 @@ components:- price_amount- currency- provisional+ - carried_forward- security- created_at- updated_at@@ -3539,6 +3540,11 @@ components:type: stringprovisional:type: boolean+ carried_forward:+ type: boolean+ description: 'The price repeats an earlier one: no quote was available for+ this date. A non-provisional price stored before this field was added+ reads false even when it repeats an earlier one'security:type: objectrequired:@@ -9916,6 +9922,13 @@ paths:or false.schema:type: boolean+ - name: carried_forward+ in: query+ required: false+ description: Filter by whether the price repeats an earlier one rather than+ being a quote for its date. When supplied, must be true or false.+ schema:+ type: booleanresponses:'200':description: security prices listeddiff --git a/spec/requests/api/v1/security_prices_spec.rb b/spec/requests/api/v1/security_prices_spec.rbindex 3325c6db7b..11db5f29ee 100644--- a/spec/requests/api/v1/security_prices_spec.rb+++ b/spec/requests/api/v1/security_prices_spec.rb@@ -112,6 +112,9 @@ RSpec.describe 'API V1 Security Prices', type: :request doparameter name: :provisional, in: :query, required: false,description: 'Filter by provisional price status. When supplied, must be true or false.',schema: { type: :boolean }+ parameter name: :carried_forward, in: :query, required: false,+ description: 'Filter by whether the price repeats an earlier one rather than being a quote for its date. When supplied, must be true or false.',+ schema: { type: :boolean }response '200', 'security prices listed' doschema '$ref' => '#/components/schemas/SecurityPriceCollection'diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rbindex 93df7d1f60..6bf22c6052 100644--- a/spec/swagger_helper.rb+++ b/spec/swagger_helper.rb@@ -1907,7 +1907,7 @@ RSpec.configure do |config|},SecurityPrice: {type: :object,- required: %w[id date price price_amount currency provisional security created_at updated_at],+ required: %w[id date price price_amount currency provisional carried_forward security created_at updated_at],properties: {id: { type: :string, format: :uuid },date: { type: :string, format: :date },@@ -1915,6 +1915,7 @@ RSpec.configure do |config|price_amount: { type: :string, description: 'Exact decimal security price' },currency: { type: :string },provisional: { type: :boolean },+ carried_forward: { type: :boolean, description: 'The price repeats an earlier one: no quote was available for this date. A non-provisional price stored before this field was added reads false even when it repeats an earlier one' },security: {type: :object,required: %w[id ticker],diff --git a/test/controllers/api/v1/security_prices_controller_test.rb b/test/controllers/api/v1/security_prices_controller_test.rbindex 4039766d9b..073a5f08be 100644--- a/test/controllers/api/v1/security_prices_controller_test.rb+++ b/test/controllers/api/v1/security_prices_controller_test.rb@@ -109,6 +109,25 @@ class Api::V1::SecurityPricesControllerTest < ActionDispatch::IntegrationTestassert_equal [ @security_price.id ], response_data["security_prices"].map { |price| price["id"] }end+ test "lists whether a price is carried forward and filters on it" do+ carried = Security::Price.create!(security: @security, date: @security_price.date + 1.day, price: @security_price.price, currency: @security_price.currency, carried_forward: true)++ get api_v1_security_prices_url, params: { security_id: @security.id, carried_forward: true }, headers: api_headers(@api_key)+ assert_response :success+ rows = JSON.parse(response.body)["security_prices"]+ assert_equal [ [ carried.id, true ] ], rows.map { |price| [ price["id"], price["carried_forward"] ] }++ get api_v1_security_prices_url, params: { security_id: @security.id, carried_forward: false }, headers: api_headers(@api_key)+ assert_not_includes JSON.parse(response.body)["security_prices"].map { |price| price["id"] }, carried.id+ end++ test "rejects malformed carried_forward filter" do+ get api_v1_security_prices_url, params: { carried_forward: "maybe" }, headers: api_headers(@api_key)++ assert_response :unprocessable_entity+ assert_includes JSON.parse(response.body)["errors"], "carried_forward must be true or false"+ end+test "rejects blank provisional filter" doget api_v1_security_prices_url,params: { provisional: "" },diff --git a/test/migrations/backfill_carried_forward_on_security_prices_migration_test.rb b/test/migrations/backfill_carried_forward_on_security_prices_migration_test.rbnew file mode 100644index 0000000000..3e900e81ec--- /dev/null+++ b/test/migrations/backfill_carried_forward_on_security_prices_migration_test.rb@@ -0,0 +1,130 @@+# frozen_string_literal: true++require "test_helper"+require Rails.root.join("db/migrate/20261121100100_backfill_carried_forward_on_security_prices")++class BackfillCarriedForwardOnSecurityPricesMigrationTest < ActiveSupport::TestCase+ FRIDAY = Date.new(2026, 10, 30)++ setup do+ @security = Security.create!(ticker: "BACKFILL", name: "Backfill")+ end++ test "marks provisional rows, across batches" do+ rows = (0..2).map { |day| price(FRIDAY + day.days, 100, provisional: true) }+ migration = BackfillCarriedForwardOnSecurityPrices.new+ migration.stubs(:batch_size).returns(1)+ updates = 0+ migration.define_singleton_method(:exec_update) { |*args| updates += 1; super(*args) }++ ActiveRecord::Migration.suppress_messages { migration.up }++ assert_equal [ true ] * 3, rows.map { |p| p.reload.carried_forward }+ # One update per row, then the empty one that ends the loop.+ assert_equal 4, updates+ end++ # A refresh can make every row of a batch real before its update runs.+ test "an update that a refresh emptied does not end the backfill" do+ rows = (0..1).map { |day| price(FRIDAY + day.days, 100, provisional: true) }+ migration = BackfillCarriedForwardOnSecurityPrices.new+ migration.stubs(:batch_size).returns(1)+ emptied = false+ migration.define_singleton_method(:exec_update) do |*args|+ next super(*args) if emptied+ emptied = true+ 0+ end++ ActiveRecord::Migration.suppress_messages { migration.up }++ assert_equal [ true ] * 2, rows.map { |p| p.reload.carried_forward }+ end++ # A weekend row repeating Friday may be a pegged or crypto quote.+ test "leaves every non-provisional row, repeats included" do+ rows = [ price(FRIDAY, 100), price(FRIDAY + 1.day, 100), price(FRIDAY + 4.days, 100) ]++ run_migration++ assert_equal [ false ] * 3, rows.map { |p| p.reload.carried_forward }+ end++ test "can run twice" do+ provisional = price(FRIDAY, 100, provisional: true)++ run_migration+ run_migration++ assert provisional.reload.carried_forward+ end++ private+ def price(date, value, provisional: false)+ Security::Price.create!(security: @security, date: date, price: value, currency: "USD", provisional: provisional)+ end++ def run_migration+ ActiveRecord::Migration.suppress_messages do+ BackfillCarriedForwardOnSecurityPrices.new.up+ end+ end+end++# A refresh can commit a real quote between the backfill's subquery and its+# update. Real connections and commits, so this cannot run in a transaction.+class BackfillCarriedForwardOnSecurityPricesRaceTest < ActiveSupport::TestCase+ self.use_transactional_tests = false++ setup do+ @security = Security.create!(ticker: "BACKFILLRACE", name: "Backfill race")+ @row = Security::Price.create!(security: @security, date: Date.new(2026, 10, 30), price: 100, currency: "USD", provisional: true)+ end++ teardown do+ Security::Price.where(security_id: @security.id).delete_all+ @security.delete+ end++ test "skips a row a refresh made real while the update waited for it" do+ refresh = ActiveRecord::Base.connection_pool.checkout+ refresh.begin_db_transaction+ # A raw BEGIN is not tracked by transaction_open?, so track it here.+ refresh_open = true+ refresh.exec_update("UPDATE security_prices SET provisional = false, price = 101 WHERE id = #{refresh.quote(@row.id)}")++ backfill = Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do+ ActiveRecord::Migration.suppress_messages { BackfillCarriedForwardOnSecurityPrices.new.up }+ end+ end++ assert wait_for_blocked_update, "the backfill must be waiting on the refresh's row lock"+ refresh.commit_db_transaction+ refresh_open = false+ assert backfill.join(10), "the backfill must finish once the refresh commits"++ @row.reload+ assert_equal [ false, false ], [ @row.provisional, @row.carried_forward ]+ ensure+ refresh.rollback_db_transaction if refresh_open+ ActiveRecord::Base.connection_pool.checkin(refresh) if refresh+ backfill&.kill if backfill&.alive?+ end++ private+ def wait_for_blocked_update+ 50.times do+ # Uncached: a cached first answer would be repeated on every poll.+ waiting = ActiveRecord::Base.uncached do+ ActiveRecord::Base.connection.select_value(<<~SQL)+ SELECT count(*) FROM pg_stat_activity+ WHERE wait_event_type = 'Lock' AND query LIKE '%SET carried_forward = true%'+ SQL+ end+ return true if waiting.to_i.positive?+ sleep 0.1+ end+ false+ end+enddiff --git a/test/models/investment_statement_test.rb b/test/models/investment_statement_test.rbindex 7656e4c3a7..79bd20905e 100644--- a/test/models/investment_statement_test.rb+++ b/test/models/investment_statement_test.rb@@ -2562,7 +2562,7 @@ class InvestmentStatementTest < ActiveSupport::TestCasecarried = Security.create!(ticker: "CARRY", name: "Carried forward")Security::Price.create!(security: carried, date: as_of - 10.days, price: 10, currency: "USD")(0..2).each do |days_ago|- Security::Price.create!(security: carried, date: as_of - days_ago.days, price: 10, currency: "USD", provisional: true)+ Security::Price.create!(security: carried, date: as_of - days_ago.days, price: 10, currency: "USD", provisional: true, carried_forward: true)endHolding.create!(account: account, security: carried, date: as_of, qty: 1, price: 10, amount: 10, currency: "USD", cost_basis: 8, cost_basis_locked: true)@@ -2571,6 +2571,26 @@ class InvestmentStatementTest < ActiveSupport::TestCaseassert_equal [ [ "CARRY", as_of - 10.days ] ], stale.map { |i| [ i.security.ticker, i.detail ] }end+ # Carried-forward rows older than the provisional lookback are stored+ # non-provisional, so they need their own mark to stay out of freshness.+ test "data_quality_issues does not count old carried-forward prices as quotes" do+ account = create_investment_account(balance: 5000)+ as_of = Date.current - 8.days+ last_quote = Date.current - 15.days+ security = Security.create!(ticker: "GAPPED", name: "Gap filled")+ provider = mock+ provider.stubs(:fetch_security_prices).returns(Provider::Response.new(success?: true, error: nil, data: [+ OpenStruct.new(security: security, date: last_quote, price: 10, currency: "USD")+ ]))+ Security::Price::Importer.new(security: security, security_provider: provider, start_date: last_quote, end_date: Date.current).import_provider_prices+ Holding.create!(account: account, security: security, date: as_of, qty: 1, price: 10, amount: 10, currency: "USD", cost_basis: 8, cost_basis_locked: true)++ assert_not Security::Price.find_by!(security: security, date: as_of).provisional, "the precondition: the filled row at as_of is not provisional"+ stale = @statement.data_quality_issues(as_of: as_of).select { |i| i.kind == :stale_price }++ assert_equal [ [ "GAPPED", last_quote ] ], stale.map { |i| [ i.security.ticker, i.detail ] }+ end+# One account can hold the same security in two currencies. Without a cost# basis both are flagged, tied on everything but the holding, so the# holding id settles their order whatever order they arrive in.diff --git a/test/models/security/manual_price_import_test.rb b/test/models/security/manual_price_import_test.rbindex c2b43dffbe..561a56d069 100644--- a/test/models/security/manual_price_import_test.rb+++ b/test/models/security/manual_price_import_test.rb@@ -33,6 +33,14 @@ class Security::ManualPriceImportTest < ActiveSupport::TestCaseassert_not existing.provisionalend+ test "a close over a carried-forward price counts as a real quote" do+ existing = @security.prices.create!(date: 1.day.ago.to_date, price: 20, currency: "AUD", carried_forward: true)++ import([ row(1.day.ago, "23") ])++ assert_not existing.reload.carried_forward+ end+test "one bad row leaves every row in the batch unwritten" do@security.prices.create!(date: 5.days.ago.to_date, price: 19, currency: "AUD")diff --git a/test/models/security/price/importer_test.rb b/test/models/security/price/importer_test.rbindex a1f00272bf..069c65b4d2 100644--- a/test/models/security/price/importer_test.rb+++ b/test/models/security/price/importer_test.rb@@ -618,6 +618,150 @@ class Security::Price::ImporterTest < ActiveSupport::TestCaseassert_not old_price.provisional, "Old gap-filled price should not be provisional"end+ test "an old gap-filled price is carried forward, the quote it repeats is not" do+ Security::Price.delete_all++ start_date = 20.days.ago.to_date+ end_date = start_date + 2.days++ @provider.expects(:fetch_security_prices).returns(provider_success_response([+ OpenStruct.new(security: @security, date: start_date, price: 150, currency: "USD")+ ]))++ Security::Price::Importer.new(+ security: @security,+ security_provider: @provider,+ start_date: start_date,+ end_date: end_date+ ).import_provider_prices++ rows = Security::Price.where(security: @security).order(:date)+ assert_equal [ [ start_date, false, false ], [ start_date + 1.day, true, false ], [ end_date, true, false ] ],+ rows.map { |p| [ p.date, p.carried_forward, p.provisional ] },+ "the filled days are carried forward though too old to be provisional"+ end++ test "a stored price the provider has no quote for is not marked carried forward" do+ Security::Price.delete_all++ start_date = 20.days.ago.to_date+ user_date = start_date + 1.day+ end_date = start_date + 2.days+ Security::Price.create!(security: @security, date: user_date, price: 120, currency: "USD")++ @provider.expects(:fetch_security_prices).returns(provider_success_response([+ OpenStruct.new(security: @security, date: start_date, price: 150, currency: "USD")+ ]))++ Security::Price::Importer.new(+ security: @security,+ security_provider: @provider,+ start_date: start_date,+ end_date: end_date+ ).import_provider_prices++ kept = Security::Price.find_by!(security: @security, date: user_date)+ filled = Security::Price.find_by!(security: @security, date: end_date)+ assert_equal [ 120, false ], [ kept.price, kept.carried_forward ], "the stored price is kept as a real one"+ assert_equal [ 120, true ], [ filled.price, filled.carried_forward ], "the day after repeats it"+ end++ test "a carried-forward price the provider later quotes is no longer carried forward" do+ Security::Price.delete_all++ test_date = Date.current+ test_date += 1.day while test_date.saturday? || test_date.sunday?++ travel_to test_date do+ Security::Price.create!(security: @security, date: Date.current, price: 100, currency: "USD", provisional: true, carried_forward: true)++ @provider.expects(:fetch_security_prices).returns(provider_success_response([+ OpenStruct.new(security: @security, date: Date.current, price: 165, currency: "USD")+ ]))++ Security::Price::Importer.new(+ security: @security,+ security_provider: @provider,+ start_date: Date.current,+ end_date: Date.current+ ).import_provider_prices++ price = Security::Price.find_by!(security: @security, date: Date.current)+ assert_equal [ 165, false, false ], [ price.price, price.provisional, price.carried_forward ]+ end+ end++ test "a carried-forward price kept by a later import stays carried forward" do+ Security::Price.delete_all++ start_date = 20.days.ago.to_date+ carried_date = start_date + 1.day+ Security::Price.create!(security: @security, date: carried_date, price: 100, currency: "USD", carried_forward: true)++ @provider.expects(:fetch_security_prices).returns(provider_success_response([+ OpenStruct.new(security: @security, date: start_date, price: 100, currency: "USD"),+ OpenStruct.new(security: @security, date: carried_date, price: 105, currency: "USD")+ ]))++ Security::Price::Importer.new(+ security: @security,+ security_provider: @provider,+ start_date: start_date,+ end_date: carried_date+ ).import_provider_prices++ kept = Security::Price.find_by!(security: @security, date: carried_date)+ assert_equal [ 100, true ], [ kept.price, kept.carried_forward ]+ end++ # The quote's day was re-closed at 110 after 100 had been carried past it.+ test "a fill anchors on the last real quote, not a carried-forward one" do+ Security::Price.delete_all++ quote_date = 20.days.ago.to_date+ Security::Price.create!(security: @security, date: quote_date, price: 110, currency: "USD")+ Security::Price.create!(security: @security, date: quote_date + 1.day, price: 100, currency: "USD", carried_forward: true)+ end_date = quote_date + 4.days++ @provider.expects(:fetch_security_prices).returns(provider_success_response([+ OpenStruct.new(security: @security, date: end_date, price: 130, currency: "USD")+ ]))++ Security::Price::Importer.new(+ security: @security,+ security_provider: @provider,+ start_date: quote_date,+ end_date: end_date+ ).import_provider_prices++ filled = Security::Price.where(security: @security, date: (quote_date + 2.days)..end_date).order(:date)+ assert_equal [ 110, 110, 130 ], filled.map(&:price)+ end++ test "a fill with only carried-forward prices before it anchors on the latest one" do+ Security::Price.delete_all++ first_date = 40.days.ago.to_date+ Security::Price.create!(security: @security, date: first_date, price: 100, currency: "USD", carried_forward: true)+ Security::Price.create!(security: @security, date: first_date + 1.day, price: 105, currency: "USD", carried_forward: true)+ end_date = first_date + 4.days++ @provider.expects(:fetch_security_prices).returns(provider_success_response([+ OpenStruct.new(security: @security, date: end_date, price: 130, currency: "USD")+ ]))++ Security::Price::Importer.new(+ security: @security,+ security_provider: @provider,+ start_date: first_date,+ end_date: end_date+ ).import_provider_prices++ filled = Security::Price.where(security: @security, date: (first_date + 2.days)..end_date).order(:date)+ assert_equal [ 105, 105, 130 ], filled.map(&:price)+ assert_nil @security.reload.first_provider_price_on, "the stored history is not treated as pre-listing"+ end+test "provisional weekend prices get fixed via cascade from Friday" doSecurity::Price.delete_all