Enforce one tagging per tag and object with a unique index
Part of #3494
Replaces #4081, which was opened from a fork branch. Its CodeRabbit history stays there (two threads, both resolved).
What: adds a unique index on taggings over (tag_id, COALESCE(taggable_type, ''), taggable_id), which is partial: only rows with a taggable. A migration first removes the duplicates already there, keeping the oldest row of each, under a lock against writers. Every writer that could store a tag twice now stores it once: Tag#replace_and_destroy! (merging tags), Transaction#tag_ids=/#tags=, and the QIF and Sure data importers.
Why: nothing in the database stopped one tag being stored twice on one transaction, and merging tags or importing a file with a repeated tag did exactly that.
Start reading: db/migrate/20261007120000_add_unique_index_to_taggings.rb, then Transaction#tag_ids= and Tag#replace_and_destroy!.
Key tests:
test/migrations/add_unique_index_to_taggings_migration_test.rb: "removes duplicate taggings and keeps the oldest"test/migrations/add_unique_index_to_taggings_migration_test.rb: "treats a missing taggable_type and an empty one as the same key"tag_test.rb: "replace and destroy moves the tag and tags nothing twice"transaction_test.rb: "assigning a repeated tag stores it once"transaction_test.rb: "a malformed tag id still raises and leaves the tags in place"
Behaviour change: the migration deletes duplicate taggings, which are rows that only repeat another. A repeated tag in a form, the API or an import is now stored once instead of twice. A malformed tag id still raises, as on main.
Stack: bottom of the taggings stack (1 of 2), based on main. Next: letting a family tag a security.
Size: +80 / −3 outside tests (7 commits), 477 lines with tests.
Re-cut onto current main: the seven commits are replayed with no code conflicts. In transactions_controller_test.rb, transaction_test.rb and tag_test.rb, main had added tests at the same places, and this PR's tests now follow main's.
Migration notes: 20261007120000_add_unique_index_to_taggings. It is older than main's latest (20261116120000) and kept as it was on #4081. Rails records migrations by version, so it still runs on a database that lacks it. schema.rb gains the index and its version stays at 2026_11_16_120000. It is reversible: down drops the index; deleted duplicates are not restored.
Fork pre-flight: jaysbeekay/sure#349 (merged into the fork's mirror). It carried the same changes as earlier commits, and the fork's up/taggings-unique-index is at this head.
Full description and evidence, carried from #4081
Commit SHAs, "Updated" notes and merge notes below refer to the branch as it was on #4081, before this re-cut.
What changed
How a duplicate got in today:
- Merging tags.
Tag#replace_and_destroy!re-pointed every tagging of the deleted tag, including those on transactions that already had the replacement. Each of those ended up with the replacement twice. - Assigning tags with a repeat.
tag_ids=andtags=on a has_many :through insert one row per element, repeats included. The CSV, Mint and QIF importers pass a row's tags through as given, sofood|food, or two names mapped to the same tag, stored it twice. The API and bulk edit pass submitted ids straight in as well. - The QIF split and Sure data importers create one tagging per listed tag, so a repeated tag in the file was stored twice. An export taken from an affected database lists the tag id twice.
The fix:
- Migration: locks
taggingsagainst writers, deletes duplicates keeping the oldest row of each(tag_id, COALESCE(taggable_type, ''), taggable_id), then addsindex_taggings_uniqueon that expression.- It is partial (
WHERE taggable_id IS NOT NULL) because both taggable columns are nullable, and a row with no taggable isn't a tagging of anything. - It indexes
COALESCE(taggable_type, ''), because by default Postgres treats two NULLtaggable_types as different keys and would let that duplicate through. The expression works on any supported PostgreSQL version;NULLS NOT DISTINCTwould need 15 or later. The dedupe partitions on the same expression, so what it keeps is exactly what the index accepts.
- It is partial (
Tag#replace_and_destroy!skips transactions that already carry the replacement. It does this withNOT EXISTS, comparingCOALESCE(taggable_type, '')so it matches how the index keys the type. Their old row is removed by the existingdestroy!.Transaction#tag_ids=and#tags=collapse repeats before handing off to Rails. Repeats are compared by their cast ids, soABC…andabc…count as the same tag, as they do in the database, but the original values are what Rails receives: a malformed id still raisesRecordNotFound, as onmain, rather than being cast to a blank that Rails would drop (which would clear the tags). This one change covers the transaction form, the API, bulk edit, the assistant functions, transfers and the CSV/Mint/QIF importers.QifImportsplit lines andFamily::DataImporter#mapped_tag_idsdrop repeated tags before creating taggings.
Demo data
No demo data needed: nothing new is shown, and the demo generator doesn't create taggings.
Migration notes
20261007120000_add_unique_index_to_taggings, current Rails migration version (8.1). The schema version stays atmain's2026_10_11_151000, because this migration's version is earlier, and the only schema change is the new index line (an expression index,"tag_id, COALESCE(taggable_type, ''::character varying), taggable_id"). A test checks the migration builds exactly that index.- Rows deleted: for each
(tag_id, taggable_type, taggable_id)with a taggable id set, every row but the oldest (bycreated_at, thenid). The rows are identical apart from their ids and timestamps, so nothing a user can see is lost: the transaction keeps the tag, once. Rows with no taggable id are left alone. - Locking: it takes
LOCK TABLE taggings IN SHARE ROW EXCLUSIVE MODEbefore the dedupe and holds it to the end of the migration's transaction. Writes totaggingswait for the few moments the migration runs, so no new duplicate can land between the delete and the index.DELETEalone takes onlyROW EXCLUSIVE, which would let inserts through. Measured on PostgreSQL 16 with the migration's exact SQL: about 0.14 s for 100k taggings and about 1.5 s for 1M (with 1% duplicates). The lock blocks writes only; reads carry on. - Any supported PostgreSQL version. No
NULLS NOT DISTINCT, so nothing here needs PostgreSQL 15. Compose, the devcontainer and CI all ship 16 or later. - Rollback drops the index. The deleted duplicates aren't restored, since they held nothing the kept row doesn't.
add_index ... if_not_exists: true, so the migration can be re-run safely.
Verification
Tests were written first and failed for the expected reason before the fix. Ten failed because the duplicate was stored (Expected: ["KEEP"] Actual: ["KEEP", "KEEP"], Expected: 2 Actual: 3, RecordNotUnique expected but nothing was raised), and the migration test failed because the migration didn't exist yet.
New and changed tests:
test/migrations/add_unique_index_to_taggings_migration_test.rb- removes duplicates and keeps the oldest. The newer duplicate is given a lower id, so keeping
MIN(id)would fail. - leaves distinct taggings alone
- removes duplicates with a NULL
taggable_type, and the index then refuses another - leaves rows with no taggable alone
- refuses a duplicate afterwards
- can be run again
- removes duplicates and keeps the oldest. The newer duplicate is given a lower id, so keeping
test/models/tagging_test.rb: the index refuses a duplicate, including one with a NULL type. The same tag on different transactions is still fine.test/models/transaction_test.rb: a repeated tag id (including an upper-case copy), a repeated tag, and a new transaction built with a repeated tag are each stored once. A malformed tag id still raises and leaves the tags in place, on its own, beside a valid id, and after a blank one; a blank id is still ignored. These pass onmain's writer, so they pin that this PR keeps its behaviour.test/models/tag_test.rbandtest/controllers/tag/deletions_controller_test.rb:- a merge moves the tag where it's needed and duplicates nothing
- a NULL-type row the replacement already has is skipped
- The old controller test expected the replacement to gain one transaction per tagged transaction. Its fixture transaction already carries both tags, so it was counting the duplicate this PR removes, and it was rewritten.
test/models/family/data_importer_test.rb,test/models/qif_import_test.rbandtest/controllers/api/v1/transactions_controller_test.rb: a repeated tag on the import and API paths is stored once, and an API update with a malformed tag id is refused with the tags unchanged.
Mutation check: 17 deliberate breakages, each caught by a test; the last two were run at 8dc65486a for the malformed-id review fix. Twelve were run at 3905558e1. The three marked (new), and the re-run cast check, were run at the head before that fix. They covered:
- dropping the dedupe
- keeping the lowest id instead of the oldest
- the previous
NULLS NOT DISTINCTindex, under which a missing and an empty type are different keys (new) - the merge comparing the type with
IS NOT DISTINCT FROM(new) - running the dedupe without the table lock (new)
- skipping NULL types in the dedupe
- deduping rows with no taggable
- a non-partial index
- the merge without its skip
- the merge comparing the type with
= tag_ids=withoutuniqtag_ids=withuniqbut no cast (re-run at the current head with the new case-variant test)tags=withoutuniq- each importer without
uniq tag_ids=casting beforeuniqand passing the cast ids on (the reviewed version): the malformed-id model and API tests failtag_ids=keying the dedupe on the cast alone, without the raw-value fallback:a malformed tag id after a blank one still raisesfails
Results:
bin/rails testonb1da2c313: 10,829 runs, 46,184 assertions, 0 failures, 0 errors, 33 skips (run withTZ=UTC; without it, one holdings test that usesDate.todayfails when the local date is a day ahead of UTC).bin/rails testonc8fe0562f(after the rebase ontomainff51e7e2d): 11,804 runs, 54,430 assertions, 0 failures, 0 errors, 34 skips.bin/rails teston8dc65486a(the malformed-id review fix, onmaina3bb5d991): 11,847 runs, 54,601 assertions, 0 failures, 0 errors, 34 skips.bin/rubocopon the changed files andbin/brakeman: clean.bin/rubocop: 2879 files inspected, no offenses detectedbundle exec erb_lint: not run, no ERB changednpm run lint: not run, no JavaScript changedbin/brakeman: 0 security warnings
Blast radius
Every writer of taggings, and what keeps it off the index:
| Writer | Why it can't hit the index now |
|---|---|
Tag#replace_and_destroy! (tag deletion with replacement) | skips transactions that already carry the replacement |
TransactionsController update and duplicate, Transactions::BulkUpdatesController via Entry.bulk_update!, Api::V1::TransactionsController create/update, Assistant::Function::CreateTransaction/UpdateTransaction, Transfer::Creator, TransfersController#update_tags | all assign through Transaction#tag_ids=, which now collapses repeats |
TransactionImport, MintImport, QifImport parent rows (Transaction.new(tags:), tags =) | go through Transaction#tags=, which now collapses repeats, including on the import!(recursive: true) path |
QifImport#import_split_lines! | row[:tags].uniq |
Family::DataImporter transactions and split lines | mapped_tag_ids returns unique ids |
Rule::ActionExecutor::SetTransactionTags | already passes (existing + selected).uniq under a row lock |
Transaction#toggle_tag! | already checks for the tag under a row lock before creating it |
accepts_nested_attributes_for :taggings | no controller permits taggings_attributes, so no request reaches it |
What it doesn't cover: two requests that add the same new tag to the same transaction at the same moment. Each computes its insert from its own snapshot, so the second now gets RecordNotUnique where it used to create a silent duplicate. That's the constraint doing its job, and it needs a genuine race (the tag picker's toggle already locks the row). I left it out to keep this PR to the index.
Since review
6f4f5175e: merged currentmain. One conflict, intest/models/transaction_test.rb, wheremainand this PR both added tests at the same place; both are kept. Full suite: 13,076 runs, 0 failures.cd88f4d8e: merged currentmain(2250ba801). Clean merge; this PR's own diff is unchanged (git patch-id --stablematches). Full suite: 13,190 runs, 0 failures, 0 errors.
Summary by cubic
Enforces a unique index on taggings so a tag can be applied to an object only once, and makes every writer that could store a tag twice store it once.
- A migration deletes duplicate taggings, keeping the oldest of each, under a lock against writers, then creates the index.
Tag#replace_and_destroy!(tag merging),Transaction#tag_ids=/#tags=, and the QIF and data importers now collapse repeats.Tag#replace_and_destroy!resets its taggings before destroying, so it no longer deletes rows it just moved when the association was loaded first.- A malformed tag id still raises
RecordNotFoundand leaves the tags unchanged. - Concurrent writers racing to add the same new tag to the same object now get
RecordNotUniqueinstead of a silent duplicate.
Migration
20261007120000_add_unique_index_to_taggingslockstaggingswhile deduping and holds the lock until the index exists.- The index folds a missing
taggable_typeto''withCOALESCE, so it works on any supported PostgreSQL version. - Rollback drops the index; the deleted duplicates are not restored.
- Tests pin that the lock runs inside the migration's transaction and that a missing index is read without aborting it.
Summary by CodeRabbit
- Bug Fixes
- Prevented duplicate tags when assigning tags or importing transactions, including split transactions.
- Replacing a tag no longer creates duplicate associations on transactions that already have its replacement.
- Duplicate tag associations are cleaned up during the upgrade, and future duplicates are prevented.
- Invalid tag IDs no longer change a transaction’s existing tags.