Let a family tag a security with its own tags

Merged
JA
14d ago
+404-1

Part of #3494

Replaces #4410, which was opened from a fork branch. Its CodeRabbit history stays there (four threads, all resolved).

What: makes Security a taggable, so a household can group securities with its own tags ("pension", "speculative"). It has one writer, Security#set_tags_for(family, tag_ids), which replaces that family's tags on the security and leaves every other family's alone. It reads the family's tags under a share lock.
Why: classification columns live on a row every family holding the instrument shares, so they can't hold a grouping that means something to one household.
Start reading: Security#set_tags_for and #tags_for in app/models/security.rb.
Key tests (test/models/security/tags_test.rb, 15 tests):

  • "set_tags_for leaves another family's tags on the security alone"
  • "a tag belonging to another family is not attached"
  • "the security has no family-blind tag writer"
  • "a family's data reset removes its security tags and keeps another family's"

Behaviour change: none for users. This is the model only, with no UI and no migration (taggings is already polymorphic).

Stack: top of the taggings stack (2 of 2), on #5293 (taggings unique index). GitHub shows only this slice's diff.
Size: +50 / −0 outside tests (4 commits), 313 lines with tests.
Re-cut onto current main: the three model commits replay cleanly. #4410 also carried three commits that refused malformed tag ids in the transactions API (5cedcc868, 6a2aab984, 95e78308b). main's transactions API now does this itself (malformed_tag_ids? and unknown_tag_ids?), and #4410's own merge with main had already taken main's controller. Those commits are therefore folded into one test-only commit, Pin the transactions API's refusal of malformed tag ids. Its tests run against main's controller and are the same tests #4410 carried. The final tree equals #4410's own changes applied to the new #5293.
Fork pre-flight: jaysbeekay/sure#537. Same commits: the fork's up/security-taggable is at this head.

Full description and evidence, carried from #4410

Commit SHAs, "Updated" notes and merge notes below refer to the branch as it was on #4410, before this re-cut.

Summary

The classification columns on securities (asset class, sub-class, sector, region) live on a row that every family holding the instrument shares, so they cannot hold a grouping that means something to one household only, such as "pension", "kids' fund" or "speculative". tags already carries family_id and taggings is already polymorphic, but only Transaction is a taggable.

This makes Security a taggable too, with one writer that keeps the edit inside the family that made it.

What changed

app/models/security.rb

  • has_many :taggings, as: :taggable, dependent: :destroy and has_many :tags, through: :taggings.
  • Security#set_tags_for(family, tag_ids): replaces family's tags on the security and leaves every other family's alone.

app/models/tag.rb

  • has_many :securities, through: :taggings, source: :taggable, source_type: "Security", mirroring the existing transactions.

Tenancy: why the writer is not security.tags = ...

A security is global, a tag is per family. security.tags therefore spans every family that has tagged the instrument, and the obvious writers are wrong in two ways:

security.tags = family.tags.where(id: tag_ids)  # deletes other families' taggings
security.tag_ids = tag_ids                      # attaches a tag the family does not own

The first destroys another household's data. The second discloses: attaching a tag this family does not own would put that tag's name on an instrument other families hold. set_tags_for resolves ids only through family.tags (an id from another family, or an unknown id, is ignored), removes only taggings whose tag belongs to family, and creates only the missing ones. Each failure mode has its own test.

Reading one family's tags is security.tags.where(family: family). Nothing reads security.tags yet; the association comment says which form to use.

with_lock serialises edits to one security. With #4081's unique index, two concurrent saves of the same tag would otherwise fail one of them on the index rather than both succeed. The lock reloads the record, so an association the caller had already loaded does not keep a removed tag.

Left out: any UI or controller action (held for the UI phase), tagging a Holding (a holding row is a per-date snapshot, so a tag on it would be lost on the next materialisation), per-account tagging of one instrument, allocation by tag, and export/import of security tags (Family::DataExporter exports transaction tag ids only; unchanged).

Demo data

No change to demo data or seeds.

Migration notes

None. No migration and no schema change: taggings.taggable_type is a free string, and #4081's index already keys on it.

Verification

  • New tests: test/models/security/tags_test.rb (11 tests): attach and reach from the tag, another family's tag not attached, another family's tags survive an edit, an empty selection clears only this family's, a tag left out is removed and the kept tagging row is untouched, a repeated id keeps the one existing row, already loaded associations reflect the write, destroying a tag, destroying a security, merging two tags on the same security, and a family data reset.
  • Fail-first. Against #4081's head without this change: 11 runs, 11 errors, each NoMethodError on set_tags_for, taggings or tags for Security.
  • Mutations, each applied alone to the committed change, test/models/security/tags_test.rb run, then reverted:
