Add an asset classification schema to securities
Upstream: we-promise/sure#3608 (part of we-promise/sure#3494) — same branch, same commit. This is the fork pre-flight.
Summary
Fork pre-flight for an upstream PR. The branch targets mirror/upstream-main, so CI here exercises exactly what we-promise/sure would receive.
Drop 0.6 of #119, and the first piece of the foundations sent upstream. Deliberately the smallest one: schema only, no reader, no dependency on any other part of the drop.
securities can say what a holding is called and where it trades, but not what it is. Allocation by asset class, sub-class, sector or region has nowhere to read from, and a provider that returns a sector has nowhere to put it — Provider::SecurityConcept::SecurityInfo is Data.define(:symbol, :name, :links, :logo_url, :description, :kind, :exchange_operating_mic), with no field for one.
Adds asset_class, asset_sub_class, sector, industry, region, classification_source, classification_locked.
Why it is this small
Nothing reads or writes these columns yet. Every security stays unclassified and the migration carries no data risk. It is separated from the code that populates it so the taxonomy can be argued about on its own terms, before anything depends on it — if the six-class / twelve-sub-class scheme is wrong, this is the cheapest possible moment to say so.
Design notes
- 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 taxonomy is the six-class / twelve-sub-class scheme other portfolio trackers use, so a provider payload or a CSV maps onto it without a translation table.
classification_sourcemirrorsHolding's cost-basis provenance, so a later writer knows whether it may replace an existing value.classification_lockedis the user's veto over every source.- Constraints are added
NOT VALIDthen validated, which on PostgreSQL is two short locks rather than a full-table scan under an exclusive lock. That needsdisable_ddl_transaction!, andvalidate_check_constrainthas no inverse, so the migration is explicitup/downrather thanchange.
Files changed
5 files, +383.
| File | Change |
|---|---|
db/migrate/20260916120000_add_classification_to_securities.rb | New — 7 columns, 3 check constraints, and the re-run guard below |
app/models/security.rb | ASSET_CLASSES, ASSET_SUB_CLASSES, CLASSIFICATION_SOURCES + three allow_nil inclusion validations |
test/models/security_test.rb | 6 tests |
test/migrations/add_classification_to_securities_migration_test.rb | New — the two states a re-run can find a constraint in |
db/schema.rb | Regenerated |
The re-run guard, which is the substantive change since the Formal review
The constraint loop originally relied on add_check_constraint(..., validate: false, if_not_exists: true), and the header claimed every step was safe to run again. It was not.
if_not_exists: resolves through CheckConstraintDefinition#defined_for?, which compares validate alongside the name, so it only matches a constraint that is also NOT VALID. Against one that is present and validated it reports "absent", the ADD is issued a second time, and PostgreSQL raises PG::DuplicateObject.
That state is reachable here rather than theoretical: up validates each constraint in a second loop, and with disable_ddl_transaction! those commit one at a time while the schema_migrations row is written only after the last. A process killed in that window leaves the migration pending with all three constraints present and validated — exactly the shape the guard failed to match.
The loop now skips on the name alone, which matches a constraint whatever its validation state. The trailing validate loop is a no-op on an already-validated constraint, so the case the original did handle is not traded away.
Two things corrected while porting
- Migration timestamp. In the fork it is
20260909000000, which is earlier than upstream's current schema version (2026_09_14_200000). Anyone already migrated past that date would have received an out-of-order migration. Renamed to20260916120000and the schema version bumped to match. - Migration Rails version. The fork's copy declared
ActiveRecord::Migration[7.2];AGENTS.mdasks for the current version and the schema declares[8.1], so it is now[8.1]. (Upstream is inconsistent here — 3 of the last 5 migrations use[7.2]— so this follows the written rule rather than the majority practice.)
On the Rails version specifically, since CodeRabbit asked for [7.2] on this PR: Gemfile.lock is rails (8.1.3.1) and db/schema.rb declares ActiveRecord::Schema[8.1], so [8.1] is the current version and the written rule is the one to follow. The fork's own .cursor/rules line that pinned [7.2] was itself stale, which is what produced the friction; #175 fixes that rule so it tracks whatever db/schema.rb declares rather than naming a version that goes out of date.
The port was done hunk by hunk rather than by copying files: app/models/security.rb has four hunks of fork divergence, two of which are unrelated Brandfetch changes. Verified that no Brandfetch line appears in this diff.
Validation
| Check | Result |
|---|---|
bin/rails test test/models/security_test.rb | 31 runs, 95 assertions, 0 failures at the current head — 6 of those tests are this PR's, the rest are upstream's |
bin/rails test test/migrations/add_classification_to_securities_migration_test.rb | 2 runs, 7 assertions, 0 failures. Against the loop as it was, both error with PG::DuplicateObject |
bin/rubocop (changed files) | no offenses |
bin/brakeman --no-pager | Security Warnings: 0 |
bin/rails test (full suite) | 9,362 runs, 37,746 assertions, 0 failures, 1 environmental error (below), re-measured at the current head |
The migration itself, which CI never runs
Both CI workflows prepare their databases with db:schema:load, so a green test_unit proves db/schema.rb — not db/migrate/20260916120000_add_classification_to_securities.rb. The regenerated schema is evidence that up ran once; nothing showed down had ever run, and down is the half a self-hoster executes on a rollback.
Run on a scratch database, so no existing database was touched:
| Step | Result |
|---|---|
db:schema:load | baseline |
db:migrate:down VERSION=20260916120000 | all 3 constraints and all 7 columns removed, in order, no errors |
db:migrate | all 7 columns re-added, all 3 constraints re-added and re-validated |
db:schema:dump vs db/schema.rb | the securities classification surface matches |
One correction to that last row. The constraints are equivalent on both paths, but they do not render identically: after db:migrate on PostgreSQL 16.13 the three check constraints dump as ARRAY['provider'::character varying, ...]::text[], while after db:schema:load of the committed file they dump as ARRAY['provider'::character varying::text, ...]. The committed db/schema.rb carries the second form, so a dump taken straight after db:migrate differs on those three lines. It is a rendering difference in the dumper, not a difference in the constraint — pg_get_constraintdef and the drift test agree on both — and an earlier reply in thread 4034181541 attributed the flip to connection.quote, which the sweep's sandbox contradicts: connection.quote("equity") is 'equity', so that SQL is byte-identical to the interpolated literal. The next contributor who runs db:migrate and commits will carry a three-line diff on these constraints either way.
So the round trip leaves the table exactly as db/schema.rb describes it, and the down path is exercised rather than assumed.
The one error is environmental, not this change. RecurringTransaction::PipelineTest#test_run_with_lock!_refuses_to_stack_on_a_held_family_lock fails with PG::ConnectionBad: … FATAL: password authentication failed for user "root". It reproduces identically on a clean checkout of origin/main with none of this change applied, and is tracked as jaysbeekay/sure#168: config/database.yml sets user: where Rails expects username:, so configuration_hash[:username] is nil and the test's second PG.connect falls back to the OS user. CI supplies credentials differently and does not hit it. Nothing in this diff touches that file or that test.
The DB-level test (the database enforces the classification taxonomy independently of the model) is the one that proves the migration actually applied rather than the model validations passing on their own. The fourth test asserts the model's constant lists and the database constraint contain the same values, so the two cannot drift.
Three questions the draft pass raised, answered
All three are settled in comments rather than by changing behaviour, because in each case the current behaviour is the intended one and what was missing was the reason.
Why the taxonomy is declared twice. ASSET_CLASSES and friends live in both Security and the migration. That is deliberate, not a copy-paste: a migration has to produce the same schema whenever it runs — on a fresh install today, on a self-hosted instance upgrading in a year — and a constant borrowed from a model would produce a different constraint once the model's list changed. It is the usual reason migrations do not reference application code. The cost is that growing the taxonomy is a two-file edit, and the drift test is what stops the halves separating silently: it reads the rendered constraint back out of the catalog and compares it to the constants, so moving one without the other fails rather than ships.
Why sector and industry are free text, and why region is a different case. sector and industry carry provider vocabulary and no two providers agree on it — EODHD's General.Sector is not GICS. No constraint and no inclusion validation on either, 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 those columns rather than in them.
region is not that case, and grouping it with them would be wrong — the migration's header says so, and this section used to contradict it. 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 there is no provider value for a validation to reject. The enforcement is therefore model-level inclusion over that list, and it lands with the drop that derives the value rather than here, where nothing writes the column yet. It is left unconstrained in the database for one reason only: the list lives in configuration, and widening it should not require a migration.
What null: false on classification_locked costs. An explicit nil write raises rather than falling back to the default, update_column(:classification_locked, nil) included. 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.
Not in this PR
No reader, no writer, no UI, no provider ingestion, no SecurityInfo field. Those are drop 3 (#122). This is the schema they will need.
- Add seven asset-classification columns to
securities. - Add model taxonomies and optional inclusion validations.
- Add database constraints for enumerated classification values.
- Add tests for validation, database enforcement, taxonomy drift, and free-text fields.
- Regenerate
db/schema.rb.
| Contributing author | Lines added | Lines removed |
|---|---|---|
| jaysbeekay | 222 | 1 |