Stop emailing old matches after an email rule's conditions widen

Merged
JA
2mo ago
+623-11

Fixes #389.

Upstream issue: we-promise/sure#4102
Upstream PR: we-promise/sure#4150 (https://github.com/we-promise/sure/pull/4150), opened 2026-10-11 from this same branch. How the two relate: same branch, same commits (up/rule-email-backfill at e073e3f6e), three commits on upstream main 2b18df230.

e073e3f6e, 2026-10-12: CodeRabbit's finding on we-promise/sure#4150 (comment 4246083394), confirmed and fixed at the owner's request ("Yes, make both fixes").

  • The defect, introduced by f2c50fc42. Both importers mark every existing condition for destruction and build new ones on each re-import, so every condition reads as changing even when the criteria are identical. The rule re-seeded, which recorded a match still waiting for the next run as delivered, so it was never emailed.
  • The fix, once in Rule#note_match_criteria_change, not in each importer: both importers and the form share it, and the importers are unchanged. When a condition reports a change, the rule compares a signature of the stored criteria (one query) with the same rows after the save's pending changes. The signature is order-independent at each level, treats nil and "" as equal, and includes sub-conditions. seed_notification_baseline is unchanged, so the #4089 guard merge stands.
  • New tests, each failing at 55ce46826 (a pending "Coffee bar" recorded as delivered): RuleImport with identical conditions, reordered conditions, and "" where nil was stored; a Sure re-import of a compound rule with reordered sub-conditions.
  • Mutations, each caught: always re-seed; order-sensitive comparison; no nested signature (the two existing sub-condition widening tests); nil vs "" as a change; marked conditions kept; in-memory edits ignored (16 tests).
  • Validation: rule, rule import, rules controller and data importer tests, 244 runs, 0 failures. Full bin/rails test on e073e3f6e: 11,565 runs, 0 failures, 0 errors. bin/rubocop on the changed files: no offenses. bin/brakeman: 0 warnings.
  • Upstream: replied in the thread (4249144383) and resolved it; the upstream description below carries the same edits.

Rebased 2026-10-12 onto upstream main 2b18df230 at the owner's request ("rebase #4150"). That main carries we-promise/sure#4145, the SnapTrade expectation fix.

  • c3594e8e3 became b6e7e7348, and f2c50fc42 became 55ce46826. git range-diff shows both patches unchanged.
  • The only change between the two bases is #4145's three lines in test/models/snaptrade_account/activities_processor_test.rb.
  • Rule, rule import, rules controller, data importer and SnapTrade tests on 55ce46826: 314 runs, 0 failures.
  • Pushed with --force-with-lease against f2c50fc42.
  • mirror/upstream-main is still at d55eac220 until its daily reset. Until then this PR's diff also shows #4145's three changed lines.
  • CI on 55ce46826: running at the time of writing. With #4145 in the base, ci / test_unit is expected to go green.

f2c50fc42, 2026-10-12: Codex's P1 on we-promise/sure#4150 ("Detect criteria removals after importers clear the association"), confirmed and fixed.

  • The defect. Both importers destroyed an existing rule's conditions with destroy_all before the rule's save:

    • Family::DataImporter#import_rules;
    • RuleImport.

    If the import carried no conditions, nothing changing was left for note_match_criteria_change to see, so no baseline was taken. A rule with no conditions matches every transaction, so the next run emailed old ones.

  • Reproduced through both importers with a test each. Each emailed "Tea house" or enqueued a job at c3594e8e3.

  • The fix. Both importers now mark the old conditions for destruction (rule.conditions.each(&:mark_for_destruction)). The save then removes them through autosave, inside the same transaction. match_criteria_changing? already counts a marked condition as a change, so Rule needed no change. The actions are still destroyed up front, as before, because they don't decide what the rule matches.

  • New tests:

    • test/models/rule/notification_baseline_on_edit_test.rb: "a Sure re-import that removes every condition does not email existing matches".
    • test/models/rule_import_test.rb: "re-importing an email rule with no conditions does not email existing matches".
  • Mutation. Putting either importer back to conditions.destroy_all fails that importer's test.

  • Negative. The existing "session rule reimport only replaces current family conditions and actions" still passes. So the marked conditions are removed, and the other family's rule is untouched.

  • Blast radius. The two destroy_all calls were the only places that clear a rule's conditions before a save. A grep of app/ and lib/ for conditions.destroy_all, conditions.delete_all, conditions.clear, conditions.replace and Rule::Condition.where/delete/destroy finds one other hit. That hit is Family::FinancialDataReset, which deletes the rules together with their conditions, so no rule is saved afterwards.

    • RulesController#update goes through nested attributes, which already mark for destruction.
  • Validation:

    • Rule, rule import, rules controller and data importer tests: 240 runs, 0 failures.
    • Full bin/rails test on f2c50fc42: 11,561 runs, 2 failures. Both are the known ones: the Ruby 3.3 Provider::OpenaiTest string, and the SnapTrade test below.
    • bin/rubocop on the changed files: no offenses. bin/brakeman: 0 warnings.
  • Branch diffstat now: 7 files, +461/−3. This commit is 4 files, +65/−3.

  • CI on f2c50fc42: ci / test_unit had 11,561 runs and 1 failure, the SnapTrade test below. Lint, both scans and Codacy were green.

