Record an email action's baseline when it is created

Merged
JA
1mo ago
+391-33

Closes #4152.

Fork pre-flight: jaysbeekay/sure#439 (same branch, same commit; its CI, review and test history live there).

Problem

A "Send email notification" action is meant to record the transactions its rule already matches as delivered when it is created, so the rule only ever emails what appears afterwards. That create-time baseline never ran. Rule::Action registered the same method twice:

after_create_commit :seed_notification_baseline
after_update_commit :seed_notification_baseline, if: :saved_change_to_action_type?

Both expand to after_commit :seed_notification_baseline, on: ..., and Rails keeps only the last commit callback naming a method. So a new email rule, or an email action added to an existing rule, emailed every transaction it already matched on its first run (Apply, or the next sync). Only changing an existing action's type to email took a baseline.

Change

  • Rule::Action: one after_commit :seed_notification_baseline, on: %i[create update], if: :saved_change_to_action_type?. On create the type changes from nil, so the existing guard admits every new action, and on update it still seeds only when an action becomes an email action. Rule::Action._commit_callbacks now holds one entry covering create and update.
  • Importers keep an email rule's baseline across a re-import. RuleImport and Family::DataImporter#import_rules destroy and rebuild a rule's actions on every re-import. With the create-time seed working, an identical re-import would have re-seeded and recorded a match still waiting for the rule's next run as delivered, so it would never be emailed. An importer that replaces a rule's own email action now sets keep_notification_baseline on the new one, and the seed skips it; the baseline stays under the rule's id. An import that creates a rule, or gives a rule its first email action, seeds. Whether a rule already had one is read once, before the import writes anything (Rule.ids_with_stored_email_notification_action): every row shares one transaction, so a rule named twice in one file would otherwise see, on its second row, the email action its first row had only just written, and keep a baseline nothing had recorded (review feedback).
  • The assistant's update_rule keeps it too. update_rule (also served over MCP) replaces a rule's whole action list whenever actions is passed: assign_definition marks every action for destruction and builds the list again. Resending an unchanged email action would have re-seeded the same way. assign_definition now notes whether the rule had an email action before marking and sets the same flag on the rebuilt actions. create_rule goes through the same method on a new rule, which has no actions, so a new rule still seeds.
  • One definition of the email action (review feedback). Rule::Action::EMAIL_NOTIFICATION, with an email_notifications scope and Rule::Action#email_notification?, used by the seed. Rule#stored_email_notification_action? (persisted? && actions.email_notifications.exists?) is the check the assistant makes before replacing a rule's actions; each of its calls commits on its own. The importers read the snapshot above instead. It reads the database, so actions built or marked for destruction in memory do not change it. The assistant used an in-memory any? before. The answer is the same: find_rule loads the rule fresh, and its actions are unchanged when the check runs. A test pins the constant to Rule::ActionExecutor::SendEmailNotification#key, which is derived from the class name, so a rename fails a test. In app/ and lib/ the literal now appears only in the constant.
  • The executor test that called the seed by hand (send_email_notification_test.rb), on the belief that after_create_commit does not fire under transactional tests, now creates the rule and relies on the callback. The update callback was firing in the same tests all along.

Left out: any backfill for rules created before this fix. Those rules have already emailed their history, or will on their next run, and a migration cannot tell which. Re-seeding when a rule's criteria change or when it is switched on is already on main (#4150, #4089); see below.

Interaction with merged work

Merged since this PR opened: #4150, #4089, #4211 and #3020. This branch has current main merged in; the merge conflicts were adjacent additions, kept on both sides.

  • #4150 (criteria-change re-seed). It runs Rule#seed_notification_baseline as an after_update on Rule, a different class and callback from this PR's Rule::Action one. In both importers it changed rule.conditions.destroy_all to mark_for_destruction; this PR's email-action snapshot and keep flag sit beside that. Behaviour composes: a re-import with changed criteria is re-seeded by #4150's rule callback, and an identical one by neither, which is #4150's own tested invariant and still passes. A save in which the rule re-seeds and an email action is added takes the baseline once: the action's seed skips when the rule has already taken it in that save (notification_baseline_taken_in_this_save?). This PR now also switches #4150's check to actions.email_notifications.exists?, and drops the hand call to the action's seed from the helper in notification_baseline_on_edit_test.rb, whose comment said the create-time seed does not run. The helper now relies on creation to seed, and that file's tests still fail with #4150's re-seed removed.
  • #4089 (switch-on re-seed, and a rescue Rule::SafeRegex::TimeoutError at the end of Rule::Action#seed_notification_baseline). With this PR the rescue also covers the create-time seed, which is what its comment describes. Its email_rule test helper already clears any create-time baseline (NotificationDelivery.where(rule: rule).delete_all), so its tests are unaffected. This PR changes one of them, "an email action added after a later save still takes its baseline", to create the action and rely on the callback instead of calling the seed by hand.
  • #4211 (an inactive rule's email action sends nothing). Rule#apply on an inactive rule sends nothing, and update_rule leaves a changed rule inactive, so this PR's update_rule resend test switches the rule on first (update_columns(active: true)), as apply_rule does in use. The pre-seed test in send_email_notification_test.rb is this PR's version, with #4211's active: true on its rules.create!.
  • #3020 (split_transaction action). No interaction: it adds split fields and validations to Rule::Action, beside this PR's constant, scope and callback.

