Add starts with, ends with and regex rule operators

Closed
JA
2mo ago
+1429-10

Status (13 Oct): ported onto current upstream main by merge. The hold is lifted. Head is c9f239baf. See "Port (13 Oct)" below.

Port (13 Oct): merged onto upstream main, owner decision. The owner decided on 13 Oct to port this branch. It replaces the hold recorded in 6141255084. The branch merges mirror/upstream-main 3e35aaa07, which equals upstream main, as a merge commit. There is no rebase and no force push. The push was a fast-forward, 8c2a470ea..c9f239baf, so we-promise/sure#4089 moved to c9f239baf too. Its body is not edited; the replacement text is held for the owner.

CommitWhat
98e10d994Merge, resolving the conflicts in Rule and RuleJob
7270aff53Bind a regex rule's matches as one array parameter
f8bd0d253Test a regex timeout inside the ordered rule run
bb8c75d9eKeep a regex as written in the assistant's rule tools
c9f239bafQueue no run when apply_rule's email baseline times out

Resolutions.

  • we-promise/sure#4013 Rule::Runner: the regex branch and only_id: now sit in matching_scope, so the runner meets the timeout at the rule's own turn.
    • Its rescue records the run as failed. The rule claims and stops nothing, and the rules below still run in order.
    • The per-apply regex cache is removed. Upstream's Rule#apply evaluates its scope once, as a default argument, and the runner passes an explicit scope, so nothing read the cache any more.
    • RuleJob keeps upstream's retry_on LockBusy and adds discard_on TimeoutError.
  • we-promise/sure#4163 rename: matching_resources_scope is now matching_scope, which is public. Every reader goes through it: the runner, affected_resource_count, matching_transaction_ids, matches_transaction?, matching_resources (assistant preview), total_affected_resource_count and Rule#apply's default scope.
  • we-promise/sure#4109 null bytes: 3568dce86's NUL check in Rule::SafeRegex is removed. The regex validation now skips any value DatabaseTextValidator rejects.
    • On the plain merge, a null byte was reported twice ("Value is invalid" and "Value is not a valid regular expression"). Malformed UTF-8 raised ArgumentError from String#blank? inside the regex validation.
    • The tests now assert one :invalid error and no probe for a null byte, a lone null byte and malformed UTF-8.
  • Found in the sibling grep, beyond the conflicts.
    • Regex ids were bound with where(id: ids), one bind per id, which breaks past PostgreSQL's 65,535 limit. They now go through we-promise/sure#4013's scope_for_transaction_ids, as one array parameter.
    • The assistant's build_condition (we-promise/sure#3990) stripped a regex value.
    • The assistant's apply_rule queued RuleJob even when the switch-on baseline timed out. RuleJob runs the requested rule even when inactive, so this could email the history the switch-off prevents. It now returns baseline_timed_out and queues nothing.
  • Rule#seed_notification_baseline on switch-on is kept (8c2a470ea). For the two open upstream PRs on the same method:
    • we-promise/sure#4176 (jaysbeekay/sure#439) touches only Rule::Action and the importers. The baseline tests here now delete any create-time baseline in their helpers, so they hold either way. Checked with we-promise/sure#4176's Rule::Action applied: 29 runs green. Without the deletion, three tests fail.
    • we-promise/sure#4150 (jaysbeekay/sure#412) adds after_update :seed_notification_baseline, if: :match_criteria_changed? to Rule. Rails keeps only the last callback registered for the same method name, so whichever lands second must merge the two into after_update :seed_notification_baseline, if: -> { switched_on? || match_criteria_changed? }, keeping this branch's method body with its TimeoutError rescue.

Combined test (nightly 6120646191). regex_execution_test.rb covers a regex timeout, rule ordering and the email baseline together:

  • Under ApplyRulesJob, an active, stop-processing email rule at the top whose pattern times out gets a failed run and emails nothing. The rule below it decides, and that rule's stop processing still holds for the third rule.
  • RuleJob for a rule below a timed-out one records the failure and runs.
  • An email rule left off by a timed-out switch-on baseline is skipped by the sync run, even once the pattern runs in time.