Correction to my own earlier note, under the "code master" review below. It said "RuleImport requires conditions, so it isn't affected". That was wrong: RuleImport requires only an action, and it was affected the same way. Both paths are fixed in f2c50fc42.

Rebased 2026-10-12 onto upstream main d55eac220, 34 commits past the old base 94e71a8c2:

  • Two of the files moved upstream. main includes we-promise/sure#4109 ("Reject null bytes in rule fields"), which also changes rule.rb and rule/condition.rb. The rebase applied cleanly.
  • The patch was unchanged by the rebase. Its added and removed lines were identical to ba75e1bab's, 5 files, +396. Only the surrounding context moved.
  • Local full bin/rails test at c3594e8e3: 11,559 runs, 2 failures, both outside this change.
  • we-promise/sure#4089 has still not reached main, so the guard merge below is still pending on whichever lands second.

CI on c3594e8e3: ci / test_unit is red, on a failure that is upstream main's, not this PR's.

  • Passing: ci / test_system, ci / lint, ci / lint_js, ci / scan_ruby, ci / scan_js and Codacy. cubic is neutral.
  • ci / test_unit result: 11,559 runs, 1 failure. The failing test is SnaptradeAccount::ActivitiesProcessorTest#test_calculates_realized_gain/loss_for_option_buy_and_sell_using_per-contract_prices, which expects a realized gain of 7,000.00 and gets 6,999.79.
  • Why it isn't this PR's: it fails the same way on bare upstream main d55eac220, without this branch. we-promise/sure#4033 ("count fees in gains") takes a disposal's fee off the proceeds and adds a purchase's fee to the cost, and the test's expectations predate that rule.
  • The fix is upstream's: we-promise/sure#4144 reports it, and we-promise/sure#4145 changes the three expectations to 6,999.79 / 5,425.20 / 1,574.59. I get the same values independently, and with them the file passes on main d55eac220. It is not ported here, because it is unrelated to this change. #4145 has merged, and this branch is rebased onto it (above).

Process note. #389's Issue Gatekeeper Review had not landed when this was built. On 2026-10-10 the owner replied "Go with your recommendation" to a recommendation naming #388 and #389; I took that as the override rule 7 asks for.

The two owner decisions #389's plan left open, decided:

  1. Widening re-baselines. The issue's five grounds hold: the baseline exists so history is never emailed, the action-type callback guards the same hazard, the email doesn't say the transactions are old, and the rule's confirm page already shows what a broadened rule matches.
  2. Active or not. RulesController#apply_all runs inactive rules too, and the existing Rule::Action#seed_notification_baseline seeds without checking active.

Corrections to #389's body, found while building this:

  • "The same edit through an import already re-baselines" is not true. It relied on Rule::Action's create-time seed, which never runs: after_create_commit and after_update_commit name the same method, and Rails keeps only the last. That is a separate, older defect, raised as #411. With this PR, an import that changes a rule's criteria does re-seed, through the rule-level callback, including an import that removes every condition (f2c50fc42).
  • "after_create_commit does not fire inside a transactional test" (the reason given in send_email_notification_test.rb:62) is not the cause either; #411 has the evidence.

