Warn on the rule form when a similar rule already exists
Closes jaysbeekay/sure#703
Upstream issue: we-promise/sure#5176
Upstream PR: we-promise/sure#5528 (same branch, same commit), in native stack we-promise/sure#5529
Stacked on jaysbeekay/sure#830 (up/rule-health-overlaps, the overlaps slice split out of jaysbeekay/sure#796), whose Rule::Health text comparison similar_to reuses; the diff below is this branch's own commits.
Summary
Saving a rule never compared it with the family's other rules, so a duplicate, or a rule that a rule above already beats on every match, saved with a success message. The web form now checks before saving. If another rule is a duplicate, has the same conditions with different actions, or names the same or contained text and sets a field this one sets, the form re-renders (422) with a warning listing each similar rule: its run position and name (an edit link), its first condition and action, how many transactions both match, and, when it runs first, that it wins on those. "Save anyway" resubmits with confirm_similar and saves as today.
What changed
Rule::Health#similar_to(rule)(app/models/rule/health.rb): compares one rule, saved, new or carrying the form's unsaved changes, with the family's other rules, active and inactive.- Returns
Similar(rule, position, wins, shared_count). When either rule is switched off,winsandshared_countare nil: it doesn't run on sync, so there's no winner and no count. A new rule counts as on, since it is saved inactive and switched on at the confirm step. winsneeds the similar rule to run first where the saved rule will land, and to compete with it: set a field it sets, or stop the rules below. A new rule runs last (Rule#assign_next_position); a rule joining or leaving a group lands right after that group's other rules (Rule::Layout#place_after_group!), so that place is used; otherwise the stored order.shared_countis the number of distinct transaction ids both match, or nil (no line) when either match query fails. The form's rule is matched through an unsaved copy without the conditions marked for destruction, which#matching_scopewould otherwise still apply.- A rule is never similar to itself (
other.id == rule.id). - Only similar rules' matches are queried:
matches_ofis now lazy per rule (the health page still reads every rule). The text and field caches are keyed by object identity, since the form's copy of an edited rule shares the stored rule's id. Signatures skip conditions and actions marked for destruction. A merchant the family's rules don't name is looked up on its own.
- Returns
RulesController#create/#update: beforesave_rule, unlessconfirm_similaris present, run the check on a valid rule and render:new/:editwith 422 when it finds anything. An invalid rule shows its errors as before.rules/_similar_rules.html.erb(aDS::Alertwith Cancel and aSave anywaysubmit namedconfirm_similar), rendered at the top ofrules/_form;RulesHelper#rule_summary, whose action label (#rule_action_label) the rules list now uses too;rule_health_referencenow takes the position; locale strings.- The form's re-render keeps what was submitted (Codex threads):
rule/conditions/_condition_groupreads a group's sub-conditions before its template builds a blank one onto it, so a new AND/OR group keeps its conditions (it rendered only persisted ones);rule/conditions/_conditionandrule/actions/_actionwrite_destroyfrommarked_for_destruction?and hide that row, so a removed condition or action stays removed;Rule::Health#moving_groupalso takes a group typed into the form, which is built unsaved and leavesrule_group_idunchanged.render_invalid_rulerenders the same partials, so an invalid rule keeps a new group's conditions too.
Deliberately left out
- Blocking, merging, reordering; warnings in the assistant, the importers or Quick Categorize;
Transaction::Ruleable#eligible_for_category_rule?.
Blast radius: who else creates or updates rules, and what do they pass?
| Writer | Path | Effect |
|---|---|---|
Rules form (incl. the transaction page's prompt, which only pre-fills new) | RulesController#create / #update | new check |
Rule.create_from_grouping (Quick Categorize) | model | unchanged; test: still creates an identical duplicate |
Assistant::Function::CreateRule / UpdateRule | model | unchanged; test: CreateRule still creates an identical duplicate |
RuleImport and the rule CSV/JSON importers, Rule.replace_merchant_references! | model | unchanged (no validation added) |
Active toggle on the rules list (PATCH with active only) | #update | not checked: a request with active alone skips the check (test: switching a duplicate off saves it) |
Edit flow: the form resubmits the rule's own conditions; the rule is skipped by id, and a test edits a rule without changes and saves with no notice.
Tests
test/controllers/rules_controller_test.rb (15 new), test/models/rule/health_test.rb (2 new), test/models/rule_test.rb (1), test/models/assistant/function/create_rule_test.rb (1). Before = parent commit (#796): the 7 positive controller tests fail (Rule.count changed by 1 / no [data-similar-rule]), the 2 Health tests error (undefined method 'similar_to'); the negatives and the unchanged-writer tests pass before and after.
| Test | Kind | Before | After |
|---|---|---|---|
| create identical to existing → 422, names it (with its condition and action), count unchanged | positive | fails | passes |
same with confirm_similar=1 → saved, +1, redirects to confirm | positive | passes | passes |
| unrelated rule → saved, no notice | negative | passes | passes |
| same conditions, Groceries vs Dining out → 422; same conditions, tags only (no shared field) → 422 with no "wins" | positive | fails | passes |
update until it repeats another → 422 naming it, value unchanged; with confirm_similar → saved | positive (update path) | fails | passes |
| inactive duplicate → "(inactive)", no wins, no count; same rule active → wins + "1 transaction" | boundary | fails | passes |
| edit: similar rule directly above → wins; moved directly below → listed, no wins | boundary | fails | passes |
| new rule placed in a group above the similar rule → listed, no wins (without the group → wins) | boundary | fails | passes |
| shared count: existing matches 3, new (OR group) matches 3, shared "2 transactions" | count | fails | passes |
| edit without changes → saves, no notice | negative (self) | passes | passes |
| "woolworths metro" → Dining under "woolworths" → Groceries → "1 transaction" | positive | fails | passes |
| narrower text, no shared transactions, sets tags → saved | negative | passes | passes |
| switching a duplicate rule off from the list saves it (review) | toggle | fails (422) | passes |
| an inactive rule edited to repeat another: no wins, no count (review) | boundary | fails (wins shown) | passes |
| a similar stop rule above that shares no field wins (review) | stop half | passes; dropping other.stop_processing? fails it | passes |
| the rules list labels a rule's action as the notice does (review) | list label | passes | passes |
Rule::Health: unsaved rule with an AND group vs active + inactive rules | model | errors | passes |
Rule::Health: a condition marked for destruction is left out | model | errors | passes |
Rule::Health: a rule whose match query fails gets no shared count, not 0 | model | errors | passes |
| the warning keeps a new group's conditions in the form, and renders no extra blank one (Codex) | re-render | fails (no sub-condition inputs) | passes |
| an invalid rule keeps a new group's conditions in the form | re-render, render_invalid_rule | fails | passes |
| the warning keeps a removed condition and action removed (Codex) | re-render | fails (0 hidden rows with _destroy=true) | passes |
| a similar rule wins over a rule moved into a new group typed into the form; not moved: no wins (Codex) | boundary | fails (no wins) | passes |
create_from_grouping still creates an identical duplicate | unchanged writer | passes | passes |
assistant CreateRule still creates an identical duplicate | unchanged writer | passes | passes |
Mutations (applied to the container copy only)
| Mutation | Caught by |
|---|---|
check only in #create | update test, position test |
| a rule similar to itself | edit-without-changes |
| inactive treated as active | inactive test |
| inactive skipped | inactive test |
| always "wins" | position test |
| group placement ignored | group test |
| "wins" without a shared field or stop | same-conditions tags half |
| failed match read as an empty set | failed-query model test |
| shared = the other rule's total | both shared-count tests |
| same conditions must also have the same actions | same-conditions, tags-only half |
| text overlap ignores the field | narrower-no-share negative |
confirm_similar ignored | save-anyway and update tests |
| unsaved copy keeps destroyed conditions | marked-for-destruction model test |
| group renders only persisted sub-conditions (as before) | both new-group re-render tests |
| group reads its sub-conditions after the template is built | both new-group re-render tests |
condition or action _destroy written as false, or its row not hidden (4 mutations) | removed condition and action |
moving_group ignores an unsaved group | new-group test |
Screenshots
Before (up/rule-health): the prompt-prefilled rule "Woolworths Metro → Dining out" saves and goes straight to the Apply confirmation. After: the form shows the warning naming "#2 Woolworths", light, dark and mobile.
| Before | After | |
|---|---|---|
| Light | ![]() | ![]() |
| Dark | ![]() | ![]() |
| Mobile | ![]() | ![]() |
Validation
- At 0bd681c5c (re-render fixes, restacked on #830):
rules_controller_test.rb,health_test.rb,rule_test.rb,create_rule_test.rb163 runs, 0 failures;test/system/rules_test.rb13 runs, 1 failure (keeps a rule with long text inside a phone-width screen), which fails the same way on the previous head 7971b92a9 in this container and passes in CI. Full suite: CI on this head. rules_controller_test.rb,test/models/rule,rule_test.rb,test/models/assistant/function: 965 runs, 0 failures, 0 errors (before the last model test was added;health_test.rbnow 23 runs, 0 failures).- Full
bin/rails teston this head: 16463 runs, 105060 assertions, 0 failures, 8 errors, 9 skips. All 8 errors are environmental:ReleaseNotesWorkflowTest,Errno::ENOENT: node. bin/rubocop,erb_linton the changed files: no offenses.bin/brakeman: 0 warnings.- Size: 155 non-test lines added, 19 removed.
- Independent review before commit: 6 points. Fixed: "wins" ignored where a rule placed in a group lands; "wins" was claimed for rules that set no common field; a failed match query read as "0 transactions". Declined with reason: a name condition and a merchant condition compared as the same text is what the issue asks for (its problem statement is
merchant = <id>vsname contains <merchant name>); cost with a very short pattern grows with the rules that share the text, bounded by the similar rules as the plan states; the merchant-name lookup takes the form's id unscoped, as the health page's does, and reveals only whether a rule is listed. - No API or migration changes. Checked against upstream
AGENTS.md(DS::Alert / DS::Button, tokens,t()throughout). - Checked against upstream AGENTS.md (blob 1a5dbebd, 2026-11-17): no deviations.
Refresh (2026-11-22)
- Merged
up/rule-health-overlaps(with current upstreammain) in; no conflicts. New commit e42b0ee14: a request that submits onlyactiveorapply_immediatelyskips the similar-rule check (upstream's newtest_update_saves_apply_immediatelygot a 422 without it); a form edit that also sendsapply_immediatelyis still checked (new test, failed before with a 422). - Full
bin/rails testat b040cebb6: 18213 runs, 0 failures, 8 errors (environmentalReleaseNotesWorkflowTest, nonode).





