The personal finance app for everyone (by everyone)
Ruby
Add an asset classification schema to securities (#3608)
jaysbeekay235e6548a6db
diff --git a/app/models/security.rb b/app/models/security.rbindex 981b35dada..1a1343da83 100644--- a/app/models/security.rb+++ b/app/models/security.rb@@ -41,6 +41,47 @@ class Security < ApplicationRecordSetting.brand_fetch_icon_url(base_asset, namespace: "crypto")end+ # Classification taxonomy: the six-class / twelve-sub-class scheme other+ # portfolio trackers use, so an import maps onto it without a translation+ # table. The database enforces the same sets (chk_securities_asset_class,+ # chk_securities_asset_sub_class, chk_securities_classification_source);+ # adding a value means changing both, deliberately.+ #+ # Schema only for now: nothing writes these columns yet, so every security+ # is unclassified (NULL) until a later drop populates them.+ #+ # The migration repeats these lists rather than reading them from here, so+ # that it produces the same schema whenever it runs. Changing a list is+ # therefore a two-file edit, and "the model taxonomy and the database+ # constraint list the same values" fails if only one side moves.+ #+ # `sector` and `industry` have no constants and no validation on purpose:+ # they hold provider vocabulary, which no two providers agree on. An+ # `inclusion` rule there would reject a value a provider legitimately+ # returns.+ #+ # `region` is NOT the same case, and grouping it with those two would be+ # wrong. No provider supplies a region -- they supply a country, and the+ # region is derived from it against a list this application owns -- so its+ # vocabulary is closed and a model-level `inclusion` validation is the right+ # enforcement once something writes it. It is unconstrained today only+ # because nothing does. It is left unconstrained in the DATABASE for a+ # different reason: the list belongs in configuration, where widening it+ # should not need a migration. The migration header says the same.+ ASSET_CLASSES = %w[+ alternative_investment commodity equity fixed_income liquidity real_estate+ ].freeze++ ASSET_SUB_CLASSES = %w[+ bond cash collectible commodity cryptocurrency etf loan mutual_fund+ precious_metal private_equity real_estate stock+ ].freeze++ # Same shape as Holding's cost-basis provenance: who set the classification,+ # so a later writer knows whether it may replace it. `classification_locked`+ # is the user's veto over every source.+ CLASSIFICATION_SOURCES = %w[provider manual ai default].freeze+before_validation :upcase_symbolsbefore_save :generate_logo_url_from_brandfetch, if: :should_generate_logo?before_save :reset_first_provider_price_on_if_provider_changed@@ -52,6 +93,9 @@ class Security < ApplicationRecordvalidates :ticker, uniqueness: { scope: :exchange_operating_mic, case_sensitive: false }validates :kind, inclusion: { in: KINDS }validates :price_provider, inclusion: { in: ->(_) { Security.valid_price_providers } }, allow_nil: true+ validates :asset_class, inclusion: { in: ASSET_CLASSES }, allow_nil: true+ validates :asset_sub_class, inclusion: { in: ASSET_SUB_CLASSES }, allow_nil: true+ validates :classification_source, inclusion: { in: CLASSIFICATION_SOURCES }, allow_nil: truescope :online, -> { where(offline: false) }scope :standard, -> { where(kind: "standard") }diff --git a/db/migrate/20260916120000_add_classification_to_securities.rb b/db/migrate/20260916120000_add_classification_to_securities.rbnew file mode 100644index 0000000000..b01395364f--- /dev/null+++ b/db/migrate/20260916120000_add_classification_to_securities.rb@@ -0,0 +1,129 @@+# frozen_string_literal: true++# Schema for classifying a security by asset class, sub-class, sector, industry+# and region, with provenance and a lock so a user's manual classification is+# not overwritten by a provider or a default.+#+# Schema only. Nothing reads or writes the columns until a later drop, so+# every value stays NULL and the migration carries no data risk.+#+# The enumerated columns are plain strings with a check constraint, matching+# `securities.kind` (`chk_securities_kind`): adding a value later is a+# constraint swap, not a type change. The permitted+# values are the six-class / twelve-sub-class taxonomy other portfolio trackers+# use, so an import maps onto them without a translation table.+#+# Written as explicit up/down rather than `change` because the constraints are+# added NOT VALID and validated afterwards. On PostgreSQL that is two short+# locks instead of one full-table scan under an exclusive lock; it needs+# `disable_ddl_transaction!` to mean anything, and `validate_check_constraint`+# has no inverse for a `change` block to record.+class AddClassificationToSecurities < ActiveRecord::Migration[8.1]+ disable_ddl_transaction!++ # These lists are deliberately repeated here rather than read from+ # `Security::ASSET_CLASSES` and friends. A migration has to produce the same+ # schema whenever it is run -- on a fresh install today, on a self-hosted+ # instance upgrading in a year -- and a constant it borrowed from a model+ # would produce a different constraint once the model's list changed. That is+ # the usual reason migrations do not reference application code, and it+ # applies here rather than being a copy-paste.+ #+ # The cost is that growing the taxonomy is a two-file edit. `SecurityTest`+ # "the model taxonomy and the database constraint list the same values" reads+ # the rendered constraint back out of the catalog and compares it to the+ # model's constants, so the two cannot silently diverge -- a change to one+ # without the other fails that test rather than shipping.++ ASSET_CLASSES = %w[+ alternative_investment commodity equity fixed_income liquidity real_estate+ ].freeze++ ASSET_SUB_CLASSES = %w[+ bond cash collectible commodity cryptocurrency etf loan mutual_fund+ precious_metal private_equity real_estate stock+ ].freeze++ CLASSIFICATION_SOURCES = %w[provider manual ai default].freeze++ CONSTRAINTS = {+ "chk_securities_asset_class" => [ "asset_class", ASSET_CLASSES ],+ "chk_securities_asset_sub_class" => [ "asset_sub_class", ASSET_SUB_CLASSES ],+ "chk_securities_classification_source" => [ "classification_source", CLASSIFICATION_SOURCES ]+ }.freeze++ # Every step is written to be safe to run again. Without a DDL transaction+ # each statement commits on its own while schema_migrations stays unwritten,+ # so a process killed part-way leaves some columns created and the migration+ # still pending -- and the next run would die on "column already exists"+ # rather than finishing the job.+ def up+ add_column :securities, :asset_class, :string, if_not_exists: true+ add_column :securities, :asset_sub_class, :string, if_not_exists: true+ # `sector` and `industry` are free text, and deliberately so: they come from+ # providers, each with its own vocabulary (EODHD's `General.Sector` is not+ # GICS, and no two agree on wording). There is no constraint and no+ # `inclusion` validation on purpose -- adding one would reject a value a+ # provider legitimately returns and break ingestion for that provider.+ # Normalisation, if it ever happens, belongs above these columns.+ add_column :securities, :sector, :string, if_not_exists: true+ add_column :securities, :industry, :string, if_not_exists: true+ # `region` is NOT the same case, and grouping it with the two above would+ # be wrong. No provider supplies a region: they supply a country, and the+ # region is derived from it against a list this application owns. So its+ # vocabulary is closed, and a model-level `inclusion` validation over that+ # list is the right enforcement -- there is no provider value for it to+ # reject. It is left unconstrained in the database only because the list+ # lives in configuration, where widening it should not need a migration.+ add_column :securities, :region, :string, if_not_exists: true+ add_column :securities, :classification_source, :string, if_not_exists: true+ # A boolean with a constant default is a catalog-only change on+ # PostgreSQL 11+; existing rows are not rewritten. The project ships+ # PostgreSQL 16 (compose.example.yml, .devcontainer) and the existing+ # loans migrations rely on the same behaviour.+ #+ # `null: false` means an explicit nil write raises rather than falling back+ # to the default -- `update_column(:classification_locked, nil)` and any+ # other ORM bypass included. That is intended: "locked" is a yes or no, and+ # a third state would leave a later writer guessing whether it may replace+ # a user's classification.+ add_column :securities, :classification_locked, :boolean, null: false, default: false, if_not_exists: true++ CONSTRAINTS.each do |name, (column, values)|+ # `if_not_exists: true` is not sufficient here, and this is the reason.+ # It resolves through `CheckConstraintDefinition#defined_for?`, which+ # compares `validate` alongside the name, so it only recognises an+ # existing constraint that is *also* NOT VALID. One this migration has+ # already created AND validated is not matched, the ADD is issued a+ # second time, and PostgreSQL raises `PG::DuplicateObject`. That is a+ # reachable state: `disable_ddl_transaction!` leaves a window between+ # `validate_check_constraint` below and the schema_migrations write, and+ # a process killed inside it leaves exactly this shape. Matching on the+ # name alone is what "safe to run again" actually requires.+ next if check_constraint_exists?(:securities, name: name)++ # connection.quote rather than "'#{v}'": the values are this migration's+ # own constants today, so hand-quoting is safe by inspection -- but the+ # next person adding a taxonomy value should not have to know that the+ # safety comes from where the string came from.+ quoted = values.map { |value| connection.quote(value) }.join(", ")+ add_check_constraint :securities, "#{column} IN (#{quoted})",+ name: name, validate: false+ end++ CONSTRAINTS.each_key do |name|+ validate_check_constraint :securities, name: name+ end+ end++ def down+ CONSTRAINTS.each_key do |name|+ remove_check_constraint :securities, name: name, if_exists: true+ end++ %i[+ classification_locked classification_source region industry sector+ asset_sub_class asset_class+ ].each { |column| remove_column :securities, column, if_exists: true }+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 1460237126..ef1b0e3ddf 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -2248,6 +2248,10 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_22_230000) doendcreate_table "securities", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.string "asset_class"+ t.string "asset_sub_class"+ t.boolean "classification_locked", default: false, null: false+ t.string "classification_source"t.string "country_code"t.datetime "created_at", null: falset.string "exchange_acronym"@@ -2256,6 +2260,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_22_230000) dot.datetime "failed_fetch_at"t.integer "failed_fetch_count", default: 0, null: falset.date "first_provider_price_on"+ t.string "industry"t.string "kind", default: "standard", null: falset.datetime "last_health_check_at"t.string "logo_url"@@ -2263,6 +2268,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_22_230000) dot.boolean "offline", default: false, null: falset.string "offline_reason"t.string "price_provider"+ t.string "region"+ t.string "sector"t.string "ticker", null: falset.datetime "updated_at", null: falset.string "website_url"@@ -2272,6 +2279,9 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_22_230000) dot.index ["kind"], name: "index_securities_on_kind"t.index ["price_provider", "offline_reason"], name: "index_securities_on_price_provider_and_offline_reason"t.index ["price_provider"], name: "index_securities_on_price_provider"+ t.check_constraint "asset_class::text = ANY (ARRAY['alternative_investment'::character varying::text, 'commodity'::character varying::text, 'equity'::character varying::text, 'fixed_income'::character varying::text, 'liquidity'::character varying::text, 'real_estate'::character varying::text])", name: "chk_securities_asset_class"+ t.check_constraint "asset_sub_class::text = ANY (ARRAY['bond'::character varying::text, 'cash'::character varying::text, 'collectible'::character varying::text, 'commodity'::character varying::text, 'cryptocurrency'::character varying::text, 'etf'::character varying::text, 'loan'::character varying::text, 'mutual_fund'::character varying::text, 'precious_metal'::character varying::text, 'private_equity'::character varying::text, 'real_estate'::character varying::text, 'stock'::character varying::text])", name: "chk_securities_asset_sub_class"+ t.check_constraint "classification_source::text = ANY (ARRAY['provider'::character varying::text, 'manual'::character varying::text, 'ai'::character varying::text, 'default'::character varying::text])", name: "chk_securities_classification_source"t.check_constraint "kind::text = ANY (ARRAY['standard'::character varying::text, 'cash'::character varying::text])", name: "chk_securities_kind"enddiff --git a/test/migrations/add_classification_to_securities_migration_test.rb b/test/migrations/add_classification_to_securities_migration_test.rbnew file mode 100644index 0000000000..95cd346d6b--- /dev/null+++ b/test/migrations/add_classification_to_securities_migration_test.rb@@ -0,0 +1,99 @@+# frozen_string_literal: true++require "test_helper"+require Rails.root.join("db/migrate/20260916120000_add_classification_to_securities")++# The migration declares `disable_ddl_transaction!`, so each statement commits on+# its own while the schema_migrations row stays unwritten. A process killed+# part-way therefore leaves the schema partly changed and the migration still+# pending, and the next run has to finish the job rather than die on something it+# already did. These tests pin that promise for the two states such a run can+# find a check constraint in: already validated, and added but NOT VALID.+class AddClassificationToSecuritiesMigrationTest < ActiveSupport::TestCase+ CONSTRAINT = "chk_securities_asset_class"++ # The state every existing installation is already in: the columns and the+ # constraints are present and validated, because this migration -- or the+ # fork's earlier copy of it, which this one replaces -- has run to completion.+ #+ # `if_not_exists: true` does NOT cover this. It resolves through+ # `CheckConstraintDefinition#defined_for?`, which compares `validate` next to+ # the name, so it only recognises a constraint that is also NOT VALID. Against+ # a validated one it reports "absent", the ADD is issued a second time and+ # PostgreSQL raises PG::DuplicateObject. Without the name-only guard in `up`,+ # this test fails with exactly that error.+ test "re-running over validated constraints does not raise" do+ assert constraint_validated?, "fixture schema should already carry the validated constraint"++ assert_nothing_raised { run_migration }++ assert constraint_validated?, "the constraint must still be present and validated afterwards"+ end++ # The other half of the boundary, and the case the original `if_not_exists:`+ # was aimed at: killed after the ADD but before the VALIDATE. The re-run must+ # not duplicate the constraint, and must finish the validation it skipped.+ test "re-running over an unvalidated constraint validates it rather than duplicating it" do+ # The predicate an interrupted run would actually have left: the migration+ # adds the full list NOT VALID and validates it afterwards, so a process+ # killed in between leaves THIS, not some narrower constraint. Built from+ # the migration's own constant so the two cannot drift.+ values = AddClassificationToSecurities::ASSET_CLASSES.map { |v| "'#{v}'" }.join(", ")+ # IF EXISTS: this test builds the interrupted state from scratch, so it+ # must not depend on the constraint being there when it starts. Without it+ # a run against a database where the migration has not been applied fails+ # on the setup rather than on the thing under test.+ connection.execute("ALTER TABLE securities DROP CONSTRAINT IF EXISTS #{CONSTRAINT}")+ connection.execute(+ "ALTER TABLE securities ADD CONSTRAINT #{CONSTRAINT} " \+ "CHECK (asset_class IN (#{values})) NOT VALID"+ )+ assert_not constraint_validated?, "precondition: the constraint is present but NOT VALID"+ before = constraint_expression++ assert_nothing_raised { run_migration }++ assert_equal 1, constraint_count, "the re-run must not add a second constraint under the same name"+ assert constraint_validated?, "the re-run must validate the constraint it found unvalidated"+ # `NOT VALID` is the one thing that MUST change -- validating is what+ # removes it -- so the predicate is compared with that marker stripped.+ assert_equal before.sub(/ NOT VALID\z/, ""), constraint_expression,+ "the re-run replaced the predicate instead of validating the one it found"+ AddClassificationToSecurities::ASSET_CLASSES.each do |value|+ assert_includes constraint_expression, "'#{value}'",+ "#{value} is missing from the constraint the re-run left behind"+ end+ end++ private+ def connection = ActiveRecord::Base.connection++ def constraint_count+ connection.select_value(+ "SELECT count(*) FROM pg_constraint WHERE conname = #{connection.quote(CONSTRAINT)}"+ )+ end++ def constraint_validated?+ connection.select_value(+ "SELECT convalidated FROM pg_constraint WHERE conname = #{connection.quote(CONSTRAINT)}"+ )+ end++ # The rendered predicate, read back from the catalog. Counting the+ # constraints and checking they are validated does not say WHICH constraint+ # survived: a re-run that dropped the full list and re-added a narrower one+ # would pass both of those (raised by cubic on #190).+ def constraint_expression+ connection.select_value(+ "SELECT pg_get_constraintdef(oid) FROM pg_constraint " \+ "WHERE conname = #{connection.quote(CONSTRAINT)}"+ )+ end++ def run_migration+ ActiveRecord::Migration.suppress_messages do+ AddClassificationToSecurities.new.up+ end+ end+enddiff --git a/test/models/security_test.rb b/test/models/security_test.rbindex 0fe528d3f0..740dc6de57 100644--- a/test/models/security_test.rb+++ b/test/models/security_test.rb@@ -5,6 +5,127 @@ class SecurityTest < ActiveSupport::TestCase# 1. Original ticker# 2. Duplicate ticker on a different exchange (different market price)# 3. "Offline" version of the same ticker (for users not connected to a provider)+ test "classification columns accept nil and every value in the taxonomy" do+ security = securities(:aapl)++ assert_nil security.asset_class+ assert_not security.classification_locked?++ Security::ASSET_CLASSES.each do |asset_class|+ security.asset_class = asset_class+ assert security.valid?, "#{asset_class} should be a valid asset_class"+ end+ Security::ASSET_SUB_CLASSES.each do |sub_class|+ security.asset_sub_class = sub_class+ assert security.valid?, "#{sub_class} should be a valid asset_sub_class"+ end+ Security::CLASSIFICATION_SOURCES.each do |source|+ security.classification_source = source+ assert security.valid?, "#{source} should be a valid classification_source"+ end+ end++ test "classification columns reject values outside the taxonomy" do+ security = securities(:aapl)++ security.asset_class = "stocks"+ assert_not security.valid?+ assert_includes security.errors[:asset_class], "is not included in the list"++ security.asset_class = nil+ security.asset_sub_class = "share"+ assert_not security.valid?++ security.asset_sub_class = nil+ security.classification_source = "guess"+ assert_not security.valid?+ end++ test "the database enforces the classification taxonomy independently of the model" do+ security = securities(:aapl)++ # update_column skips validations, so only the check constraint can object.+ # Each attempt runs in its own savepoint: a failed statement aborts the+ # surrounding transaction, which is the one the test fixture runs in.+ { asset_class: "stocks", asset_sub_class: "share", classification_source: "guess" }.each do |column, value|+ assert_raises(ActiveRecord::StatementInvalid, "#{column}=#{value} should violate the check constraint") do+ Security.transaction(requires_new: true) { security.update_column(column, value) }+ end+ end++ security.update_columns(asset_class: "equity", asset_sub_class: "stock", classification_source: "manual", classification_locked: true)+ assert_equal %w[equity stock manual], security.reload.values_at(:asset_class, :asset_sub_class, :classification_source)+ assert security.classification_locked?+ end++ # The counterpart to the two taxonomy tests: sector and industry are free text+ # ON PURPOSE, because each provider ships its own vocabulary and a constraint+ # would reject a value one of them legitimately returns. That is an absence --+ # of a constraint and of an `inclusion` rule -- and an absence is exactly what+ # no other test here would notice being filled in. Adding either one later+ # breaks classification ingestion for a provider, and the first symptom would+ # be in the provider, not in this file.+ #+ # `region` is deliberately NOT asserted here; see the test below for why the+ # two cases are not the same.+ #+ # Values chosen to be outside any plausible taxonomy and to carry the+ # punctuation real provider strings do, since a normalising validation would+ # pass a tidy string and fail on these.+ test "sector and industry are unconstrained free text" do+ security = securities(:aapl)+ free_text = "Consumer Electronics & Durables -- EMEA/APAC (ex-Japan), 2nd tier"++ security.assign_attributes(sector: free_text, industry: free_text)+ assert security.valid?, "no inclusion validation belongs on these"++ # And no check constraint either, which the model's validations cannot show.+ security.update_columns(sector: free_text, industry: free_text)+ assert_equal [ free_text ] * 2, security.reload.values_at(:sector, :industry)+ end++ # `region` is unconstrained at the DATABASE level for a different reason than+ # sector and industry, and this test protects only that reason. No provider+ # supplies a region -- they supply a country, and the region is derived from+ # it against a list this application owns -- so the vocabulary is closed and+ # a model-level `inclusion` validation is the right enforcement once+ # something writes it. The list belongs in configuration, where widening it+ # should not need a migration, which is why the constraint is not in the+ # schema.+ #+ # So this asserts the missing CHECK constraint and says nothing about model+ # validation: an `inclusion` rule arriving on `region` later is the intended+ # end state, not a regression, and a test that failed when it landed would be+ # asserting the opposite of the design.+ test "region carries no database check constraint so the list can live in configuration" do+ security = securities(:aapl)+ outside_any_list = "Trans-Kuiper Belt, 2nd tier"++ security.update_columns(region: outside_any_list)+ assert_equal outside_any_list, security.reload.region++ assert_nil Security.connection.check_constraints(:securities).find { |c| c.expression.include?("region") },+ "a check constraint on region would move the list out of configuration and into a migration"+ end++ test "the model taxonomy and the database constraint list the same values" do+ constraints = Security.connection.check_constraints(:securities).index_by(&:name)++ {+ "chk_securities_asset_class" => Security::ASSET_CLASSES,+ "chk_securities_asset_sub_class" => Security::ASSET_SUB_CLASSES,+ "chk_securities_classification_source" => Security::CLASSIFICATION_SOURCES+ }.each do |name, values|+ expression = constraints.fetch(name).expression+ # Capture whole quoted literals rather than `[a-z_]+`: a value carrying a+ # digit or a hyphen would not match that class at all, so it would vanish+ # from the scan and fail this test even though the constant and the+ # constraint agree -- a spurious failure every time the taxonomy grows.+ assert_equal values.sort, expression.scan(/'([^']+)'/).flatten.sort,+ "#{name} and the model constant have drifted apart"+ end+ end+test "can have duplicate tickers if exchange is different" dooriginal = Security.create!(ticker: "TEST", exchange_operating_mic: "XNAS")duplicate = Security.create!(ticker: "TEST", exchange_operating_mic: "CBOE")