Review findings, fork side.

  • Gatekeeper light review, comments 6103101765 and 6103156567: DRAFT_ON_TRACK, with no BLOCKER, MAJOR or MODERATE findings.

    • OBSERVATION, the #4089 guard merge: agreed, already planned (see "Interaction with #4089" below). Re-checked 2026-10-11 at 275f2f994 and 2026-10-12 at d55eac220: #4089 is still not on main. Whichever lands second merges the guards into if: -> { switched_on? || match_criteria_changed? }.
    • Re-run the rules_controller and rule_import suites at the final head: done at f2c50fc42 within the 240-run set and the full suite (above).
  • "code master" review (comment 6105940647), HOLD, on ba75e1b: nothing confirmed, and nothing to change. Each finding was checked against this head with temporary probes and mutations. The review's line numbers don't match the head (for example, the pluck is at rule.rb:69, not :49).

    1. Unbounded memory, and insert_all past PostgreSQL's limit: declined.
      • Every normal run of an email rule already plucks and inserts the same full match set, through the same matching_resources_scope and NotificationDelivery.record_for (send_email_notification.rb:9,20). Family::Syncer#perform_post_sync re-applies every rule after every sync.
      • activerecord 8.1.3.1 writes insert_all as literal SQL, so the 65,535 bind-parameter limit never applies (0 binds measured).
      • Measured at 100,000 matches: 11.9 s for the edit's baseline, against 11.1 s for a normal first run and 9.2 s for a steady-state run.
      • If batching were ever wanted, it belongs in record_for, which both paths share.
    2. A long transaction holds a row lock: declined.
      • The insert is the last work before commit, so it holds locks about as long as a normal run's insert.
      • Moving it after commit reopens the window this PR closes: swapping in after_update_commit fails "the new baseline is written inside the edit's transaction".
    3. @match_criteria_changed is lost on reload: declined.
      • reload doesn't clear custom instance variables, and nothing calls it. With a reload injected between the callbacks, all 57 tests still pass.
      • The variable is needed because autosave drops destroyed conditions from the association. Rewriting the check on saved_change_to_* fails "removing a condition does not email existing matches".
    4. No error handling in the seed: declined. Rolling back is correct.
      • A temporary test showed it: with the rescue the review asks for, the edit commits without a baseline, and the next run emails "Tea house", which is #389 again.
      • A database error inside the callback also aborts PostgreSQL's transaction, so a rescue couldn't commit cleanly anyway.
    5. actions.exists? inside the transaction: not worth its code. It is one indexed query, run only when the criteria change, and it reads the saved state, which is the right state to read.
    6. No test for concurrent edits: not worth its code. The unique index plus the rule-row lock from touch: true carry it; the worst case is a deadlock that rolls one edit back cleanly.
    7. Import failure path untested: declined. The review itself calls the rollback correct.
    8. value_in_database coercion: declined. rule_conditions.value is a string column, so both sides are Ruby Strings.

    Outside the review, my note at the time: Family::DataImporter#import_rules deletes an existing rule's conditions with destroy_all, so an import with no conditions and the same effective_date takes no baseline. I left it alone as rare and unverified, and wrongly said RuleImport wasn't affected. Codex raised the same path on we-promise/sure#4150. It is real in both importers and fixed in f2c50fc42 (above).

  • Full Gatekeeper review, in three parts: comment 6107810964, 6107836719 and 6107893159, on ba75e1b (the same patch as c3594e8e3). APPROVE, risk HIGH, confidence HIGH, CI passing. It found no BLOCKER, MAJOR or MODERATE items; test evidence is adequate, and requirements are aligned.

    • It confirms the baseline reuses NotificationDelivery.record_for, which every email-rule run already executes, so the change adds no new scale or lock scope. That agrees with the "code master" disposition above.
    • OBSERVATION, the interaction with upstream #4089: already planned above.
    • OBSERVATION, the create-time seed never runs: pre-existing and out of scope here, as "Not in this change" says. It is tracked as #411.
    • After the review: f2c50fc42 (the Codex fix) was pushed on top. It changes only how the two importers clear conditions and adds two tests; the rule callbacks the review approved are untouched.
  • Nightly review (comment 6120443360), READY WITH CONDITIONS, on c3594e8e3: no blocking findings.

    • MEDIUM, required CI: this is the SnapTrade failure documented above. The base comparison it asks for is already verified: the same test fails on bare upstream main d55eac220. The fix is we-promise/sure#4145. It has landed, and this branch is rebased onto it as 55ce46826. ci / test_unit there is the check.
    • UNVERIFIED, latency and allocation on a large family: latency was measured for the "code master" review. At 100,000 matches the edit's baseline takes 11.9 s, against 11.1 s for a normal first run of the same rule. Allocation was not measured separately. The edit plucks the same id set, through the same scope, as every normal run, which Family::Syncer already triggers after each sync. So the edit adds no allocation beyond what the rule's own runs already do.
  • Nightly review (comment 6134304391), READY TO MERGE, on e073e3f6e. No blocking or other material findings. Nothing to change.