MutationCaught by
Naive self.tags = family.tags.where(id: wanted)"leaves another family's tags on the security alone", "an empty selection clears this family's tags but not another family's"
Ids resolved through Tag instead of family.tags"a tag belonging to another family is not attached"
mine taken from Tag (removal not scoped to the family)"leaves another family's tags...", "an empty selection clears..."
No removal of deselected tags"a tag left out of the selection is removed...", "an empty selection clears...", "already loaded associations..."
Remove all of the family's taggings and recreate"a tag left out ... the kept one is untouched", "re-submitting the same tag keeps the one existing tagging"
Create every wanted id, no check for existingthe same two tests (RecordNotUnique from #4081's index)
Bare transaction instead of with_lock"already loaded associations reflect the write without a reload"
Drop dependent: :destroy on Security#taggings"destroying a security removes its taggings and keeps the tags"
Drop Tag#securities"set_tags_for attaches the family's tag and the tag reaches the security"

The merge and reset tests pin existing code (Tag#replace_and_destroy! from #4081, Family::FinancialDataReset) against the new taggable type; they are regression coverage, not fail-first evidence for this change. The concurrency half of with_lock is not exercised by a test.

  • Neighbouring suites (test/models/security/tags_test.rb, security_test.rb, tag_test.rb, tagging_test.rb): 50 runs, 0 failures.
  • Full bin/rails test on this branch (Ruby 3.4.9): 11858 runs, 54621 assertions, 0 failures, 0 errors, 34 skips, at 6cf322131.
  • bin/rubocop on the changed files: no offenses. bin/brakeman: no warnings. No ERB changed.
  • Merges cleanly with current main (git merge-tree).

Blast radius

Who else hits these lines, and what do they pass? set_tags_for is new and has no caller yet. The associations add a second taggable type to the readers of taggings:

  • Tag#replace_and_destroy! moves taggings with no type filter, so merging two tags now moves security taggings too. That is intended. With #4081, a security already carrying both tags keeps one tagging instead of gaining a duplicate; tested.
  • Tag has_many :taggings, dependent: :destroy, and Family has_many :tags, dependent: :destroy, so deleting a tag or a family removes its security taggings.
  • Family::FinancialDataReset scopes taggings as Tagging.where(tag_id: tag_scope.select(:id)), so a reset removes that family's security taggings and leaves other families' on the same security; tested.
  • Demo::DataCleaner (Security.destroy_all) and lib/tasks/securities.rake (security.destroy!) now also remove the security's taggings, through dependent: :destroy.

What else reads what this changes the reading of? grep -rn "taggings\|Tagging\|taggable" app/ lib/:

  • Rule::ConditionFilter::TransactionTag filters taggable_type: "Transaction"; unaffected.
  • ReportsController joins taggings from the transaction side; unaffected.
  • Family::DataImporter and QifImport create taggings on transactions only; unaffected.
  • Family::DataExporter reads transaction.tags / tag_ids; security tags are not exported (left out above).

Summary by cubic

Makes Security a taggable so a family can group securities with its own tags, such as "pension" or "speculative". No UI, no migration, and no behavior change for users.

  • Adds Security#set_tags_for(family, tag_ids), which replaces only that family's tags on the shared security row, leaves every other family's alone, and refuses an unsaved security.
  • Reads the wanted tags under a share lock inside the security row lock so a concurrent tag deletion cannot fail the insert.
  • Reads a family's tags via Security#tags_for(family); the family-blind tags, tags=, tag_ids and tag_ids= accessors are deliberately absent.
  • Adds Tag#securities as a read-only query, so set_tags_for stays the only tag writer.
  • Adds Security#move_taggings_to! and calls it from securities:deduplicate, so deduplicating securities moves a duplicate's tags onto the canonical row instead of destroying them.
  • Pins the transactions API's refusal of malformed tag ids (validation failed, tags unchanged) with tests against main's existing controller behavior.

Summary by CodeRabbit

  • Bug Fixes
    • Security tags are managed separately for each family, so updating or clearing one family’s tags preserves tags belonging to others.
    • Invalid tag identifiers and unsupported tag input formats are rejected without changing existing tags or creating transaction entries.
    • Supported clearing inputs continue to remove the selected family’s tags.
    • Tags are preserved when duplicate securities are consolidated, including when the canonical security already has the same tag.