Fail-first.

  • This branch's rule tests run against upstream main's app files, with Rule::SafeRegex removed: 111 runs, 17 failures, 47 errors (UnsupportedOperatorError for starts_with/matches_regex, NameError: Rule::SafeRegex).
  • Each port fix, before its change:
    • the bind test: 7 binds against 6;
    • the leading-space preview: expected 1, got 2;
    • apply_rule: 0 jobs expected, but 1 were enqueued;
    • the null-byte and UTF-8 tests: the double message above, and ArgumentError.

Mutations on the resolved code. 15, each restored from the commit and each caught by the targeted rule, job, controller and assistant tests:

MutationCaught by
Skip the regex branch in matching_scope18 tests
Swallow the timeout in matching_scope11 tests, including both ordered-run tests
Remove the affected_resource_count rescuethe confirmation counts are 0 rather than an error ...
Remove the matches_transaction? rescuea rule whose pattern times out does not count as covering a transaction
Remove discard_onRuleJob records a failed run ... and does not raise for a retry
Remove the switch-on after_update10 tests
Leave the rule on after a switch-on timeout4 tests
Remove the action-baseline rescuean email-notification action whose baseline times out ...
Drop starts_with from the operator list6 tests
Drop matches_regex from the operator list28 tests
Drop the only_id: narrowing2 tests
Drop the DatabaseTextValidator guardthe 3 invalid-text tests
where(id: ids) instead of the array parameter... bound as one parameter however many there are
Strip the regex in build_conditiona regex value is previewed as written, spaces included
Remove apply_rule's timeout guardan email rule whose baseline times out on activation stays off and is not queued

Validation at c9f239baf.

  • bin/rails test: 11,853 runs, 54,633 assertions, 0 failures, 0 errors, 34 skips. The same suite was green at bb8c75d9e before the last commit.
  • bin/rubocop on the changed Ruby: no offenses. bin/brakeman --no-pager -q: 0 warnings. No ERB or JS changed.
  • Diff against upstream main: 266 non-test lines added and 8 removed, plus 852 test lines.

Decided 2026-10-13, option (a), not fixed here. Apply all runs inactive rules (ApplyAllRulesJob passes family.rules; Rule::Runner runs requested rules regardless of active?), so an email rule that a timed-out baseline left off could still email its history under Apply all (a scratch test enqueued one RuleEmailNotificationJob). The owner chose option (a): an inactive rule's email action does nothing. It is a separate small PR in Rule::ActionExecutor::SendEmailNotification#execute, which this PR does not touch, tracked as jaysbeekay/sure#445. The same gap exists on main without this PR for rules switched off by hand.

Part of #130

Upstream pre-flight for the model layer of drop 11.1 (rule text operators and bounded regex). Upstream issue: we-promise/sure#4080. Upstream PR: we-promise/sure#4089 (draft, opened 2026-10-09). Same branch, same commit. Base is mirror/upstream-main at 3e35aaa07, which is upstream main at the time of the port. The branch was rooted at upstream main 00dd977fb and now merges 3e35aaa07, so the diff below is what upstream will see.

What is not here, and why. From #292 only the operators and Rule::SafeRegex go. Rule priority (the priority column, Rule.prioritised, apply_in_priority_order, Rule#move, the advisory-locked ApplyAllRulesJob, the syncer change and the export/import field) is held back. Upstream we-promise/sure#4013 has since merged (92d8ee524); it runs rules in a user-set order with its own rules.position column and Rule::Runner, and this branch now runs through that runner. The delivery rules say adopt rather than duplicate. The rules index/form UI stays on the fork as usual.

