Enforce one tagging per tag and object with a unique index

Merged
JA
14d ago
+508-13

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= and tags= 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, so food|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 taggings against writers, deletes duplicates keeping the oldest row of each (tag_id, COALESCE(taggable_type, ''), taggable_id), then adds index_taggings_unique on 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 NULL taggable_types as different keys and would let that duplicate through. The expression works on any supported PostgreSQL version; NULLS NOT DISTINCT would need 15 or later. The dedupe partitions on the same expression, so what it keeps is exactly what the index accepts.
  • Tag#replace_and_destroy! skips transactions that already carry the replacement. It does this with NOT EXISTS, comparing COALESCE(taggable_type, '') so it matches how the index keys the type. Their old row is removed by the existing destroy!.
  • Transaction#tag_ids= and #tags= collapse repeats before handing off to Rails. Repeats are compared by their cast ids, so ABC… and abc… count as the same tag, as they do in the database, but the original values are what Rails receives: a malformed id still raises RecordNotFound, as on main, 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.
  • QifImport split lines and Family::DataImporter#mapped_tag_ids drop 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 at main's 2026_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 (by created_at, then id). 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 MODE before the dedupe and holds it to the end of the migration's transaction. Writes to taggings wait for the few moments the migration runs, so no new duplicate can land between the delete and the index. DELETE alone takes only ROW 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
  • 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 on main's writer, so they pin that this PR keeps its behaviour.
  • test/models/tag_test.rb and test/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.rb and test/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 DISTINCT index, 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= without uniq
  • tag_ids= with uniq but no cast (re-run at the current head with the new case-variant test)
  • tags= without uniq
  • each importer without uniq
  • tag_ids= casting before uniq and passing the cast ids on (the reviewed version): the malformed-id model and API tests fail
  • tag_ids= keying the dedupe on the cast alone, without the raw-value fallback: a malformed tag id after a blank one still raises fails

Results:

  • bin/rails test on b1da2c313: 10,829 runs, 46,184 assertions, 0 failures, 0 errors, 33 skips (run with TZ=UTC; without it, one holdings test that uses Date.today fails when the local date is a day ahead of UTC).
  • bin/rails test on c8fe0562f (after the rebase onto main ff51e7e2d): 11,804 runs, 54,430 assertions, 0 failures, 0 errors, 34 skips.
  • bin/rails test on 8dc65486a (the malformed-id review fix, on main a3bb5d991): 11,847 runs, 54,601 assertions, 0 failures, 0 errors, 34 skips. bin/rubocop on the changed files and bin/brakeman: clean.
  • bin/rubocop: 2879 files inspected, no offenses detected
  • bundle exec erb_lint: not run, no ERB changed
  • npm run lint: not run, no JavaScript changed
  • bin/brakeman: 0 security warnings

Blast radius

Every writer of taggings, and what keeps it off the index:

WriterWhy 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_tagsall 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 linesmapped_tag_ids returns unique ids
Rule::ActionExecutor::SetTransactionTagsalready 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 :taggingsno 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 current main. One conflict, in test/models/transaction_test.rb, where main and this PR both added tests at the same place; both are kept. Full suite: 13,076 runs, 0 failures.
  • cd88f4d8e: merged current main (2250ba801). Clean merge; this PR's own diff is unchanged (git patch-id --stable matches). 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 RecordNotFound and leaves the tags unchanged.
  • Concurrent writers racing to add the same new tag to the same object now get RecordNotUnique instead of a silent duplicate.

Migration

  • 20261007120000_add_unique_index_to_taggings locks taggings while deduping and holds the lock until the index exists.
  • The index folds a missing taggable_type to '' with COALESCE, 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.