Enforce one tagging per tag and object with a unique index
Summary
Nothing in the database stopped the same tag being stored twice on one transaction, and several ordinary paths did exactly that. This adds a unique index on taggings, cleans up the duplicates already there, and changes every writer so none of them can now hit the index on a normal request.
Part of #3494
Fork pre-flight: jaysbeekay/sure#349 (same branch, same commit).
Updated 2026-11-05. Upstream main (529d7de76) is merged in. No change to this PR's own files; #4410 merges this head down. Full suite on 9b3142ff7: 14,687 runs, 0 failures, 0 errors.
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 CodeRabbit
- Bug Fixes
- Duplicate tags are consolidated during imports and transaction updates, including repeated tags in split transactions.
- Replacing a tag no longer creates duplicate associations when an item already has the replacement tag.
- Existing duplicate tag associations are cleaned up, while distinct assignments are preserved and duplicate associations are prevented going forward.
- Invalid tag IDs no longer replace a transaction’s existing tags, and blank tag IDs are ignored.