Review responses are recorded here rather than as comments, because comments posted from this session get an assistant footer appended, which this repository's attribution rule forbids.

The upstream description follows, as prepared for we-promise/sure#4150. Its title is "Stop emailing old matches after an email rule's conditions widen".


Closes #4102. Fork pre-flight: jaysbeekay/sure#412.

Problem

An email-notification rule records the transactions it already matches as delivered (a baseline), so it only reports what appears afterwards. The baseline describes the match set of the conditions and effective date it was taken under.

Editing the rule to match more brought older transactions into range: a broader condition, a removed condition, or an earlier or cleared effective date. The next run then emailed them as new activity, and the email does not say they are old.

Change

  • Rule::Condition#match_criteria_changing? is true when a condition is new, marked for destruction, or its type, operator or value is changing, at any depth (compound sub-conditions included).
    • It reads only in-memory state, so it runs no query.
    • A value moving between nil and "" is not a change: the edit form sends a valueless condition's hidden value back as "" where an import stored nil.
  • Rule records and acts on the change in two callbacks:
    • before_update :note_match_criteria_change records whether effective_date or any condition is changing. It runs before the save because autosave removes destroyed conditions from the association.
    • When a condition reports a change, it is confirmed against the stored criteria, with one query. The importers replace every condition, so each one reads as changing even when the criteria are the same. The rule compares a signature of the conditions as stored with the same rows after the save's pending changes: in-memory copies replace their rows, new conditions join, and those marked for destruction drop out.
    • A signature is each condition's type, operator, value and its sub-conditions' signatures, sorted at each level, with nil and "" equal. Order does not count: top-level conditions all apply, and a group's and/or reads its members either way.
    • after_update :seed_notification_baseline, if: :match_criteria_changed? then re-seeds through NotificationDelivery.record_for(rule_id:, transaction_ids: matching_transaction_ids), for a rule with a send_email_notification action, active or not.
  • after_update, not after_update_commit. It runs inside the save's transaction, after the nested autosave, so it reads the conditions as saved. The new baseline commits with the edit, and if writing it fails, the edit rolls back.
  • Both importers mark a rule's old conditions for destruction instead of destroy_all-ing them before the save (Family::DataImporter#import_rules, RuleImport). The save then removes them through autosave, inside the same transaction, and the rule sees its conditions change.
    • Without this, a re-import whose conditions list is empty left nothing changing. A rule with no conditions matches every transaction, so the next run emailed every older one.
    • The actions are still destroyed up front, as before: they don't decide what the rule matches.

The cost, stated: a transaction that arrived since the rule's last run, and matched the old conditions, is absorbed into the new baseline and not emailed. The existing code already prefers that direction ("we would rather miss a digest than spam", send_email_notification.rb).

Narrowing edits also re-seed, since a widening can't be told from a narrowing without running both queries. A narrowing edit cannot email history, so its only effect is that same cost. A re-import that leaves the criteria as they were, in any order, does not re-seed.

Interaction with #4089, which adds Rule#seed_notification_baseline as an after_update with if: :switched_on?: the method name and body here match it, so whichever lands second merges the two into if: -> { switched_on? || match_criteria_changed? }.

 app/models/family/data_importer.rb                 |   4 +-
 app/models/rule.rb                                 |  85 +++++++
 app/models/rule/condition.rb                       |  18 ++
 app/models/rule_import.rb                          |   6 +-
 test/controllers/rules_controller_test.rb          |  86 +++++++
 .../rule/notification_baseline_on_edit_test.rb     | 275 +++++++++++++++++++++
 test/models/rule_import_test.rb                    | 156 ++++++++++++
 7 files changed, 627 insertions(+), 3 deletions(-)