Tests

test/models/rule/notification_baseline_on_create_test.rb (new), one form test in test/controllers/rules_controller_test.rb, and the corrected executor test. Measured as NotificationDelivery rows and enqueued RuleEmailNotificationJob arguments, before and after. Each positive test failed on 3e35aaa07 first:

TestOn 3e35aaa07
creating a rule with an email action records its current matches as the baseline0 rows, 2 expected
a new email rule's first run emails nothing that matched before itemailed both old matches
a match that appears after the email rule is created is still emailedemailed the new match and both old ones
adding an email action to an existing rule records the baseline[]
controller: creating an email rule through the form records its current matches[]
RuleImport / Sure import record the baseline for a new email rule[]
a RuleImport re-import that adds an email action to an existing rule records the baseline[]
an identical RuleImport / Sure re-import keeps the baseline, so a pending match is still emailedemailed the pending match and both old ones (no baseline at all)
executor: pre-seed watermark records existing matches without sending1 job enqueued
assistant create_rule: a new email rule records its current matches as the baselineregression guard for the seed on this path
assistant update_rule: replacing a rule's actions with an email action records the baselineregression guard for the seed on this path
assistant update_rule: resending an unchanged email action keeps the baseline, so a pending match is still emailedfailed on 5071b52d5 (this PR's first commit): the pending match was recorded as delivered
the email action type is the email executor's keyfailed on 3b4a64d4c: NameError, no constant yet (drift guard)
email_notifications selects only the email actionsfailed on 3b4a64d4c: no such scope
a rule reports a stored email action, even once it is marked for replacementfailed on 3b4a64d4c: no such predicate
an email action that is only built, not stored, does not count as the rule'sfailed on 3b4a64d4c: no such predicate

Negatives, passing before and after: changing an existing action's type to email still seeds; creating a rule without an email action records nothing and never runs the match query; editing an email action without changing its type does not re-seed.

Mutations, each caught:

  • the two separate callbacks restored: 25 tests (re-measured on 95230b936 across the rule, rules controller, assistant, importer and job tests; the criteria-change tests now count, since their helper relies on the create-time seed);
  • on: %i[update] only: 25 tests;
  • the saved_change_to_action_type? guard dropped: "editing an email action without changing its type";
  • keep_notification_baseline ignored: both identical re-import tests;
  • the flag forced off in RuleImport / in the Sure importer: that importer's identical re-import test;
  • the flag forced on in RuleImport: 3 tests (new rule, adding an email action, identical re-import); in the Sure importer: 2 tests;
  • in update_rule: the flag never set (the resend test); the flag forced on (create_rule's new rule and "replacing ... with an email action"); any existing action counted as an email action ("replacing ... with an email action"). A persisted? check in the first version survived mutation, since no new action exists yet when it runs, and was removed.
  • the shared definition (2e276bf56): changing the constant's value, 17 tests; Rule#stored_email_notification_action? always false, 4 tests (both identical re-imports, the assistant resend, the predicate test); reading the in-memory actions instead, the "only built" test; Rule::Action#email_notification? always false, 15 tests; the scope inverted, 8 tests. The persisted? in the shared predicate only saves a query on a new rule, whose association query matches nothing, so it is not mutation-tested.
  • the update_columns(active: true) in the resend test does not weaken it: with the keep flag ignored, it still fails.
  • #4150's check matching another action type instead of the scope (95230b936): 28 tests, including "editing a rule without an email action writes no notification deliveries"; #4150's criteria-change re-seed removed: 14 tests, 11 of them in notification_baseline_on_edit_test.rb with the hand-called seed gone.
  • the import snapshot (01a8e7470): either importer going back to stored_email_notification_action? fails its "naming a new email rule twice" test; an empty snapshot fails both identical re-import tests.

Blast radius. Who else creates a Rule::Action, and does it need the flag?

  • The rule form's create: a new rule, so it seeds (controller test). Its update keeps the ids of unchanged actions, so nothing is recreated and nothing re-seeds. A submit that removes an email action and adds a new one is treated as adding one, and seeds.
  • RulesController#new: builds an unsaved rule to prefill the form. It is never saved.
  • Rule.create_from_grouping: a new rule with a set-category action only, so it never reaches the seed.
  • RuleImport and Family::DataImporter#import_rules: destroy and rebuild a rule's actions. Flagged.
  • The assistant tools (Assistant::Function::RuleSupport#assign_definition, also served over MCP). create_rule builds a new rule, so it seeds. update_rule marks every action for destruction and rebuilds them, so it is flagged. preview_rule never saves.
  • The v1 rules API is read-only.

seed_notification_baseline has no other caller.

Validation

  • Full suite on this head (95230b936): 12,960 runs, 59,739 assertions, 0 failures, 0 errors, 36 skips.
  • bin/rubocop on the changed files: no offences. bin/brakeman --no-pager -q: 0 warnings.
  • No UI, API, migration or locale changes. Migration notes: none.

Summary by CodeRabbit

  • Bug Fixes
    • Creating or importing a rule with email notifications now records existing matching transactions, preventing duplicate notifications.
    • Transactions that begin matching later remain eligible for email notifications.
    • Updating or re-importing a rule without changing its email notification action preserves pending notifications.
    • Replacing a rule’s actions with an email notification action records existing matches as delivered, preventing duplicate notifications when the rule is applied.