Divergences from fork main (all other code is byte-identical; the four test files are fork main's plus the additions below):

  • Rule#matches_transaction? exists upstream (we-promise/sure#3796) and not on fork main; it reaches the regex scope, so it gains a TimeoutError rescue (reads as "does not cover").
  • RuleJob gains discard_on Rule::SafeRegex::TimeoutError. Since the port, upstream's RuleJob runs through Rule::Runner and re-raises the requested rule's error. Without the discard, a timed-out pattern would be retried by Sidekiq, re-running every active rule above it. The runner itself carries on past a failing rule. The fork's RuleJob test that asserted the raise now asserts a recorded failed run and no raise.
  • Tests added here, not on the fork: matches_transaction? for a regex rule and on timeout; a read after #apply resolves the pattern again (on 8c2a470ea this covered the per-apply cache's ensure reset; the cache is removed by the port); the "unchanged condition is not probed" test also saves the condition directly (saving the rule alone never validates an unchanged condition, so the changed-only guard survived mutation). The last two are fork test gaps worth back-porting. Also here only: matches_transaction? runs a regex rule's pattern on the one transaction (only_id: in matching_resources_scope, 3fab17de3) rather than resolving the family's matches first; fork main has no matches_transaction?, so nothing to back-port.

Follow-up (9 Oct): review fixes. (Kept for the record. The null-byte part, 3568dce86, is superseded by we-promise/sure#4109 in the port above.) Head is now 8c2a470ea (two commits on 3fab17de3), pushed to this branch, so they are on we-promise/sure#4089 too. They answer the adversarial review (comment 6079713683) and the reply to it (6079761143). The text proposed for #4089's body is held for the owner, and #4089 itself is not edited.

  • 3568dce86 Refuse a regex pattern containing a null byte as invalid. Rule::SafeRegex#error returns :invalid for a pattern containing NUL, before the probe and before the blank check (String#strip removes NUL, so "\0" alone read as :blank, a kind the condition has no message for). The form shows "Value is not a valid regular expression" instead of a 500. No saved row can hold a NUL: the pg driver refuses it on write as well (update_columns raises ArgumentError, checked against Postgres), so the ~* filter and every matching_resources_scope caller only ever see validated patterns.
  • 8c2a470ea Record an email rule's baseline again when it is switched on. Rule gains after_update :seed_notification_baseline, if: :switched_on? (active going from false to true). When the rule has a send_email_notification action, it records matching_transaction_ids through NotificationDelivery.record_for. It runs inside the save's transaction, after the nested conditions and actions are autosaved, so the baseline uses the saved conditions and commits together with active: no reader (the syncer, RuleJob) can see the rule on without its baseline. On TimeoutError the rule stays off (update_columns(active: false)), notification_baseline_timed_out? is set, RulesController#apply queues no RuleJob, and #apply and #update (the toggle and the form) show the alert rules.notification_baseline_timed_out instead of the success notice. This deliberately also stops emails for matches that appeared while the rule was off. A rule without an email action is unaffected.

Blast radius: every writer of Rule#active. RulesController#apply (update!(active: true)): seeds, then queues the run, or queues nothing and alerts on a timeout. RulesController#update (the toggle and the form, :active permitted): seeds, or alerts on a timeout. Rule::Action#seed_notification_baseline (update_columns(active: false)): skips callbacks, unaffected. Rule.create_from_grouping (active: true on build): a create with no email action, unaffected. RuleImport#create_or_update_rule_from_row and Family::DataImporter#import_rules (active = / assign_attributes): they rebuild the actions, so the new action's after_create_commit already seeds; switching an existing rule on seeds as well (an idempotent insert, at the cost of one extra match query). The API is read-only. Readers of active (Family::Syncer, Financekit::Downstream, Transaction::Ruleable) are unchanged.

Tests (written first, failing for the right reason before the fix).

  • safe_regex_test.rb: a pattern containing a null byte is invalid and never reaches the database. Before the fix, the probe was reached: unexpected invocation ... select_value("SHOW statement_timeout").
  • condition_regex_test.rb: a rule with a null byte is rejected and nothing is saved, and a null byte is reported on the form as an invalid pattern. Before the fix: ArgumentError: string contains null byte.
  • New test/models/rule/notification_baseline_on_enable_test.rb, with deltas measured on NotificationDelivery and on enqueued RuleEmailNotificationJob:
    • switching on records the matches without emailing them (before the fix: Expected: 1, Actual: 0);
    • a later match is still emailed;
    • the baseline uses conditions changed, or removed, in the same submit;
    • negatives: no email action records nothing; a rule already on, saved again, does not re-seed; switching off records nothing;
    • a timeout leaves the rule off and keeps the rest of the save.
  • rules_controller_test.rb:
    • Apply records the baseline before queuing RuleJob;
    • Apply on a timeout queues nothing and alerts (before the fix: Expected: 0, Actual: 1 jobs);
    • the toggle alerts and stays off on a timeout, and switches on otherwise.

Mutations (each restored from the commit, each caught).

MutationCaught by
Remove the NUL checkthe null-byte tests in safe_regex_test.rb and both in condition_regex_test.rb
NUL check after the blank checka pattern containing a null byte is invalid and never reaches the database ("\0" read as :blank)
Remove the after_update9 tests: every model and controller positive and timeout test
Fire on any change of activeswitching a rule off records nothing
Fire whenever the rule is onsaving a rule that is already on does not record a baseline again
Drop the email-action guardswitching on a rule without an email action records nothing
Timeout leaves the rule onthe model timeout test, and both controller timeout tests
Timeout not flaggedthe model timeout test, and both controller timeout tests
Seed in before_update (before the nested autosave)a condition removed in the same form submit does not narrow the baseline
Apply queues the run anywayapply leaves an email rule off and queues nothing when its baseline times out
Update always shows the success noticethe active toggle leaves an email rule off and says why when its baseline times out

Validation at 8c2a470ea. bin/rails test: 10,912 runs, 46,471 assertions, 0 failures, 0 errors, 33 skips. bin/rubocop on the changed files: no offenses. bin/brakeman --no-pager -q: 0 warnings. No ERB changed. Checked against upstream AGENTS.md: logic is in the model, the controller only picks the flash, the new string goes through t(), and commit subjects are 72 characters or fewer.

Declined findings from the same review (other locales, length counting whitespace, the 1 s probe) are answered with evidence in 6079761143.


Closes #4080

Fork pre-flight: jaysbeekay/sure#366 (same branch, same commit). Model layer of drop 11.1 of jaysbeekay/sure#130. The branch merges main at 3e35aaa07 (no rebase), so the diff against main is this PR's change alone.

Summary

Text rule conditions (transaction name, notes) gain three operators: Starts with, Ends with and Matches regex. They appear in the existing rule form's operator list wherever "Contains" does today, and in the assistant's rule tools (get_rule_options, preview_rule, create_rule, update_rule). Users see them as soon as this merges. There is no new screen.

Matches regex is the security-relevant part. A saved pattern runs on every sync, so Rule::SafeRegex bounds it against ReDoS and against patterns that would fail at run time. The limits and their tests are listed under Verification.

Rules run through Rule::Runner (#4013) in their set order, with stop processing. A pattern that times out fails its own rule's turn: the failure is recorded, it claims and stops nothing, and the rules below it still run.

What changed

  • Rule::ConditionFilter adds starts_with, ends_with and matches_regex to the text operator list.
    • Starts with and ends with are ILIKE, with the value passed through sanitize_sql_like, so % and _ match themselves.
    • Matches regex is ~* (case-insensitive), and its value is bound as written. The whitespace normalisation the other text operators apply would change what a pattern matches.
    • TransactionDetails and TransactionType keep their own operator lists and do not gain these.
  • Rule::SafeRegex (new). The pattern runs in PostgreSQL, whose regex engine does not backtrack, so nested quantifiers such as (a+)+$ stay linear. It guards four things:
    • Back-references \1 to \9 (exponential in PostgreSQL's engine) are refused. An escaped backslash before a digit (\\1) is not mistaken for one.
    • A pattern PostgreSQL will not compile (parentheses () not balanced, regular expression is too complex) is probed once at save under a 1 s statement_timeout. It becomes a validation error instead of a rule that fails on every sync. Only SQLSTATE 2201B counts as a bad pattern; any other database error is re-raised.
    • Patterns over 200 characters are refused.
    • with_timeout runs a block under SET LOCAL statement_timeout inside a savepoint, restores the previous value, and raises TimeoutError on QueryCanceled.
  • Rule::Condition adds regex?, uses_regex? (which looks into compound conditions) and a regex_value_is_safe validation.
    • The validation runs only when the value or operator changes, so toggling a rule does not probe its pattern again.
    • It skips a value that DatabaseTextValidator (#4109) rejects, such as a null byte or malformed UTF-8. That value is reported once, as "Value is invalid", and never probed, because the driver refuses to send it.
  • Rule#matching_scope handles rules with a regex condition. When any condition uses a regex, the matching ids are resolved under the 5 s execution timeout and returned as scope_for_transaction_ids(ids). That is one array parameter however many rows match.
    • Every reader goes through it: Rule::Runner, affected_resource_count, matching_transaction_ids, matches_transaction?, matching_resources (assistant preview), total_affected_resource_count and Rule#apply's default scope.
    • When the pattern times out, the display counts read 0, and matches_transaction? reads it as not covering the transaction, so the "create a rule?" prompt is still offered.
    • matches_transaction? passes only_id:, so its regex query runs on that one row.
    • Rule#apply resolves its scope once and hands it to every action, so a rule with several actions scans once.
  • RuleJob adds discard_on Rule::SafeRegex::TimeoutError beside retry_on Rule::Runner::LockBusy. The runner records the failed RuleRun, and the job re-raises the requested rule's error. For a timeout, a Sidekiq retry would time out again and re-run every active rule above, so the job is discarded instead. ApplyRulesJob and ApplyAllRulesJob do not raise for a failing rule; the runner carries on with the next one.
  • Email baseline on a timeout. Rule::Action handles a timeout when the action is created. If the email-notification baseline times out, the action is kept and the rule is switched off, because with no baseline its next run would email every past match.
  • Email baseline on switch-on. Rule gains after_update :seed_notification_baseline, if: :switched_on? (active going from false to true). This covers the toggle, the form, Apply and an import.
    • The callback records the rule's current matches as delivered when it has a send_email_notification action. It runs inside the save's transaction, after the nested conditions are written, so the baseline uses the saved conditions and commits together with active.
    • On a timeout the rule stays off, RulesController#apply queues no run, and the toggle, form and Apply show an alert (rules.notification_baseline_timed_out) instead of the success notice.
    • This deliberately also stops emails for matches that appeared while the rule was off.
  • Assistant rule tools (#3990):
    • RuleSupport#build_condition keeps a regex value as written; other values are still stripped. For example, " shop$" stripped to "shop$" would also match "Workshop".
    • get_rule_options reads the operator list from the filters, so it offers the new operators without a change, and preview_rule counts and samples regex matches through matching_scope.
    • apply_rule activates with update!(active: true), as Apply does. When the email baseline times out, it now returns a baseline_timed_out error and queues nothing, as RulesController#apply does. Before, it queued RuleJob, which runs the requested rule whether or not it is active, and reported the rule as activated.
  • Locales: operator labels and the timeout alert in views/rules/en.yml; the four validation messages in models/rule/en.yml.

Merged with main (13 Oct)

This was opened against main at 00dd977fb. Since then, #4013, #4163, #4109 and #3990 have merged. main (3e35aaa07) is merged into the branch, and the conflicts in Rule and RuleJob are resolved as follows:

  • #4013 (Rule::Runner): the regex timeout surfaces from matching_scope at the rule's turn in the runner. The runner's own rescue records the failed run, and the rule claims and stops nothing. The per-apply regex cache this PR had is removed, since nothing reads it any more. RuleJob keeps upstream's retry_on LockBusy and adds the discard_on.
  • #4163 (rename): the regex branch and only_id: live in matching_scope, which is now public; matching_resources delegates to it.
  • #4109 (null bytes): this PR's own NUL check in Rule::SafeRegex is removed in favour of DatabaseTextValidator. On the plain merge a null byte was reported twice ("is invalid" and "is not a valid regular expression"), and malformed UTF-8 raised ArgumentError from String#blank? in the regex validation. The tests for both now assert one "Value is invalid" error and no probe.
  • #3990 (assistant rule tools): covered by the build_condition and apply_rule changes above.

Overlap with open PRs

  • #4176 (create-time baseline) records the baseline when the email action is created, through one after_commit ... on: %i[create update] plus keep_notification_baseline.
    • It does not touch Rule, so it merges cleanly with the switch-on callback here. The two seeds are idempotent inserts.
    • This PR's baseline tests delete any create-time baseline in their helpers. Checked with we-promise/sure#4176's Rule::Action applied: they pass (29 runs). Without the deletion, three tests fail.
  • #4150 (re-seed when the match criteria change) adds after_update :seed_notification_baseline, if: :match_criteria_changed? to Rule, with the same method name.
    • Rails keeps only the last callback registered for the same method, so a textual merge that keeps both lines would silently drop one.
    • Whichever lands second should merge them into one: after_update :seed_notification_baseline, if: -> { switched_on? || match_criteria_changed? }.
    • The method body should be this PR's, which adds the TimeoutError rescue that keeps the rule off.

Demo data

None. The demo generator's rules are unchanged; a regex rule can be created from the existing form.

Migration notes

None. No schema change. Existing rules keep their operators and match exactly as before.

Verification

  • bin/rails test at c9f239baf: 11,853 runs, 54,633 assertions, 0 failures, 0 errors, 34 skips.
  • bin/rubocop on the changed Ruby files: no offenses. bin/brakeman --no-pager -q: 0 warnings. No ERB or JavaScript changed.
  • Fail-first, re-run on the merged branch. This PR's tests were run against main's versions of the changed app files, with Rule::SafeRegex removed: 111 runs, 17 failures, 47 errors. Examples: UnsupportedOperatorError: Unsupported operator: starts_with, and NameError: Rule::SafeRegex.
  • Ordered run, timeout and email baseline together (regex_execution_test.rb):
    • An active, stop-processing email rule at the top whose pattern times out under ApplyRulesJob gets a failed run and is not raised. It emails nothing and records no delivery. The rule below it decides the category, and that rule's stop processing still holds for the one below.
    • RuleJob for a rule below a timed-out one records that failure and runs the requested rule.
    • An email rule left off by a timed-out switch-on baseline is skipped by the sync run, even once its pattern runs in time.
  • ReDoS and limits (safe_regex_test.rb, condition_regex_test.rb, regex_execution_test.rb):
    • Back-references are refused, and \\1 is accepted. Nested quantifiers are accepted, because PostgreSQL runs them linearly.
    • Length is capped at the boundary: 200 accepted, 201 refused.
    • Unbalanced and too-complex patterns are refused at save, and nothing is saved.
    • A non-regex database error is re-raised. A failed probe does not poison an open transaction.
    • with_timeout raises TimeoutError and restores the limit afterwards.
    • A match query that really sleeps in PostgreSQL is cancelled (no stub), in under 0.9 s against a 30 ms limit. A regex inside a compound condition is bounded too.
    • A null byte, a lone null byte and malformed UTF-8 are each rejected as invalid text without a probe.
    • Regex matches are bound as one parameter whatever the match count. Before the fix this showed 7 binds against 6.
  • Operators (condition_filter/text_operators_test.rb, preview_rule_test.rb):
    • Prefix and suffix match without mid-string hits, on name and on notes, and % and _ are literal.
    • The regex is case-insensitive, honours anchors, and its whitespace is not normalised.
    • The operators are offered on the right filters.
    • The assistant preview counts and samples all three. It keeps a regex's leading space (before the fix: expected 1 match, got 2), and it reports an uncompilable pattern as a problem.
    • apply_rule on an email rule whose baseline times out leaves it off and queues nothing (before the fix: 0 jobs expected, but 1 were enqueued).
  • Switch-on baseline (notification_baseline_on_enable_test.rb, rules_controller_test.rb):
    • Switching on records the matches without emailing them, and a later match is still emailed.
    • The baseline uses conditions changed, or removed, in the same submit.
    • Negatives: no email action, already on, switching off.
    • A timeout leaves the rule off and keeps the rest of the save. Apply then queues nothing and alerts, and the toggle alerts.
  • Mutations on the merged code. Each line below was broken on purpose and caught by the tests named:
    • Skipping the regex branch in matching_scope: 18 tests.
    • Removing the affected_resource_count rescue, the matches_transaction? rescue, the action-baseline rescue, or discard_on: one named test each.
    • Swallowing the timeout inside matching_scope: 11 tests, including both ordered-run tests.
    • Removing the switch-on callback: 10 tests. Leaving the rule on after a switch-on timeout: 4 tests.
    • Dropping starts_with from the operator list: 6 tests. Dropping matches_regex: 28 tests.
    • Dropping the only_id: narrowing: 2 tests.
    • Dropping the DatabaseTextValidator guard: the three invalid-text tests.
    • Binding with where(id: ids): the bind test.
    • Stripping the regex in build_condition, or removing apply_rule's timeout guard: one named test each.
    • The earlier 36 mutations, on 8c2a470ea, are in jaysbeekay/sure#366.

Blast radius

Who else hits this line, and what do they pass?

matching_scope is read by:

  • Rule::Runner#unstopped_scope, once per rule per run;
  • affected_resource_count (the rule confirmation page, the assistant's get_rules and apply_rule, and the auto-categorize cost estimate);
  • total_affected_resource_count (apply-all confirmation);
  • matching_transaction_ids (the email baseline, in Rule::Action and in Rule's switch-on callback);
  • matches_transaction? (Transaction::Ruleable#eligible_for_category_rule?, one transaction per call, so it passes only_id:);
  • matching_resources (the assistant's preview, which counts and samples);
  • Rule#apply's default scope.

For a rule with no regex condition the scope is returned unchanged. For a regex rule, each reader has its own answer to a timeout, listed above, and each has a test.

The assistant preview is the one reader without its own rescue. A timeout there falls to FunctionToolCaller's and McpController's generic rescue, so the tool fails and no preview token is issued.

What else reads what I just changed the reading of? grep -rn "OPERATORS_MAP\|def operators\|build_sanitized_where_condition" app/models/rule finds:

  • ConditionFilter#operators, which feeds the rule form through as_json (app/javascript/controllers/rule/conditions_controller.js), validate_operator, and the assistant's build_condition and get_rule_options;
  • TransactionName and TransactionNotes, which inherit the text list;
  • TransactionDetails and TransactionType, which override it and are deliberately unchanged.

The other writers of condition values:

  • RuleImport (CSV) and Family::DataImporter build conditions through Rule::Condition, so an imported regex is validated the same way.
  • The API (api/v1/rules) is read-only.
  • Writers of active (the switch-on callback) are the toggle, the form and Apply (RulesController), apply_rule (assistant, which now checks the timeout as Apply does), Rule.create_from_grouping (a create, with no email action), the importers (which rebuild the actions, so the action's own seed applies as well), and Rule::Action's timeout path (update_columns, which skips callbacks).