Enforce one tagging per tag and object with a unique index

Merged
JA
15d ago
+477-14

Moved 2026-11-18. we-promise/sure#4081 is closed and replaced by we-promise/sure#5293, opened from a we-promise/sure branch at the bottom of the taggings stack. This pre-flight was merged into the mirror earlier. The fork's up/taggings-unique-index is now at 344d48a97, the same commits as we-promise/sure#5293: this PR's seven commits replayed onto current upstream main with no code conflicts. Full unit suite on 65154bb17 on beastpc: 17,169 runs, 0 failures (the 8 errors are ReleaseNotesWorkflowTest, no node in the image). Rubocop is clean.

Part of #122 (drop 3, upstream slice U3). Upstream pre-flight for we-promise/sure#3494 (coordination issue).

Upstream PR: we-promise/sure#4081 (draft, opened 2026-10-09). How the two relate: same commits. On 2026-10-13 up/taggings-unique-index was rebased onto upstream main ff51e7e2d (owner-approved force push; previous head b1da2c313). It is five commits, head c8fe0562f. The only conflicts were the db/schema.rb version line and new upstream tests at the end of test/models/transaction_test.rb.

Upstream review fix, 2026-10-14: e61813a5b and 8dc65486a answer Codex 4266483059 (a malformed tag id was cast to a blank and dropped, so an all-malformed API list cleared the tags). Head 8dc65486a, on mirror/upstream-main a3bb5d991 (merged at 5257bdee7). Full bin/rails test on 8dc65486a: 11,847 runs, 54,601 assertions, 0 failures, 0 errors, 34 skips.

Fork note: fork main already has this index from #207 (index_taggings_unique). This migration has a different class name and uses if_not_exists, so the next upstream-into-fork sync runs it as a no-op.

The upstream description follows, as posted.


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.

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 ff51e7e2d): 11,804 runs, 54,430 assertions, 0 failures, 0 errors, 34 skips. Rubocop clean, Brakeman 0 warnings.
  • 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.