Add starts with, ends with and regex rule operators
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.
| Commit | What |
|---|---|
98e10d994 | Merge, resolving the conflicts in Rule and RuleJob |
7270aff53 | Bind a regex rule's matches as one array parameter |
f8bd0d253 | Test a regex timeout inside the ordered rule run |
bb8c75d9e | Keep a regex as written in the assistant's rule tools |
c9f239baf | Queue no run when apply_rule's email baseline times out |
Resolutions.
- we-promise/sure#4013
Rule::Runner: the regex branch andonly_id:now sit inmatching_scope, so the runner meets the timeout at the rule's own turn.- Its
rescuerecords 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#applyevaluates its scope once, as a default argument, and the runner passes an explicit scope, so nothing read the cache any more. RuleJobkeeps upstream'sretry_on LockBusyand addsdiscard_on TimeoutError.
- Its
- we-promise/sure#4163 rename:
matching_resources_scopeis nowmatching_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_countandRule#apply's default scope. - we-promise/sure#4109 null bytes:
3568dce86's NUL check inRule::SafeRegexis removed. The regex validation now skips any valueDatabaseTextValidatorrejects.- 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
ArgumentErrorfromString#blank?inside the regex validation. - The tests now assert one
:invaliderror and no probe for a null byte, a lone null byte and malformed UTF-8.
- 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
- 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'sscope_for_transaction_ids, as one array parameter. - The assistant's
build_condition(we-promise/sure#3990) stripped a regex value. - The assistant's
apply_rulequeuedRuleJobeven when the switch-on baseline timed out.RuleJobruns the requested rule even when inactive, so this could email the history the switch-off prevents. It now returnsbaseline_timed_outand queues nothing.
- Regex ids were bound with
Rule#seed_notification_baselineon 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::Actionand 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'sRule::Actionapplied: 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?toRule. Rails keeps only the last callback registered for the same method name, so whichever lands second must merge the two intoafter_update :seed_notification_baseline, if: -> { switched_on? || match_criteria_changed? }, keeping this branch's method body with itsTimeoutErrorrescue.
- we-promise/sure#4176 (jaysbeekay/sure#439) touches only
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. RuleJobfor 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, withRule::SafeRegexremoved: 111 runs, 17 failures, 47 errors (UnsupportedOperatorErrorforstarts_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:
| Mutation | Caught by |
|---|---|
Skip the regex branch in matching_scope | 18 tests |
Swallow the timeout in matching_scope | 11 tests, including both ordered-run tests |
Remove the affected_resource_count rescue | the confirmation counts are 0 rather than an error ... |
Remove the matches_transaction? rescue | a rule whose pattern times out does not count as covering a transaction |
Remove discard_on | RuleJob records a failed run ... and does not raise for a retry |
Remove the switch-on after_update | 10 tests |
| Leave the rule on after a switch-on timeout | 4 tests |
| Remove the action-baseline rescue | an email-notification action whose baseline times out ... |
Drop starts_with from the operator list | 6 tests |
Drop matches_regex from the operator list | 28 tests |
Drop the only_id: narrowing | 2 tests |
Drop the DatabaseTextValidator guard | the 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_condition | a regex value is previewed as written, spaces included |
Remove apply_rule's timeout guard | an 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 atbb8c75d9ebefore the last commit.bin/rubocopon 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 forkmain; it reaches the regex scope, so it gains aTimeoutErrorrescue (reads as "does not cover").RuleJobgainsdiscard_on Rule::SafeRegex::TimeoutError. Since the port, upstream'sRuleJobruns throughRule::Runnerand 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'sRuleJobtest 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#applyresolves the pattern again (on 8c2a470ea this covered the per-apply cache'sensurereset; 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:inmatching_resources_scope, 3fab17de3) rather than resolving the family's matches first; forkmainhas nomatches_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.
3568dce86Refuse a regex pattern containing a null byte as invalid.Rule::SafeRegex#errorreturns:invalidfor a pattern containing NUL, before the probe and before the blank check (String#stripremoves 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_columnsraisesArgumentError, checked against Postgres), so the~*filter and everymatching_resources_scopecaller only ever see validated patterns.8c2a470eaRecord an email rule's baseline again when it is switched on.Rulegainsafter_update :seed_notification_baseline, if: :switched_on?(activegoing from false to true). When the rule has asend_email_notificationaction, it recordsmatching_transaction_idsthroughNotificationDelivery.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 withactive: no reader (the syncer,RuleJob) can see the rule on without its baseline. OnTimeoutErrorthe rule stays off (update_columns(active: false)),notification_baseline_timed_out?is set,RulesController#applyqueues noRuleJob, and#applyand#update(the toggle and the form) show the alertrules.notification_baseline_timed_outinstead 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, anda 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 onNotificationDeliveryand on enqueuedRuleEmailNotificationJob:- 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.
- switching on records the matches without emailing them (before the fix:
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: 1jobs); - the toggle alerts and stays off on a timeout, and switches on otherwise.
- Apply records the baseline before queuing
Mutations (each restored from the commit, each caught).
| Mutation | Caught by |
|---|---|
| Remove the NUL check | the null-byte tests in safe_regex_test.rb and both in condition_regex_test.rb |
| NUL check after the blank check | a pattern containing a null byte is invalid and never reaches the database ("\0" read as :blank) |
Remove the after_update | 9 tests: every model and controller positive and timeout test |
Fire on any change of active | switching a rule off records nothing |
| Fire whenever the rule is on | saving a rule that is already on does not record a baseline again |
| Drop the email-action guard | switching on a rule without an email action records nothing |
| Timeout leaves the rule on | the model timeout test, and both controller timeout tests |
| Timeout not flagged | the 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 anyway | apply leaves an email rule off and queues nothing when its baseline times out |
| Update always shows the success notice | the 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::ConditionFilteraddsstarts_with,ends_withandmatches_regexto the text operator list.- Starts with and ends with are
ILIKE, with the value passed throughsanitize_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. TransactionDetailsandTransactionTypekeep their own operator lists and do not gain these.
- Starts with and ends with are
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
\1to\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 sstatement_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_timeoutruns a block underSET LOCAL statement_timeoutinside a savepoint, restores the previous value, and raisesTimeoutErroronQueryCanceled.
- Back-references
Rule::Conditionaddsregex?,uses_regex?(which looks into compound conditions) and aregex_value_is_safevalidation.- 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_scopehandles rules with a regex condition. When any condition uses a regex, the matching ids are resolved under the 5 s execution timeout and returned asscope_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_countandRule#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?passesonly_id:, so its regex query runs on that one row.Rule#applyresolves its scope once and hands it to every action, so a rule with several actions scans once.
- Every reader goes through it:
RuleJobaddsdiscard_on Rule::SafeRegex::TimeoutErrorbesideretry_on Rule::Runner::LockBusy. The runner records the failedRuleRun, 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.ApplyRulesJobandApplyAllRulesJobdo not raise for a failing rule; the runner carries on with the next one.- Email baseline on a timeout.
Rule::Actionhandles 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.
Rulegainsafter_update :seed_notification_baseline, if: :switched_on?(activegoing 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_notificationaction. It runs inside the save's transaction, after the nested conditions are written, so the baseline uses the saved conditions and commits together withactive. - On a timeout the rule stays off,
RulesController#applyqueues 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.
- The callback records the rule's current matches as delivered when it has a
- Assistant rule tools (#3990):
RuleSupport#build_conditionkeeps a regex value as written; other values are still stripped. For example," shop$"stripped to"shop$"would also match "Workshop".get_rule_optionsreads the operator list from the filters, so it offers the new operators without a change, andpreview_rulecounts and samples regex matches throughmatching_scope.apply_ruleactivates withupdate!(active: true), as Apply does. When the email baseline times out, it now returns abaseline_timed_outerror and queues nothing, asRulesController#applydoes. Before, it queuedRuleJob, 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 inmodels/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 frommatching_scopeat the rule's turn in the runner. The runner's ownrescuerecords 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.RuleJobkeeps upstream'sretry_on LockBusyand adds thediscard_on. - #4163 (rename): the regex branch and
only_id:live inmatching_scope, which is now public;matching_resourcesdelegates to it. - #4109 (null bytes): this PR's own NUL check in
Rule::SafeRegexis removed in favour ofDatabaseTextValidator. On the plain merge a null byte was reported twice ("is invalid" and "is not a valid regular expression"), and malformed UTF-8 raisedArgumentErrorfromString#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_conditionandapply_rulechanges 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]pluskeep_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::Actionapplied: they pass (29 runs). Without the deletion, three tests fail.
- It does not touch
- #4150 (re-seed when the match criteria change) adds
after_update :seed_notification_baseline, if: :match_criteria_changed?toRule, 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
TimeoutErrorrescue 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 testat c9f239baf: 11,853 runs, 54,633 assertions, 0 failures, 0 errors, 34 skips.bin/rubocopon 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, withRule::SafeRegexremoved: 111 runs, 17 failures, 47 errors. Examples:UnsupportedOperatorError: Unsupported operator: starts_with, andNameError: 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
ApplyRulesJobgets 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. RuleJobfor 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.
- An active, stop-processing email rule at the top whose pattern times out under
- ReDoS and limits (
safe_regex_test.rb,condition_regex_test.rb,regex_execution_test.rb):- Back-references are refused, and
\\1is 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_timeoutraisesTimeoutErrorand 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.
- Back-references are refused, and
- 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_ruleon an email rule whose baseline times out leaves it off and queues nothing (before the fix: 0 jobs expected, but 1 were enqueued).
- Prefix and suffix match without mid-string hits, on name and on notes, and
- 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_countrescue, thematches_transaction?rescue, the action-baseline rescue, ordiscard_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_withfrom the operator list: 6 tests. Droppingmatches_regex: 28 tests. - Dropping the
only_id:narrowing: 2 tests. - Dropping the
DatabaseTextValidatorguard: the three invalid-text tests. - Binding with
where(id: ids): the bind test. - Stripping the regex in
build_condition, or removingapply_rule's timeout guard: one named test each. - The earlier 36 mutations, on 8c2a470ea, are in jaysbeekay/sure#366.
- Skipping the regex branch in
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'sget_rulesandapply_rule, and the auto-categorize cost estimate);total_affected_resource_count(apply-all confirmation);matching_transaction_ids(the email baseline, inRule::Actionand inRule's switch-on callback);matches_transaction?(Transaction::Ruleable#eligible_for_category_rule?, one transaction per call, so it passesonly_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 throughas_json(app/javascript/controllers/rule/conditions_controller.js),validate_operator, and the assistant'sbuild_conditionandget_rule_options;TransactionNameandTransactionNotes, which inherit the text list;TransactionDetailsandTransactionType, which override it and are deliberately unchanged.
The other writers of condition values:
RuleImport(CSV) andFamily::DataImporterbuild conditions throughRule::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), andRule::Action's timeout path (update_columns, which skips callbacks).