Warn on the rule form when a similar rule already exists

JA
14d ago
+651-44

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, wins and shared_count are 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.
    • wins needs 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_count is 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_scope would otherwise still apply.
    • A rule is never similar to itself (other.id == rule.id).
    • Only similar rules' matches are queried: matches_of is 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.
  • RulesController#create / #update: before save_rule, unless confirm_similar is present, run the check on a valid rule and render :new / :edit with 422 when it finds anything. An invalid rule shows its errors as before.
  • rules/_similar_rules.html.erb (a DS::Alert with Cancel and a Save anyway submit named confirm_similar), rendered at the top of rules/_form; RulesHelper#rule_summary, whose action label (#rule_action_label) the rules list now uses too; rule_health_reference now takes the position; locale strings.
  • The form's re-render keeps what was submitted (Codex threads): rule/conditions/_condition_group reads 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/_condition and rule/actions/_action write _destroy from marked_for_destruction? and hide that row, so a removed condition or action stays removed; Rule::Health#moving_group also takes a group typed into the form, which is built unsaved and leaves rule_group_id unchanged. render_invalid_rule renders 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?

WriterPathEffect
Rules form (incl. the transaction page's prompt, which only pre-fills new)RulesController#create / #updatenew check
Rule.create_from_grouping (Quick Categorize)modelunchanged; test: still creates an identical duplicate
Assistant::Function::CreateRule / UpdateRulemodelunchanged; test: CreateRule still creates an identical duplicate
RuleImport and the rule CSV/JSON importers, Rule.replace_merchant_references!modelunchanged (no validation added)
Active toggle on the rules list (PATCH with active only)#updatenot 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.

TestKindBeforeAfter
create identical to existing → 422, names it (with its condition and action), count unchangedpositivefailspasses
same with confirm_similar=1 → saved, +1, redirects to confirmpositivepassespasses
unrelated rule → saved, no noticenegativepassespasses
same conditions, Groceries vs Dining out → 422; same conditions, tags only (no shared field) → 422 with no "wins"positivefailspasses
update until it repeats another → 422 naming it, value unchanged; with confirm_similar → savedpositive (update path)failspasses
inactive duplicate → "(inactive)", no wins, no count; same rule active → wins + "1 transaction"boundaryfailspasses
edit: similar rule directly above → wins; moved directly below → listed, no winsboundaryfailspasses
new rule placed in a group above the similar rule → listed, no wins (without the group → wins)boundaryfailspasses
shared count: existing matches 3, new (OR group) matches 3, shared "2 transactions"countfailspasses
edit without changes → saves, no noticenegative (self)passespasses
"woolworths metro" → Dining under "woolworths" → Groceries → "1 transaction"positivefailspasses
narrower text, no shared transactions, sets tags → savednegativepassespasses
switching a duplicate rule off from the list saves it (review)togglefails (422)passes
an inactive rule edited to repeat another: no wins, no count (review)boundaryfails (wins shown)passes
a similar stop rule above that shares no field wins (review)stop halfpasses; dropping other.stop_processing? fails itpasses
the rules list labels a rule's action as the notice does (review)list labelpassespasses
Rule::Health: unsaved rule with an AND group vs active + inactive rulesmodelerrorspasses
Rule::Health: a condition marked for destruction is left outmodelerrorspasses
Rule::Health: a rule whose match query fails gets no shared count, not 0modelerrorspasses
the warning keeps a new group's conditions in the form, and renders no extra blank one (Codex)re-renderfails (no sub-condition inputs)passes
an invalid rule keeps a new group's conditions in the formre-render, render_invalid_rulefailspasses
the warning keeps a removed condition and action removed (Codex)re-renderfails (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)boundaryfails (no wins)passes
create_from_grouping still creates an identical duplicateunchanged writerpassespasses
assistant CreateRule still creates an identical duplicateunchanged writerpassespasses

Mutations (applied to the container copy only)

MutationCaught by
check only in #createupdate test, position test
a rule similar to itselfedit-without-changes
inactive treated as activeinactive test
inactive skippedinactive test
always "wins"position test
group placement ignoredgroup test
"wins" without a shared field or stopsame-conditions tags half
failed match read as an empty setfailed-query model test
shared = the other rule's totalboth shared-count tests
same conditions must also have the same actionssame-conditions, tags-only half
text overlap ignores the fieldnarrower-no-share negative
confirm_similar ignoredsave-anyway and update tests
unsaved copy keeps destroyed conditionsmarked-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 builtboth 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 groupnew-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.

BeforeAfter
Light703-before-light-after-submit703-after-light-after-submit
Dark703-before-dark-after-submit703-after-dark-after-submit
Mobile703-before-light-mobile-after-submit703-after-light-mobile-after-submit

Validation

  • At 0bd681c5c (re-render fixes, restacked on #830): rules_controller_test.rb, health_test.rb, rule_test.rb, create_rule_test.rb 163 runs, 0 failures; test/system/rules_test.rb 13 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.rb now 23 runs, 0 failures).
  • Full bin/rails test on this head: 16463 runs, 105060 assertions, 0 failures, 8 errors, 9 skips. All 8 errors are environmental: ReleaseNotesWorkflowTest, Errno::ENOENT: node.
  • bin/rubocop, erb_lint on 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> vs name 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 upstream main) in; no conflicts. New commit e42b0ee14: a request that submits only active or apply_immediately skips the similar-rule check (upstream's new test_update_saves_apply_immediately got a 422 without it); a form edit that also sends apply_immediately is still checked (new test, failed before with a 422).
  • Full bin/rails test at b040cebb6: 18213 runs, 0 failures, 8 errors (environmental ReleaseNotesWorkflowTest, no node).