Add a Rule health page for duplicate, conflicting and shadowed rules

JA
9d ago
+796-1

Part of #5175

Fork pre-flight: jaysbeekay/sure#796 (same branch, same commit).

Stack: #5525 Claims extraction → #5526 Rule health page → #5527 overlaps section → #5528 save-time warning on the rule form (stack #5529). This PR adds the page; #5527 adds the Overlaps section and closes the issue.

Summary

Nothing in the app compared one rule with another, so duplicates and contradictions piled up, and a rule that never takes effect looked as live as any other. Settings > Rules now links a read-only Rule health page. It loads its report in a lazy Turbo frame, so the rules page itself is unaffected, and lists, each rule with its run position and an edit link:

  1. Duplicates: same conditions, effective date, actions and stop-processing setting.
  2. Conflicts: same conditions setting a field to different values, with the active rule that wins and why (run order, or it stops the rules below). With none active: "none runs on sync".
  3. Shadowed: active rules that match transactions but change nothing, because every match is stopped above or every field they set is already claimed above, naming those rules.
  4. Match nothing today, and Couldn't be checked (a rule whose match query failed, e.g. a pattern that timed out).

What changed

  • New app/models/rule/health.rb (Rule::Health.new(family)):
    • Condition signature, normalised as Rule::ConditionFilter matches: whitespace collapsed for text types; case folded only for like, not_like, starts_with, ends_with (ILIKE); = and != keep case; a matches_regex value compared exactly as written; an additional-detail condition keeps the key before its first = as written (it is looked up exactly) and normalises only the value. Order doesn't count; an AND group reads as its conditions listed flat.
    • Dry run over the active rules in order, recording claims and stops with Rule::Runner::Claims (from #5525), so it cannot drift from the real run. Each action is judged as Rule#apply does: it skips transactions claimed above for any field it sets. Tags claim nothing; an action that can't be resolved counts as an effect (the real run fails such a rule rather than changing nothing).
    • Held verdicts. Matches are read before any rule runs, but the real run re-reads them after the rules above apply. A rule whose conditions read a field an active rule above may change (name, merchant, category, transfer kind, tags) gets no shadowed or match-nothing verdict; the doubt passes to rules reading a field it sets, and no rule is reported shadowed by it.
    • Each rule's matches are read in their own savepoint; any error marks that rule failed and the report carries on.
  • RulesController#health + GET /rules/health: the full page renders the shell; a Turbo-Frame request renders the report. Added to require_non_guest!'s except list, like index, since it writes nothing.
  • rules/health.html.erb, rules/_health_report.html.erb (one DS::Section per group), RulesHelper#rule_health_reference (edit link for members, plain text for guests) and #rule_health_attributes, a "Rule health" DS::Link on rules/index, and config/locales/views/rules/en.yml.

Size: 365 non-test lines added (health.rb 240), after moving the overlaps section to #5527. That is over the ~300 guide, and it stays one PR on purpose: the held-verdict fix (35 lines) has to sit with the shadowed and match-nothing verdicts it guards, and moving conflicts or the dry run into another slice would split one model across PRs with no reviewable seam.

Deliberately left out

  • Bulk delete or merge, persisted results, a background job, and the save-time warning (#5528, #5176).
  • Attribute locks: the dry run ignores them, as ApplyAllRulesJob does. A rule whose transactions are all locked can read as live here.
  • The overlaps section: #5527.
  • A split action above changes which transactions every rule below sees (the split parent leaves the scope); the dry run does not model it.
  • A conflict winner ignores an unrelated stop rule higher up that stops both rules; the page then still names the first active one.

Blast radius: who else hits this line, and what do they pass?

  • Rule::Runner is untouched in this commit; Rule::Health only reads Rule#matching_scope, Rule::Action#claimed_attributes / #reserves_claimed_attributes? and Rule::Runner::Claims, and writes nothing.
  • require_non_guest! now excepts health as well as index; every other action still requires a member. The report reads Current.family.rules only.
  • rules/index's page actions gain one link, shown when the family has rules, guests included (the page is read-only).
  • Siblings: Rule#active_rules_above and Rule#affected_resource_count also read match sets; left alone.

Tests

test/models/rule/health_test.rb (new, 22 tests, each building its own rules and transactions) and test/controllers/rules_controller_test.rb (4 new). Before = parent commit (#5525): every model test fails with NameError: uninitialized constant Rule::Health, every controller test with undefined method 'health_rules_url'.

TestKind
like "woolworths" vs like " WOOLWORTHS " are duplicatespositive
an AND group reads like the same conditions flatpositive
different effective dates are not duplicatesnegative
= "Uber" vs = "uber" are not duplicatesnegative
matches_regex \d+ vs \D+, and ^Wool worths vs ^Wool worths, are not duplicatesnegative
same conditions, Groceries vs Dining: higher active wins; higher made inactive, lower winspositive + boundary
below a STOP rule matching the same transactions: shadowed (:stopped, by the stop rule); STOP switched off: not shadoweddelta
field claimed above on every match: shadowed (:claimed, by that rule)positive
tags-only rule below: not shadowednegative
match nothing todaypositive
regex timeout: reported failed, rest of report returnspositive
a query that raises in PostgreSQL (merchant id "not-a-uuid"): failed, rules after it still checkedsavepoint
an unresolvable action: not shadowednegative
stop rule vs same rule without stop: not duplicates (before: grouped)negative
additional detail like MCC=ABC vs MCC=abc conflict, mcc=abc does not (before: all three grouped)positive + negative
rename above, then a rule matched by name: neither it nor the rule it claimed for is shadowed, the renamed-to rule is not "match nothing"; rename switched off: both verdicts return (before: shadowed listed)delta
a rule that may match more after a rename (hardware renamed into its text) is not shadowed; rename off: shadoweddelta
doubt passes down: renamed-to rule sets a category, a category-condition rule sets a tag, a tag-condition rule; none "match nothing"; rename off: all threedelta
a rule above that matches nothing leaves the verdict below standingnegative
cross-check after a rename: every shadowed and match-nothing verdict agrees with a real Rule::Runner runequivalence
claimed rule counts only matches no stop rule above took (before: 2, after: 1)delta
controller: report renders the conflicts and shadowed sectionscontroller
cross-check: shadowed set equals the rules a real Rule::Runner run records with queued > 0 and modified 0 (2 rules)equivalence
health page renders a lazy framecontroller
report lists the family's duplicates, never another family's rule idtenancy
a guest reads page and report, without edit linksguest

Mutations (applied to the container copy only)

MutationCaught by
fold case for every operator= keeps case
never fold casecontains duplicates
normalise a pattern like textpattern compared as written
don't flatten an AND groupAND group
ignore the effective datedifferent effective dates
winner ignores activeconflict winner
claims not consultedcross-check (+ claimed shadow errors)
stops not consultedstop shadow
claim-free actions count as no effecttags-only + cross-check
a match failure abortstimeout test
savepoint removedPostgreSQL-error test
unresolvable action counts as no effectunresolvable action
claims recorded on nothingcross-check
every family's rulesother family's rule id
guest gets edit linksguest test
guest blockedguest test
duplicates key without stop_processingstop vs no-stop
additional detail key folded, or the detail branch removed, or its value not foldedadditional detail conflict
a rule's own doubt ignoredmay match more after a rename
a shadow by a doubtful rule keptrename, and the real-run cross-check
match nothing ignores doubtrename, doubt passes down, real-run cross-check
doubt not passed down from a rule with no matches todaydoubt passes down
every rule above counts as changing its fieldsrule above that matches nothing
tags not counted as a changed fielddoubt passes down

Screenshots

Before (up/rule-runner-claims): rules list without a link, light and dark. After: the rules list with the "Rule health" link, and the Rule health page, light, dark and mobile.

BeforeAfter
Rules list, light702-before-light-rules-index702-after-light-rules-index
Rules list, dark702-before-dark-rules-index702-after-dark-rules-index
Rule health, light—702-after-light-health
Rule health, dark—702-after-dark-health
Rule health, mobile—702-after-light-health-mobile

Validation

  • Full bin/rails test at a53e59371: 18172 runs, 112369 assertions, 0 failures, 8 errors, 9 skips. All 8 errors are environmental: ReleaseNotesWorkflowTest, Errno::ENOENT: node.
  • 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 main (9e419e7be) in the same container.
  • bin/rubocop and erb_lint on the changed files: no offenses. bin/brakeman: 0 warnings.
  • Checked against upstream AGENTS.md (blob 1a5dbebd): no deviations.
  • No API or migration changes.

Summary by cubic

Adds a Rule health page that compares one rule with another, so duplicates, contradictions, and shadowed rules stop looking as live as any other. Settings > Rules now links a read-only page, loaded in a lazy Turbo frame, that groups the findings:

  • Duplicates: same conditions, effective date, actions, and stop-processing setting, with conditions normalized the way they match (text whitespace collapsed, case folded only for the like operators, patterns compared as written, detail-condition values keeping their inner spacing).
  • Conflicts: same conditions setting a field to different values, naming the active rule that wins and why (run order, or it stops the rules below).
  • Shadowed: active rules that match transactions but change nothing because every match is stopped above or every field they set is already claimed above, naming those rules.
  • Match nothing today (active rules only), and Couldn't be checked for rules whose match query failed.

The report dry-runs the active rules with Rule::Runner::Claims, so it cannot drift from the real run. A rule whose conditions read a field a rule above may change (renamed above, then matched by name) gets no shadowed or match-nothing verdict; that doubt passes to rules reading the set field, and to rules below a transfer or split whose counterpart or child transactions the action may create. A transfer or split that matches nothing changes nothing. Each rule's matches run in their own savepoint, so one failing rule is reported while the rest of the report still returns.

GET /rules/health writes nothing and joins index on require_non_guest!'s exception list; guests read the page without edit links, members get links to each rule's form.

Summary by CodeRabbit

  • New Features
    • Added a Rule Health report that highlights duplicate and conflicting rules, rules that may be shadowed or match nothing, and checks that could not be completed.
    • Added a link to the report on the rules page when rules are present. The report includes related rules, explanations, and match counts where available.
    • Guests can view the report; editing links are available to signed-in users.