Tests

Measured as NotificationDelivery rows and enqueued RuleEmailNotificationJob arguments. Each positive test failed on main first:

TestOn main
widening an active email rule's condition does not email existing matchesemailed "Tea house"
clearing the effective date does not email existing matchesemailed "Coffee shop"
moving the effective date earlier does not email existing matchesemailed "Coffee shop"
a new transaction after the widening edit is still emailedemailed "Tea house" and "Guest house"; only "Guest house" expected
changing a condition's operator / type does not email existing matchesemailed "Tea house"
removing a condition does not email existing matchesemailed three old transactions
widening a compound sub-condition / adding a sub-condition to an any-of groupemailed "Tea house"
editing an inactive email rule then applying all rules does not email historyemailed "Tea house"
the new baseline is written inside the edit's transactionbaseline missing
controller: editing an email rule's condition through the form does not email existing matchesemailed "Tea house"
RuleImport: re-importing an email rule with wider conditions does not email existing matches1 job enqueued
RuleImport: re-importing an email rule with no conditions does not email existing matches1 job enqueued (also with the first version of this PR)
Sure import: a re-import that removes every condition does not email existing matchesemailed "Tea house" (also with the first version of this PR)

Negatives, passing before and after:

  • renaming an email rule does not re-seed;
  • resubmitting a valueless condition's blank value does not re-seed;
  • editing a rule without an email action writes no deliveries;
  • saving the form with unchanged conditions does not re-seed, so a match pending since the last run is still emailed;
  • the existing Sure re-import test ("session rule reimport only replaces current family conditions and actions") still passes, so the marked conditions are removed and the other family's rule is untouched;
  • a re-import with the same criteria does not re-seed, so a match pending since the last run is still emailed: RuleImport with identical conditions, with the conditions in a different order, and with a valueless condition's value as "" where nil was stored; and a Sure import of a compound rule with its sub-conditions reordered. These pass on main, and each failed at 55ce46826, this PR's previous head, by recording "Coffee bar" as delivered (CodeRabbit's finding).

The controller tests load the real edit page and submit every field it holds, as a browser does.

Mutations, each caught:

  • the callback removed;
  • detection limited to the effective date, or the effective-date arm removed;
  • no sub-condition detection;
  • any resubmitted condition counted as a change;
  • an active? guard added;
  • nil vs "" counted as a change;
  • no email-action check;
  • after_update_commit instead of after_update;
  • the new/destroyed arm removed, or the operator/type arm removed;
  • either importer put back to conditions.destroy_all (fails that importer's empty-conditions test);
  • the stored-criteria comparison removed, so every re-import re-seeds; the signature compared in order; sub-conditions left out of it; nil vs "" counted as a change in it; conditions marked for destruction kept in it; in-memory edits ignored in it.

Validation

  • Rule, rule import, rules controller and data importer tests at e073e3f6e: 244 runs, 0 failures.
  • bin/rails test on f2c50fc42, the same patches on the previous main d55eac220: 11,561 runs, 2 failures, both outside this change: Provider::OpenaiTest#test_extra_headers_stringifies_nested_values_Ruby-style, a Ruby 3.3 vs 3.4 string difference of the local runner, and the SnapTrade option test that #4145 has since fixed on main. Rebased onto main 2b18df230 as b6e7e7348 and 55ce46826 (unchanged patches): rule, rule import, rules controller, data importer and SnapTrade tests, 314 runs, 0 failures. With the CodeRabbit fix, e073e3f6e: bin/rails test, 11,565 runs, 0 failures, 0 errors.
  • bin/rubocop on the changed files: no offenses. bin/brakeman: 0 warnings. No ERB or JavaScript changed.

Not in this change

  • The create-time baseline that Rule::Action declares but never runs, so a new email rule's first run emails its history. That is a separate, older defect with its own fix.
  • Whether Apply all should run inactive rules at all.
  • Any change to the email's content or to NotificationDelivery.