The personal finance app for everyone (by everyone)
Ruby
Add starts with, ends with and regex rule operators (#4089)
jaysbeekay962c0026a883
diff --git a/app/controllers/rules_controller.rb b/app/controllers/rules_controller.rbindex dfd427b616..627689dcfe 100644--- a/app/controllers/rules_controller.rb+++ b/app/controllers/rules_controller.rb@@ -53,6 +53,13 @@ class RulesController < ApplicationControllerdef apply@rule.update!(active: true)++ # The rule stayed off, so running it now would only repeat the slow query.+ if @rule.notification_baseline_timed_out?+ redirect_back_or_to rules_path, alert: t("rules.notification_baseline_timed_out")+ return+ end+@rule.apply_later(ignore_attribute_locks: true)redirect_back_or_to rules_path, notice: "#{@rule.resource_type.humanize} rule activated"end@@ -70,9 +77,15 @@ class RulesController < ApplicationControllerdef updateif @rule.update(rule_params)+ flash_message = if @rule.notification_baseline_timed_out?+ { alert: t("rules.notification_baseline_timed_out") }+ else+ { notice: t(".success") }+ end+respond_to do |format|- format.html { redirect_back_or_to rules_path, notice: t(".success") }- format.turbo_stream { stream_redirect_back_or_to rules_path, notice: t(".success") }+ format.html { redirect_back_or_to rules_path, **flash_message }+ format.turbo_stream { stream_redirect_back_or_to rules_path, **flash_message }endelserender_invalid_rule :editdiff --git a/app/jobs/rule_job.rb b/app/jobs/rule_job.rbindex a8968e4cde..d19e4896f7 100644--- a/app/jobs/rule_job.rb+++ b/app/jobs/rule_job.rb@@ -5,6 +5,11 @@ class RuleJob < ApplicationJobretry_on Rule::Runner::LockBusy, wait: 30.seconds, attempts: 20+ # A pattern that timed out would time out again, so the failed run the runner+ # records is final: the job is not retried (a retry would also run every+ # active rule above this one again).+ discard_on Rule::SafeRegex::TimeoutError+def perform(rule, ignore_attribute_locks: false, execution_type: "manual")runner = Rule::Runner.new(rule.family,diff --git a/app/models/assistant/function/apply_rule.rb b/app/models/assistant/function/apply_rule.rbindex 529a7e339b..f06a6b2912 100644--- a/app/models/assistant/function/apply_rule.rb+++ b/app/models/assistant/function/apply_rule.rb@@ -78,7 +78,9 @@ class Assistant::Function::ApplyRule < Assistant::Functioncurrent = nilunchanged = falserule.with_lock do- current = rule.affected_resource_count+ # Not affected_resource_count, which reads a timeout as 0: a rule+ # previewed with no matches would then compare equal and be activated.+ current = rule.matching_scope.countunchanged = definition_digest(rule) == token["definition"] && current == token["match_count"]rule.update!(active: true) if unchangedend@@ -92,6 +94,16 @@ class Assistant::Function::ApplyRule < Assistant::Function)end+ # Activating an email rule records its current matches as delivered. If that+ # timed out the rule was left off, and running it now would email them all.+ if rule.notification_baseline_timed_out?+ return error(+ "baseline_timed_out",+ "The rule was not activated: checking which transactions it already matches took too long, and without that check its email action would send all of them. Simplify its conditions, preview it again and retry.",+ rule: serialize_rule(rule.reload)+ )+ end+rule.apply_later(ignore_attribute_locks: override_locked){@@ -101,5 +113,7 @@ class Assistant::Function::ApplyRule < Assistant::Functionoverride_locked: override_locked,message: "Rule activated and queued to apply to #{current} transactions. It will also run on future syncs."}+ rescue Rule::SafeRegex::TimeoutError+ regex_timeout_error(rule, "Nothing was applied.")endenddiff --git a/app/models/assistant/function/create_rule.rb b/app/models/assistant/function/create_rule.rbindex 36b4ddb980..d1eb76411b 100644--- a/app/models/assistant/function/create_rule.rb+++ b/app/models/assistant/function/create_rule.rb@@ -61,5 +61,7 @@ class Assistant::Function::CreateRule < Assistant::Functionpreview: preview(rule, sample_size: resolved_sample_size(params)),message: "Rule saved inactive. Check the preview, then call apply_rule with its preview_token to activate it."}+ rescue Rule::SafeRegex::TimeoutError+ regex_timeout_error(rule, "The rule was saved inactive.")endenddiff --git a/app/models/assistant/function/preview_rule.rb b/app/models/assistant/function/preview_rule.rbindex c582278fb0..aa44ec428c 100644--- a/app/models/assistant/function/preview_rule.rb+++ b/app/models/assistant/function/preview_rule.rb@@ -69,5 +69,7 @@ class Assistant::Function::PreviewRule < Assistant::Functionend{ success: true, rule: serialize_rule(rule), preview: preview(rule, sample_size: resolved_sample_size(params)) }+ rescue Rule::SafeRegex::TimeoutError+ regex_timeout_error(rule, "Nothing was changed.")endenddiff --git a/app/models/assistant/function/rule_support.rb b/app/models/assistant/function/rule_support.rbindex fc16f24607..4cfb00642f 100644--- a/app/models/assistant/function/rule_support.rb+++ b/app/models/assistant/function/rule_support.rb@@ -176,7 +176,9 @@ module Assistant::Function::RuleSupportif Rule::ConditionFilter::VALUELESS_OPERATORS.include?(operator)value = nilelse- value = value.to_s.strip+ # A pattern is kept as written, as the rule form keeps it: its spaces are+ # part of what it matches.+ value = Rule::ConditionFilter::REGEX_OPERATORS.include?(operator) ? value.to_s : value.to_s.stripreturn [ "#{path}: value is required for operator '#{operator}'." ] if value.blank?return [ "#{path}: value must be a number." ] if filter.type == "number" && !numeric?(value)@@ -460,4 +462,17 @@ module Assistant::Function::RuleSupportdef error(key, message, **extra){ success: false, error: key, message: message }.merge(extra)end++ # A pattern can outlive the statement timeout (Rule::SafeRegex), which+ # raises out of the rule's scope. Reported as a rule error the assistant can+ # explain; the tool wrapper would otherwise call it an unexpected failure.+ # `outcome` says what did happen to the rule first.+ def regex_timeout_error(rule, outcome)+ error(+ "regex_timeout",+ "#{outcome} Checking which transactions it matches took too long, so there is no preview and it can't be applied. " \+ "Simplify its pattern, or add a condition that narrows it, then preview it again.",+ rule: serialize_rule(rule)+ )+ endenddiff --git a/app/models/assistant/function/update_rule.rb b/app/models/assistant/function/update_rule.rbindex 67cf4aed73..632e1fa318 100644--- a/app/models/assistant/function/update_rule.rb+++ b/app/models/assistant/function/update_rule.rb@@ -95,5 +95,7 @@ class Assistant::Function::UpdateRule < Assistant::Functionpreview: preview(rule, sample_size: resolved_sample_size(params)),message: message}+ rescue Rule::SafeRegex::TimeoutError+ regex_timeout_error(rule, was_active && !rule.active ? "The rule was updated and deactivated." : "The rule was updated.")endenddiff --git a/app/models/rule.rb b/app/models/rule.rbindex 9ae2218398..4a87e26392 100644--- a/app/models/rule.rb+++ b/app/models/rule.rb@@ -32,6 +32,53 @@ class Rule < ApplicationRecordvalidate :min_actionsvalidate :no_duplicate_actions+ # Switching a rule on records the transactions it already matches as delivered,+ # so an email action only reports what appears afterwards. Rule::Action seeds the+ # same baseline when the action is created, but a rule switched off and on again+ # (by the toggle, the form, Apply or an import) would otherwise email every match+ # from before, including those from while it was off.+ #+ # after_update, not after_update_commit: it runs inside the save's transaction,+ # after the nested conditions and actions are written, so the baseline is taken+ # from the conditions as saved and is committed together with `active`. Nothing+ # can see the rule switched on without its baseline. Declared after the nested+ # attributes so it runs after their autosave. A new rule needs no callback:+ # creating its email action seeds the baseline.+ after_update :seed_notification_baseline, if: :switched_on?++ # Set when this save's after_update took the baseline, or tried to and timed+ # out. Rule::Action's commit callback for an email action added in the same+ # save then skips its own, which would run the query again and, on a timeout,+ # switch off a rule that has its baseline. Reset at the start of every save.+ before_save :reset_notification_baseline_taken++ def notification_baseline_taken_in_this_save?+ @notification_baseline_taken == true+ end++ # True when the last save asked to switch the rule on, or gave it an email+ # action, but the baseline query timed out, so the rule was left off.+ def notification_baseline_timed_out?+ @notification_baseline_timed_out == true+ end++ # Without a baseline the next run would email every past match, so the rule+ # is switched off. Rule::Action calls this from its commit callback, on the+ # rule the save went through (the controller's), so the response can say so.+ # Recorded in the debug log, where support can see why the rule went off.+ def notification_baseline_timed_out!(error, source:)+ @notification_baseline_timed_out = true+ update_columns(active: false)+ DebugLogEntry.capture(+ category: "rule_notification",+ level: "warn",+ message: "Notification baseline timed out; rule switched off",+ source: source,+ family: family,+ metadata: { rule_id: id, rule_name: name, error_class: error.class.name, error_message: error.message }+ )+ end+def action_executorsregistry.action_executorsend@@ -49,8 +96,12 @@ class Rule < ApplicationRecordendend+ # Display-only: a pattern that times out reads as zero here, and the failure+ # surfaces where the rule actually runs (#apply).def affected_resource_countmatching_scope.count+ rescue Rule::SafeRegex::TimeoutError+ 0end# Reads the currently-matching transaction ids WITHOUT running executors@@ -105,8 +156,13 @@ class Rule < ApplicationRecordend# Whether this rule's conditions currently match the given transaction.+ #+ # A pattern that times out matches nothing here, as it does when the rule runs:+ # the rule cannot categorize the transaction, so the prompt is still offered.def matches_transaction?(transaction)- matching_scope.where(id: transaction.id).exists?+ matching_scope(only_id: transaction.id).exists?+ rescue Rule::SafeRegex::TimeoutError+ falseend# The transactions this rule currently matches, as a relation (e.g. for the@@ -137,6 +193,8 @@ class Rule < ApplicationRecordtransaction_ids = Set.newrules.each do |rule|transaction_ids.merge(rule.matching_scope.pluck(:id))+ rescue Rule::SafeRegex::TimeoutError+ nextendtransaction_ids.size@@ -200,8 +258,12 @@ class Rule < ApplicationRecordendend- def matching_scope+ # `only_id` narrows the match to one resource inside the query itself, so a+ # check on a single transaction runs any pattern on that row alone rather+ # than on the whole family.+ def matching_scope(only_id: nil)scope = registry.resource_scope+ scope = scope.where(id: only_id) if only_id# 1. Prepare the query with joins required by conditionsconditions.each do |condition|@@ -213,7 +275,13 @@ class Rule < ApplicationRecordscope = condition.apply(scope)end- scope+ # A pattern is the one condition whose cost the database cannot bound by+ # itself, so its matches are resolved here, under a statement timeout, and+ # the scope returned is those ids. Every reader gets the timeout, and a+ # caller such as Rule::Runner sees it as this rule failing.+ return scope unless conditions.any?(&:uses_regex?)++ scope_for_transaction_ids(Rule::SafeRegex.with_timeout { scope.pluck(:id) })endprivate@@ -258,6 +326,27 @@ class Rule < ApplicationRecordendend+ def switched_on?+ saved_change_to_active?(from: false, to: true)+ end++ def seed_notification_baseline+ @notification_baseline_timed_out = false+ return unless actions.exists?(action_type: "send_email_notification")++ @notification_baseline_taken = true+ NotificationDelivery.record_for(rule_id: id, transaction_ids: matching_transaction_ids)+ rescue Rule::SafeRegex::TimeoutError => e+ # As in Rule::Action#seed_notification_baseline: without a baseline the next+ # run would email every past match, so the rule stays off. The timed-out query+ # ran in its own savepoint, so the rest of the save still commits.+ notification_baseline_timed_out!(e, source: self.class.name)+ end++ def reset_notification_baseline_taken+ @notification_baseline_taken = false+ end+def normalize_namereturn unless name.is_a?(String)return unless name.valid_encoding?diff --git a/app/models/rule/action.rb b/app/models/rule/action.rbindex 30d48e902f..5d39cba9c7 100644--- a/app/models/rule/action.rb+++ b/app/models/rule/action.rb@@ -93,10 +93,17 @@ class Rule::Action < ApplicationRecorddef seed_notification_baselinereturn unless action_type == "send_email_notification"+ return if rule.notification_baseline_taken_in_this_save?NotificationDelivery.record_for(rule_id: rule_id,transaction_ids: rule.matching_transaction_ids)+ rescue Rule::SafeRegex::TimeoutError => e+ # The action is already committed. With no baseline, leaving the rule on would+ # email every past match on its next run, so it is switched off instead; the+ # user can turn it back on after changing the pattern. Through the rule, so+ # an update that saved this action reports the switch-off, not success.+ rule.notification_baseline_timed_out!(e, source: self.class.name)endenddiff --git a/app/models/rule/condition.rb b/app/models/rule/condition.rbindex 416a097b20..1374c9def0 100644--- a/app/models/rule/condition.rb+++ b/app/models/rule/condition.rb@@ -20,6 +20,8 @@ class Rule::Condition < ApplicationRecordif: -> { value.to_s.valid_encoding? }validates_with DatabaseTextValidator, attributes: %i[condition_type operator value]+ validate :regex_value_is_safe, if: :regex_value_changed?+accepts_nested_attributes_for :sub_conditions, allow_destroy: true# We don't store rule_id on sub_conditions, so "walk up" to the parent rule@@ -31,6 +33,21 @@ class Rule::Condition < ApplicationRecordcondition_type == "compound"end+ def regex?+ Rule::ConditionFilter::REGEX_OPERATORS.include?(operator)+ end++ # True when this condition, or any condition nested in it, matches a pattern.+ def uses_regex?+ compound? ? sub_conditions.any?(&:regex?) : regex?+ end++ # Probing costs a database round trip, so an untouched condition (a rule being+ # toggled active, say) is not probed again.+ def regex_value_changed?+ regex? && (new_record? || will_save_change_to_value? || will_save_change_to_operator?)+ end+def apply(scope)if compound?build_compound_scope(scope)@@ -74,6 +91,19 @@ class Rule::Condition < ApplicationRecordendprivate+ # A blank value is already reported by the presence validation, and one the+ # database will not store (a null byte, malformed UTF-8) by+ # DatabaseTextValidator. Neither can be probed: the driver refuses to send it.+ def regex_value_is_safe+ return unless DatabaseTextValidator.acceptable?(value)+ return if value.blank?++ error = Rule::SafeRegex.error_for(value)+ return if error.nil?++ errors.add(:value, :"regex_#{error}", count: Rule::SafeRegex::MAX_LENGTH)+ end+def normalize_legacy_condition_typereturn unless condition_type.is_a?(String) && condition_type.valid_encoding?return if condition_type.blank?diff --git a/app/models/rule/condition_filter.rb b/app/models/rule/condition_filter.rbindex 2c3ee2f51f..05b7d31588 100644--- a/app/models/rule/condition_filter.rb+++ b/app/models/rule/condition_filter.rb@@ -3,6 +3,11 @@ class Rule::ConditionFilterTYPES = [ "text", "number", "select" ]+ # Operators whose value is a pattern, not text. The pattern is bound as given,+ # and matched against the column as stored: collapsing whitespace on either+ # side would change what it matches (a run of spaces, a tab, `^\s`).+ REGEX_OPERATORS = [ "matches_regex" ].freeze+# Operators that don't require a value (and that the form hides the value field for)VALUELESS_OPERATORS = [ "is_null", "is_not_null" ].freeze@@ -10,6 +15,9 @@ class Rule::ConditionFilter"text" => [[ :contains, "like" ],[ :does_not_contain, "not_like" ],+ [ :starts_with, "starts_with" ],+ [ :ends_with, "ends_with" ],+ [ :matches_regex, "matches_regex" ],[ :equal_to, "=" ],[ :not_equal_to, "!=" ],[ :is_empty, "is_null" ],@@ -102,10 +110,20 @@ class Rule::ConditionFilter"#{field} #{sanitize_operator(operator)}")else- normalized_value = normalize_value(value)- normalized_field = normalize_field(field)+ regex = REGEX_OPERATORS.include?(operator)+ normalized_value = regex ? value.to_s : normalize_value(value)+ normalized_field = regex ? field : normalize_field(field)++ if operator == "starts_with" || operator == "ends_with"+ sanitize_operator(operator)+ like_value = ActiveRecord::Base.sanitize_sql_like(normalized_value)+ like_value = operator == "starts_with" ? "#{like_value}%" : "%#{like_value}"- if operator == "like" || operator == "not_like"+ ActiveRecord::Base.sanitize_sql_for_conditions([+ "#{normalized_field} ILIKE ?",+ like_value+ ])+ elsif operator == "like" || operator == "not_like"sanitized_value = "%#{ActiveRecord::Base.sanitize_sql_like(normalized_value)}%"expression = ActiveRecord::Base.sanitize_sql_for_conditions(["#{normalized_field} #{sanitize_operator(operator)} ?",@@ -132,6 +150,8 @@ class Rule::ConditionFilter"ILIKE"when "not_like""NOT ILIKE"+ when "matches_regex"+ "~*"when "is_null""IS NULL"when "is_not_null"diff --git a/app/models/rule/runner.rb b/app/models/rule/runner.rbindex f45de71984..678d70e002 100644--- a/app/models/rule/runner.rb+++ b/app/models/rule/runner.rb@@ -147,6 +147,16 @@ class Rule::Runnererrors << errorerror_message = "#{error.class}: #{error.message}"Rails.logger.error("Rule::Runner failed for rule #{rule.id}: #{error_message}")+ # A failed rule, such as a pattern that timed out, is the user's to fix, so+ # support sees it in the debug log as RuleRun#fail_job! records its own.+ DebugLogEntry.capture(+ category: "rule_run",+ level: "error",+ message: "Rule run failed: #{error_message}",+ source: self.class.name,+ family: rule.family,+ metadata: { rule_id: rule.id, rule_name: rule.name, execution_type: execution_type, error_class: error.class.name, error_message: error.message }+ )if rule_runrule_run.update(status: "failed", error_message: error_message)diff --git a/app/models/rule/safe_regex.rb b/app/models/rule/safe_regex.rbnew file mode 100644index 0000000000..458f94908b--- /dev/null+++ b/app/models/rule/safe_regex.rb@@ -0,0 +1,104 @@+# Guards the `matches_regex` rule operator.+#+# The pattern runs inside Postgres (`~*`), not in Ruby, so the rules are+# Postgres' own (Advanced Regular Expressions). Its matcher is not a+# backtracking engine: nested quantifiers such as `(a+)+$` stay linear. Two+# things are not safe, and this class closes both:+#+# * back-references (`\1`..`\9`), which are exponential in Postgres' engine,+# are refused outright;+# * patterns Postgres will not compile (`parentheses () not balanced`,+# `regular expression is too complex`) only fail when a query runs them, which+# would put a saved, active rule into a failing state on every sync. They are+# probed once, at save. The pattern must be one the database can store:+# Rule::Condition leaves a null byte or malformed UTF-8 to+# DatabaseTextValidator and never probes it.+#+# Execution is bounded as well: #with_timeout runs a block under a Postgres+# `statement_timeout` and raises TimeoutError, so a rule cannot hold a worker or+# a request open.+class Rule::SafeRegex+ MAX_LENGTH = 200+ PROBE_TIMEOUT_MS = 1_000+ EXECUTION_TIMEOUT_MS = 5_000++ TimeoutError = Class.new(StandardError)++ # An escape is a backslash and the character after it. Reading them in pairs+ # keeps an escaped backslash followed by a digit (`\\1`) from reading as a+ # back-reference.+ ESCAPE_PAIR = /\\./m++ # @param pattern [String, nil] the pattern a user wrote+ # @return [Symbol, nil] nil when safe, otherwise one of :blank, :too_long,+ # :backreference, :invalid, :too_complex+ def self.error_for(pattern)+ new(pattern).error+ end++ # Runs the block with Postgres' statement_timeout set for its duration only.+ #+ # SET LOCAL lasts until the end of the outermost transaction, and a rule's+ # validation runs inside the save's transaction. Releasing a savepoint does+ # not undo it, so the previous limit is put back explicitly; a failure rolls+ # the savepoint back, which undoes it.+ #+ # @param milliseconds [Integer]+ # @raise [TimeoutError] when the database cancels the statement+ def self.with_timeout(milliseconds = EXECUTION_TIMEOUT_MS)+ connection = ActiveRecord::Base.connection+ connection.transaction(requires_new: true) do+ previous = connection.select_value("SHOW statement_timeout")+ connection.execute(set_timeout_sql(Integer(milliseconds)))+ result = yield+ connection.execute(set_timeout_sql(previous))+ result+ end+ rescue ActiveRecord::QueryCanceled+ raise TimeoutError, "regular expression exceeded #{milliseconds} ms"+ end++ # SET takes no bind parameters, so the value is quoted into the statement.+ def self.set_timeout_sql(value)+ ActiveRecord::Base.sanitize_sql_array([ "SET LOCAL statement_timeout = ?", value ])+ end+ private_class_method :set_timeout_sql++ def initialize(pattern)+ @pattern = pattern.to_s+ end++ def error+ return :blank if pattern.strip.empty?+ return :too_long if pattern.length > MAX_LENGTH+ return :backreference if backreference?++ compile_error+ end++ private+ attr_reader :pattern++ def backreference?+ pattern.scan(ESCAPE_PAIR).any? { |escape| escape.match?(/\A\\[1-9]\z/) }+ end++ # Postgres compiles the pattern before it looks at the subject, so an empty+ # subject is enough to surface a pattern it rejects.+ def compile_error+ self.class.with_timeout(PROBE_TIMEOUT_MS) do+ ActiveRecord::Base.connection.select_value(+ ActiveRecord::Base.sanitize_sql_array([ "SELECT '' ~* ?", pattern ])+ )+ end+ nil+ rescue TimeoutError+ :too_complex+ rescue ActiveRecord::StatementInvalid => e+ # Only Postgres' own verdict on the pattern (SQLSTATE 2201B) is a bad pattern;+ # a lost connection or an aborted transaction is not the user's mistake.+ raise unless e.cause.is_a?(PG::InvalidRegularExpression)++ :invalid+ end+enddiff --git a/config/locales/models/rule/en.yml b/config/locales/models/rule/en.ymlindex d869dc0d1e..716b652635 100644--- a/config/locales/models/rule/en.yml+++ b/config/locales/models/rule/en.yml@@ -7,6 +7,13 @@ en:min_actions: "must have at least one action"duplicate_actions: "Rule cannot have duplicate actions %{types}"nested_conditions: "Compound conditions cannot be nested"+ rule/condition:+ attributes:+ value:+ regex_invalid: "is not a valid regular expression"+ regex_too_complex: "is too complex to run safely"+ regex_too_long: "is too long (maximum is %{count} characters)"+ regex_backreference: "cannot use back-references (\\1 to \\9)"rule:conditions:unsupported_label: "Unsupported (%{type})"diff --git a/config/locales/views/rules/en.yml b/config/locales/views/rules/en.ymlindex e1811065c6..9c689cc344 100644--- a/config/locales/views/rules/en.yml+++ b/config/locales/views/rules/en.yml@@ -3,6 +3,7 @@ en:rules:no_action: No Actionno_condition: No condition+ notification_baseline_timed_out: This rule is still off. Checking which transactions it already matches took too long, and without that check it would email all of them. Simplify its conditions, then turn it on again.category_rule_cta:close: Closecreate_rule: Create rule@@ -121,6 +122,9 @@ en:operators:contains: Containsdoes_not_contain: Does not contain+ starts_with: Starts with+ ends_with: Ends with+ matches_regex: Matches regexequal_to: Equal tois_equal_to: Is equal tonot_equal_to: Not equal todiff --git a/test/controllers/rules_controller_test.rb b/test/controllers/rules_controller_test.rbindex dc7c99f79a..72a33ebaed 100644--- a/test/controllers/rules_controller_test.rb+++ b/test/controllers/rules_controller_test.rb@@ -1,6 +1,7 @@require "test_helper"class RulesControllerTest < ActionDispatch::IntegrationTest+ include EntriesTestHelpersetup dosign_in @user = users(:family_admin)end@@ -564,6 +565,81 @@ class RulesControllerTest < ActionDispatch::IntegrationTestassert_not rule.reload.active?end+ test "switching on an email rule records its baseline before queuing the run" do+ rule = email_rule_for(@user.family)++ assert_difference -> { NotificationDelivery.where(rule: rule).count }, 1 do+ assert_enqueued_with(job: RuleJob) { post apply_rule_url(rule) }+ end++ assert rule.reload.active?+ end++ test "apply leaves an email rule off and queues nothing when its baseline times out" do+ rule = email_rule_for(@user.family)+ Rule::SafeRegex.stubs(:with_timeout).raises(Rule::SafeRegex::TimeoutError)++ assert_no_enqueued_jobs(only: RuleJob) { post apply_rule_url(rule) }++ assert_redirected_to rules_url+ assert_equal I18n.t("rules.notification_baseline_timed_out"), flash[:alert]+ assert_nil flash[:notice]+ assert_not rule.reload.active?+ end++ test "the active toggle leaves an email rule off and says why when its baseline times out" do+ rule = email_rule_for(@user.family)+ Rule::SafeRegex.stubs(:with_timeout).raises(Rule::SafeRegex::TimeoutError)++ patch rule_url(rule), params: { rule: { active: "1" } }, as: :turbo_stream++ assert_response :success+ assert_equal I18n.t("rules.notification_baseline_timed_out"), flash[:alert]+ assert_nil flash[:notice]+ assert_not rule.reload.active?+ end++ # Rule::Action takes an email action's baseline in its commit callback, after+ # the update has saved. When that query times out the rule is switched off,+ # and the update must say so rather than report success.+ test "changing an action to an email action says the rule was switched off when its baseline times out" do+ rule = active_rule_without_email_for(@user.family)+ action = rule.actions.first+ Rule::SafeRegex.stubs(:with_timeout).raises(Rule::SafeRegex::TimeoutError)++ patch rule_url(rule), params: { rule: { actions_attributes: { "0" => { id: action.id, action_type: "send_email_notification" } } } }++ assert_equal I18n.t("rules.notification_baseline_timed_out"), flash[:alert]+ assert_nil flash[:notice]+ assert_equal "send_email_notification", action.reload.action_type+ assert_not rule.reload.active?+ end++ test "changing an action to an email action keeps the rule on and reports success when its baseline is recorded" do+ rule = active_rule_without_email_for(@user.family)+ action = rule.actions.first++ assert_difference -> { NotificationDelivery.where(rule: rule).count }, 1 do+ patch rule_url(rule), params: { rule: { actions_attributes: { "0" => { id: action.id, action_type: "send_email_notification" } } } }+ end++ assert_equal I18n.t("rules.update.success"), flash[:notice]+ assert_nil flash[:alert]+ assert rule.reload.active?+ end++ test "the active toggle switches an email rule on when its baseline is recorded" do+ rule = email_rule_for(@user.family)++ assert_difference -> { NotificationDelivery.where(rule: rule).count }, 1 do+ patch rule_url(rule), params: { rule: { active: "1" } }, as: :turbo_stream+ end++ assert_equal I18n.t("rules.update.success"), flash[:notice]+ assert_nil flash[:alert]+ assert rule.reload.active?+ end+test "member can create rule" dosign_in users(:family_member)@@ -633,4 +709,33 @@ class RulesControllerTest < ActionDispatch::IntegrationTestassert_match "connection refused", entry.messageassert_equal "connection refused", entry.metadata["error_message"]end++ private+ # A regex condition, so a stubbed timeout reaches the baseline query, and one+ # matching transaction, so a recorded baseline is visible as a delivery.+ # An active regex rule with one match and no email action yet.+ def active_rule_without_email_for(family)+ account = family.accounts.create!(name: "Baseline", balance: 1000, currency: "USD", accountable: Depository.new)+ create_transaction(date: Date.current, account: account, name: "Baseline match zq")++ Rule.create!(+ family: family, resource_type: "transaction", active: true,+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "matches_regex", value: "baseline match zq") ],+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ]+ )+ end++ # An inactive email rule with one match that arrived after the rule was+ # created, so only switching it on records that match as delivered. (Creating+ # an email action records the matches it already has.)+ def email_rule_for(family)+ account = family.accounts.create!(name: "Baseline", balance: 1000, currency: "USD", accountable: Depository.new)+ rule = Rule.create!(+ family: family, resource_type: "transaction", active: false,+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "matches_regex", value: "baseline match zq") ],+ actions: [ Rule::Action.new(action_type: "send_email_notification") ]+ )+ create_transaction(date: Date.current, account: account, name: "Baseline match zq")+ rule+ endenddiff --git a/test/models/assistant/function/apply_rule_test.rb b/test/models/assistant/function/apply_rule_test.rbindex 7fa1ae5606..f5517e3bde 100644--- a/test/models/assistant/function/apply_rule_test.rb+++ b/test/models/assistant/function/apply_rule_test.rb@@ -31,6 +31,27 @@ class Assistant::Function::ApplyRuleTest < ActiveSupport::TestCaseassert_equal 1, @rule.rule_runs.countend+ # Activating a rule with an email action records its current matches as+ # delivered. If that times out the rule stays off (Rule#seed_notification_baseline),+ # and queuing the run anyway would email every past match.+ test "an email rule whose baseline times out on activation stays off and is not queued" do+ create_transaction(name: "ZXQ Coffee Shop")+ @rule.actions.create!(action_type: "send_email_notification")+ NotificationDelivery.where(rule: @rule).delete_all+ token = preview_token+ Rule.any_instance.stubs(:matching_transaction_ids).raises(Rule::SafeRegex::TimeoutError)++ result = nil+ assert_no_enqueued_jobs only: RuleJob do+ result = @fn.call("rule_id" => @rule.id, "preview_token" => token)+ end++ assert_not result[:success]+ assert_equal "baseline_timed_out", result[:error]+ assert_not @rule.reload.active+ assert_equal 0, NotificationDelivery.where(rule: @rule).count+ end+test "the match count from get_rules alone cannot apply a rule" docreate_transaction(name: "ZXQ Coffee Shop")match_count = Assistant::Function::GetRules.new(@user).call("rule_id" => @rule.id)[:rule][:match_count]@@ -149,6 +170,41 @@ class Assistant::Function::ApplyRuleTest < ActiveSupport::TestCaseassert_equal "ai_action", @fn.call("rule_id" => @rule.id, "preview_token" => "x")[:error]end+ # The match count reads as zero when the pattern times out, so the token no+ # longer agrees and the stale branch previews the rule again. That preview+ # times out too: nothing is applied, and the error says why.+ test "a pattern that times out at apply time applies nothing and reports a regex_timeout error" do+ create_transaction(name: "ZXQ Coffee Shop")+ token = preview_token+ Rule.any_instance.stubs(:matching_scope).raises(Rule::SafeRegex::TimeoutError)++ result = nil+ assert_no_enqueued_jobs only: RuleJob do+ result = @fn.call("rule_id" => @rule.id, "preview_token" => token)+ end++ assert_not result[:success]+ assert_equal "regex_timeout", result[:error]+ assert_match "Nothing was applied", result[:message]+ assert_not @rule.reload.active+ end++ # A rule matching nothing is previewed with a match count of 0. A timeout at+ # apply time must not read as that same 0 and activate the rule.+ test "a rule previewed with no matches that times out at apply time is not activated" do+ preview = Assistant::Function::PreviewRule.new(@user).call("rule_id" => @rule.id)[:preview]+ assert_equal 0, preview[:match_count]+ Rule.any_instance.stubs(:matching_scope).raises(Rule::SafeRegex::TimeoutError)++ result = nil+ assert_no_enqueued_jobs only: RuleJob do+ result = @fn.call("rule_id" => @rule.id, "preview_token" => preview[:preview_token])+ end++ assert_equal "regex_timeout", result[:error]+ assert_not @rule.reload.active+ end+privatedef preview_tokentoken = Assistant::Function::PreviewRule.new(@user).call("rule_id" => @rule.id)[:preview][:preview_token]diff --git a/test/models/assistant/function/create_rule_test.rb b/test/models/assistant/function/create_rule_test.rbindex 9ac02bd6f3..82b033ac27 100644--- a/test/models/assistant/function/create_rule_test.rb+++ b/test/models/assistant/function/create_rule_test.rb@@ -92,4 +92,24 @@ class Assistant::Function::CreateRuleTest < ActiveSupport::TestCaseassert_equal "invalid_rule", member_fn.call(params)[:error]assert @fn.call(params)[:success]end++ # The rule is saved before the preview runs, so a timeout there must still+ # say the rule exists, inactive.+ test "a pattern that times out in the preview reports the saved rule with a regex_timeout error" do+ Rule.any_instance.stubs(:matching_scope).raises(Rule::SafeRegex::TimeoutError)++ result = nil+ assert_difference "Rule.count", 1 do+ result = @fn.call(+ "conditions" => [ { "condition_type" => "transaction_name", "operator" => "matches_regex", "value" => "zxq" } ],+ "actions" => [ { "action_type" => "set_transaction_category", "value" => @category.id } ]+ )+ end++ assert_not result[:success]+ assert_equal "regex_timeout", result[:error]+ assert_match "saved", result[:message]+ assert_equal Rule.order(:created_at).last.id, result[:rule][:id]+ assert_not result[:rule][:active]+ endenddiff --git a/test/models/assistant/function/preview_rule_test.rb b/test/models/assistant/function/preview_rule_test.rbindex 704dc514f1..4ed0b7d507 100644--- a/test/models/assistant/function/preview_rule_test.rb+++ b/test/models/assistant/function/preview_rule_test.rb@@ -59,6 +59,40 @@ class Assistant::Function::PreviewRuleTest < ActiveSupport::TestCaseassert_equal 1, @fn.call(params.merge("effective_date" => 5.days.ago.to_date.iso8601))[:preview][:match_count]end+ test "previews the text operators: a regex, starts with and ends with" do+ coffee = create_transaction(name: "ZXQ Coffee Shop")+ tea = create_transaction(name: "ZXQ Tea House")+ create_transaction(name: "Groceries ZXQ")++ regex = @fn.call(definition(conditions: [ { "condition_type" => "transaction_name", "operator" => "matches_regex", "value" => "^zxq (coffee|tea)" } ]))+ assert regex[:success], regex.inspect+ assert_equal 2, regex[:preview][:match_count]+ assert_equal [ coffee, tea ].map { |e| e.entryable.id }.sort, regex[:preview][:sample].map { |t| t[:id] }.sort++ assert_equal 2, @fn.call(definition(conditions: [ { "condition_type" => "transaction_name", "operator" => "starts_with", "value" => "zxq" } ]))[:preview][:match_count]+ assert_equal 1, @fn.call(definition(conditions: [ { "condition_type" => "transaction_name", "operator" => "ends_with", "value" => "zxq" } ]))[:preview][:match_count]+ end++ # Stripping " shop$" to "shop$" would also match "Workshop".+ test "a regex value is previewed as written, spaces included" do+ create_transaction(name: "ZXQ Coffee Shop")+ create_transaction(name: "ZXQ Workshop")++ result = @fn.call(definition(conditions: [ { "condition_type" => "transaction_name", "operator" => "matches_regex", "value" => " shop$" } ]))++ assert result[:success], result.inspect+ assert_equal 1, result[:preview][:match_count]+ assert_equal " shop$", result[:rule][:conditions].first[:value]+ end++ test "a regex the database will not compile is a problem, not a preview" do+ result = @fn.call(definition(conditions: [ { "condition_type" => "transaction_name", "operator" => "matches_regex", "value" => "(" } ]))++ assert_not result[:success]+ assert_equal "invalid_rule", result[:error]+ assert_equal [ "Conditions value is not a valid regular expression" ], result[:problems]+ end+test "rejects invalid definitions with every problem listed" doresult = @fn.call(definition(conditions: [@@ -117,6 +151,21 @@ class Assistant::Function::PreviewRuleTest < ActiveSupport::TestCaseassert_equal [ visible.entryable.id ], result[:preview][:sample].map { |t| t[:id] }end+ # A pattern that outlives the statement timeout raises out of the rule's+ # scope. The assistant gets a rule error it can explain, not "failed+ # unexpectedly" from the tool wrapper.+ test "a pattern that times out is reported as a regex_timeout error" do+ rule = @family.rules.create!(resource_type: "transaction", **rule_attributes)+ Rule.any_instance.stubs(:matching_scope).raises(Rule::SafeRegex::TimeoutError)++ result = @fn.call("rule_id" => rule.id)++ assert_not result[:success]+ assert_equal "regex_timeout", result[:error]+ assert_equal rule.id, result[:rule][:id]+ assert_nil result[:preview]+ end+privatedef rule_attributes{diff --git a/test/models/assistant/function/update_rule_test.rb b/test/models/assistant/function/update_rule_test.rbindex 2590fe500c..3bfd25a254 100644--- a/test/models/assistant/function/update_rule_test.rb+++ b/test/models/assistant/function/update_rule_test.rb@@ -96,4 +96,18 @@ class Assistant::Function::UpdateRuleTest < ActiveSupport::TestCaseassert result[:success], result.inspectassert result.dig(:preview, :preview_token).present?end++ test "a pattern that times out in the preview reports the updated rule with a regex_timeout error" do+ Rule.any_instance.stubs(:matching_scope).raises(Rule::SafeRegex::TimeoutError)++ result = @fn.call("rule_id" => @rule.id, "conditions" => [+ { "condition_type" => "transaction_name", "operator" => "matches_regex", "value" => "zxq" }+ ])++ assert_not result[:success]+ assert_equal "regex_timeout", result[:error]+ assert_match "updated", result[:message]+ assert_equal [ "zxq" ], @rule.reload.conditions.map(&:value)+ assert_not result[:rule][:active]+ endenddiff --git a/test/models/rule/condition_filter/text_operators_test.rb b/test/models/rule/condition_filter/text_operators_test.rbnew file mode 100644index 0000000000..f6f261456e--- /dev/null+++ b/test/models/rule/condition_filter/text_operators_test.rb@@ -0,0 +1,120 @@+require "test_helper"++# starts_with / ends_with / matches_regex on the text filters. The boundary that+# matters is what each one does NOT match: a prefix operator must not behave+# like `contains`, and LIKE wildcards in the user's value must stay literal.+class Rule::ConditionFilter::TextOperatorsTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @family = families(:empty)+ @rule = rules(:one)+ @account = @family.accounts.create!(+ name: "Operators test", balance: 1000, currency: "USD", accountable: Depository.new+ )+ end++ test "starts_with matches the prefix and not a mid-string occurrence" do+ prefix = create_transaction(account: @account, name: "Uber Eats order")+ mid = create_transaction(account: @account, name: "Not Uber Eats")++ matched = matching_names(condition_type: "transaction_name", operator: "starts_with", value: "uber")++ assert_includes matched, prefix.name+ assert_not_includes matched, mid.name+ end++ test "ends_with matches the suffix and not a mid-string occurrence" do+ suffix = create_transaction(account: @account, name: "Monthly Netflix")+ mid = create_transaction(account: @account, name: "Netflix monthly")++ matched = matching_names(condition_type: "transaction_name", operator: "ends_with", value: "netflix")++ assert_includes matched, suffix.name+ assert_not_includes matched, mid.name+ end++ test "starts_with and ends_with treat LIKE wildcards in the value literally" do+ literal = create_transaction(account: @account, name: "50% off store")+ other = create_transaction(account: @account, name: "500 off store")++ matched = matching_names(condition_type: "transaction_name", operator: "starts_with", value: "50%")++ assert_includes matched, literal.name+ assert_not_includes matched, other.name++ underscore = create_transaction(account: @account, name: "shop_1")+ wildcard_hit = create_transaction(account: @account, name: "shopX1")++ matched = matching_names(condition_type: "transaction_name", operator: "ends_with", value: "p_1")++ assert_includes matched, underscore.name+ assert_not_includes matched, wildcard_hit.name+ end++ test "starts_with ignores the whitespace the stored name collected" do+ padded = create_transaction(account: @account, name: " Coffee Shop")++ matched = matching_names(condition_type: "transaction_name", operator: "starts_with", value: "Coffee Shop")++ assert_includes matched, padded.name+ end++ test "starts_with and ends_with also work on notes" do+ entry = create_transaction(account: @account, name: "Plain")+ entry.update!(notes: "Reimbursable trip")++ assert_equal [ "Plain" ], matching_names(condition_type: "transaction_notes", operator: "starts_with", value: "reimb")+ assert_equal [ "Plain" ], matching_names(condition_type: "transaction_notes", operator: "ends_with", value: "TRIP")+ assert_empty matching_names(condition_type: "transaction_notes", operator: "ends_with", value: "reimb")+ end++ test "matches_regex matches case-insensitively and anchors are honoured" do+ hit = create_transaction(account: @account, name: "AMZN Mktp US*2K4")+ miss = create_transaction(account: @account, name: "Not AMZN Mktp")++ matched = matching_names(condition_type: "transaction_name", operator: "matches_regex", value: '^amzn\s+mktp')++ assert_includes matched, hit.name+ assert_not_includes matched, miss.name+ end++ # The other text operators collapse whitespace on both sides. A pattern is+ # left as written on both sides instead, so it sees the name as stored.+ test "matches_regex compares the pattern and the name without whitespace normalisation" do+ create_transaction(account: @account, name: "A B")++ assert_equal [ "A B" ], matching_names(condition_type: "transaction_name", operator: "matches_regex", value: "A B")+ assert_empty matching_names(condition_type: "transaction_name", operator: "matches_regex", value: "A B")+ assert_equal [ "A B" ], matching_names(condition_type: "transaction_name", operator: "like", value: "A B"),+ "contains still ignores the difference"+ end++ test "the text type offers the new operators" do+ operators = Rule::ConditionFilter::OPERATORS_MAP.fetch("text").map(&:last)++ assert_includes operators, "starts_with"+ assert_includes operators, "ends_with"+ assert_includes operators, "matches_regex"+ end++ test "the transaction name and notes filters offer them, details and number filters do not" do+ %w[transaction_name transaction_notes].each do |key|+ offered = @rule.registry.get_filter!(key).operators.map(&:last)+ assert_includes offered, "matches_regex", key+ end++ details = @rule.registry.get_filter!("transaction_details").operators.map(&:last)+ assert_equal %w[like = is_null], details++ amount = @rule.registry.get_filter!("transaction_amount").operators.map(&:last)+ assert_not_includes amount, "starts_with"+ end++ private+ def matching_names(condition_type:, operator:, value:)+ condition = Rule::Condition.new(rule: @rule, condition_type: condition_type, operator: operator, value: value)+ scope = condition.prepare(@account.transactions)+ condition.apply(scope).includes(:entry).map { |t| t.entry.name }.uniq+ end+enddiff --git a/test/models/rule/condition_regex_test.rb b/test/models/rule/condition_regex_test.rbnew file mode 100644index 0000000000..25e24c6d7a--- /dev/null+++ b/test/models/rule/condition_regex_test.rb@@ -0,0 +1,100 @@+require "test_helper"++# A matches_regex condition is validated when it is saved, so an unsafe pattern+# never reaches a rule that runs on every sync.+class Rule::ConditionRegexTest < ActiveSupport::TestCase+ setup do+ @family = families(:empty)+ end++ test "a rule with a valid regex condition saves" do+ rule = build_rule(value: '^amzn\s+mktp')++ assert_difference -> { @family.rules.count }, 1 do+ assert rule.save, rule.errors.full_messages.to_sentence+ end+ end++ {+ "a back-reference" => [ '(a*)*\1c', :regex_backreference ],+ "an unbalanced group" => [ "(", :regex_invalid ],+ "a pattern Postgres calls too complex" => [ "^(a{1,255}){1,255}(b)", :regex_invalid ],+ "an over-long pattern" => [ "a" * 201, :regex_too_long ]+ }.each do |description, (pattern, kind)|+ test "a rule with #{description} is rejected and nothing is saved" do+ rule = build_rule(value: pattern)++ assert_no_difference [ -> { @family.rules.count }, -> { Rule::Condition.count } ] do+ assert_not rule.save+ end++ assert rule.conditions.first.errors.of_kind?(:value, kind), rule.conditions.first.errors.details.inspect+ end+ end++ # The database driver will not send a string holding a null byte or malformed+ # UTF-8 (ArgumentError), so probing one would raise out of validation. Such a+ # value is DatabaseTextValidator's to report, once, and is never probed.+ {+ "a null byte" => "ab\u0000c",+ "a lone null byte" => "\u0000",+ "malformed UTF-8" => "ab\xFFc".dup.force_encoding(Encoding::UTF_8)+ }.each do |description, pattern|+ test "a regex with #{description} is rejected as invalid text without a probe, and nothing is saved" do+ rule = build_rule(value: pattern)+ Rule::SafeRegex.expects(:error_for).never++ assert_no_difference [ -> { @family.rules.count }, -> { Rule::Condition.count } ] do+ assert_not rule.save+ end++ assert_equal [ { error: :invalid } ], rule.conditions.first.errors.details[:value]+ assert_equal [ "Value is invalid" ], rule.conditions.first.errors.full_messages+ end+ end++ test "the same pattern is accepted under the contains operator" do+ rule = build_rule(value: "(", operator: "like")++ assert rule.save, rule.errors.full_messages.to_sentence+ end++ test "a sub-condition inside a compound condition is validated too" do+ rule = @family.rules.build(resource_type: "transaction", actions: [ Rule::Action.new(action_type: "exclude_transaction") ])+ compound = rule.conditions.build(condition_type: "compound", operator: "or")+ compound.sub_conditions.build(condition_type: "transaction_name", operator: "matches_regex", value: "(")++ assert_no_difference -> { @family.rules.count } do+ assert_not rule.save+ end+ end++ test "the validation does not run for other operators" do+ Rule::SafeRegex.expects(:error_for).never++ assert build_rule(value: "(", operator: "like").save+ end++ test "an unchanged regex condition is not probed again when its rule is saved" do+ rule = build_rule(value: "^amzn")+ rule.save!++ Rule::SafeRegex.expects(:error_for).never+ rule.update!(active: true)+ # Saving the rule leaves an unchanged condition unvalidated by itself, so the+ # condition is also saved directly: its own validations always run.+ rule.conditions.first.save!++ Rule::SafeRegex.expects(:error_for).with("^changed").returns(nil).once+ rule.conditions.first.update!(value: "^changed")+ end++ private+ def build_rule(value:, operator: "matches_regex")+ @family.rules.build(+ resource_type: "transaction",+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: operator, value: value) ],+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ]+ )+ end+enddiff --git a/test/models/rule/notification_baseline_on_enable_test.rb b/test/models/rule/notification_baseline_on_enable_test.rbnew file mode 100644index 0000000000..87b7fc89e5--- /dev/null+++ b/test/models/rule/notification_baseline_on_enable_test.rb@@ -0,0 +1,211 @@+require "test_helper"++# A rule with an email action records its current matches as already delivered+# when it is switched on, so turning a rule back on emails only what appears+# afterwards. Rule::Action seeds the same baseline when the action is created,+# but that does not cover a rule that was switched off and on again: the matches+# from before (or while it was off) would all be emailed on its next run.+#+# Every rule built here starts without a baseline, which is the state this guards+# against: email_rule deletes any baseline the action recorded when it was created,+# so these tests hold whether or not creating the action seeds one.+class Rule::NotificationBaselineOnEnableTest < ActiveSupport::TestCase+ include EntriesTestHelper, ActiveJob::TestHelper++ setup do+ @family = families(:empty)+ @account = @family.accounts.create!(name: "Baseline", balance: 1000, currency: "USD", accountable: Depository.new)+ @hit = create_transaction(date: Date.current, account: @account, name: "AMZN Mktp US").transaction+ @miss = create_transaction(date: Date.current, account: @account, name: "Corner shop").transaction+ end++ test "switching on a rule with an email action records its matches without emailing them" do+ rule = email_rule++ assert_difference -> { NotificationDelivery.where(rule: rule).count }, 1 do+ assert_no_enqueued_jobs(only: RuleEmailNotificationJob) { rule.update!(active: true) }+ end+ assert_equal [ @hit.id ], NotificationDelivery.where(rule: rule).pluck(:transaction_id)++ assert_no_enqueued_jobs(only: RuleEmailNotificationJob) { rule.apply }+ end++ test "a match that appears after the rule is switched on is still emailed" do+ rule = email_rule+ rule.update!(active: true)+ later = create_transaction(date: Date.current, account: @account, name: "AMZN Prime").transaction++ assert_enqueued_with(job: RuleEmailNotificationJob, args: [ rule.id, [ later.id ] ]) { rule.apply }+ end++ test "the baseline is taken from the conditions saved in the same form submit" do+ rule = email_rule+ condition = rule.conditions.first++ rule.update!(active: true, conditions_attributes: [ { id: condition.id, value: "corner" } ])++ assert_equal [ @miss.id ], NotificationDelivery.where(rule: rule).pluck(:transaction_id)+ end++ test "a condition removed in the same form submit does not narrow the baseline" do+ rule = email_rule+ rule.conditions.create!(condition_type: "transaction_name", operator: "like", value: "nothing matches this")++ rule.update!(active: true, conditions_attributes: [ { id: rule.conditions.last.id, _destroy: "1" } ])++ assert_equal [ @hit.id ], NotificationDelivery.where(rule: rule).pluck(:transaction_id)+ end++ test "switching on a rule without an email action records nothing" do+ rule = Rule.create!(+ family: @family, resource_type: "transaction",+ conditions: [ name_condition("amzn") ],+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ]+ )+ Rule.any_instance.expects(:matching_transaction_ids).never++ assert_no_difference -> { NotificationDelivery.count } do+ rule.update!(active: true)+ end+ assert rule.reload.active?+ end++ test "saving a rule that is already on does not record a baseline again" do+ rule = email_rule+ rule.update_columns(active: true)++ assert_no_difference -> { NotificationDelivery.count } do+ rule.update!(name: "Renamed")+ end+ end++ test "switching a rule off records nothing" do+ rule = email_rule+ rule.update_columns(active: true)++ assert_no_difference -> { NotificationDelivery.count } do+ rule.update!(active: false)+ end+ end++ test "a baseline that times out on switch-on leaves the rule off and the rest of the save in place" do+ rule = email_rule(condition: Rule::Condition.new(condition_type: "transaction_name", operator: "matches_regex", value: "amzn"))+ Rule::SafeRegex.stubs(:with_timeout).raises(Rule::SafeRegex::TimeoutError)++ assert_difference -> { DebugLogEntry.where(category: "rule_notification").count }, 1 do+ assert_nothing_raised { rule.update!(active: true, name: "Renamed") }+ end++ assert rule.notification_baseline_timed_out?+ entry = DebugLogEntry.where(category: "rule_notification").last+ assert_equal "warn", entry.level+ assert_equal @family, entry.family+ assert_equal rule.id, entry.metadata["rule_id"]+ rule.reload+ assert_not rule.active?, "a rule without a baseline would email every past match"+ assert_equal "Renamed", rule.name+ assert_equal 0, NotificationDelivery.where(rule: rule).count+ end++ test "a baseline that is recorded does not report a timeout" do+ rule = email_rule++ assert_no_difference -> { DebugLogEntry.where(category: "rule_notification").count } do+ rule.update!(active: true)+ end++ assert_not rule.notification_baseline_timed_out?+ assert rule.reload.active?+ end++ # Switching a rule on and adding its email action in one save takes the+ # baseline once, in Rule's callback. The action's commit callback must not+ # check again: a timeout there would switch off a rule that has its baseline.+ # (after_create_commit does not fire under transactional tests, so it is+ # invoked directly.)+ test "switching on and adding the email action in one save is baselined once" do+ rule = Rule.create!(+ family: @family, resource_type: "transaction", active: false,+ conditions: [ name_condition("amzn") ],+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ]+ )++ assert_difference -> { NotificationDelivery.where(rule: rule).count }, 1 do+ rule.update!(active: true, actions_attributes: [ { action_type: "send_email_notification" } ])+ end+ action = rule.actions.find { |a| a.action_type == "send_email_notification" }+ assert_same rule, action.rule, "the action must see the rule the save went through"++ rule.stubs(:matching_transaction_ids).raises(Rule::SafeRegex::TimeoutError)+ assert_no_difference -> { DebugLogEntry.where(category: "rule_notification").count } do+ action.send(:seed_notification_baseline)+ end++ assert rule.reload.active?, "the rule already has its baseline"+ end++ test "a combined save whose baseline times out is reported once and leaves the rule off" do+ rule = Rule.create!(+ family: @family, resource_type: "transaction", active: false,+ conditions: [ name_condition("amzn") ],+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ]+ )+ rule.stubs(:matching_transaction_ids).raises(Rule::SafeRegex::TimeoutError)++ assert_difference -> { DebugLogEntry.where(category: "rule_notification").count }, 1 do+ rule.update!(active: true, actions_attributes: [ { action_type: "send_email_notification" } ])+ rule.actions.find { |a| a.action_type == "send_email_notification" }.send(:seed_notification_baseline)+ end++ assert rule.notification_baseline_timed_out?+ assert_not rule.reload.active?+ end++ # The marker belongs to one save. A later save that takes no baseline clears+ # it, so an email action added after that still seeds its own.+ test "an email action added after a later save still takes its baseline" do+ rule = email_rule+ rule.update!(active: true)+ assert rule.notification_baseline_taken_in_this_save?+ rule.update!(name: "Renamed")+ NotificationDelivery.where(rule: rule).delete_all++ action = rule.actions.create!(action_type: "send_email_notification")++ assert_difference -> { NotificationDelivery.where(rule: rule).count }, 1 do+ action.send(:seed_notification_baseline)+ end+ end++ # Rule's callback runs on update only, so a rule created already on relies on+ # its email action for the baseline. The column defaults to false, so this+ # save also reads as active changing from false to true.+ test "a rule created already on still takes its baseline from the email action" do+ rule = Rule.create!(+ family: @family, resource_type: "transaction", active: true,+ conditions: [ name_condition("amzn") ],+ actions: [ Rule::Action.new(action_type: "send_email_notification") ]+ )+ NotificationDelivery.where(rule: rule).delete_all+ assert rule.saved_change_to_active?(from: false, to: true), "precondition: the create reads as a switch-on"++ assert_difference -> { NotificationDelivery.where(rule: rule).count }, 1 do+ rule.actions.first.send(:seed_notification_baseline)+ end+ end++ private+ def email_rule(condition: name_condition("amzn"))+ rule = Rule.create!(+ family: @family, resource_type: "transaction", active: false,+ conditions: [ condition ],+ actions: [ Rule::Action.new(action_type: "send_email_notification") ]+ )+ NotificationDelivery.where(rule: rule).delete_all+ rule+ end++ def name_condition(value)+ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: value)+ end+enddiff --git a/test/models/rule/regex_execution_test.rb b/test/models/rule/regex_execution_test.rbnew file mode 100644index 0000000000..d20d3bcedb--- /dev/null+++ b/test/models/rule/regex_execution_test.rb@@ -0,0 +1,346 @@+require "test_helper"++# A regex rule runs under a statement timeout. The matching ids are resolved+# inside that bound and the actions then run on those ids, so the unbounded part+# of the rule (the pattern) is the only part that is limited.+class Rule::RegexExecutionTest < ActiveSupport::TestCase+ include EntriesTestHelper, ActiveJob::TestHelper++ setup do+ @family = families(:empty)+ @account = @family.accounts.create!(name: "Regex run", balance: 1000, currency: "USD", accountable: Depository.new)+ @category = @family.categories.create!(name: "Shopping")+ @hit = create_transaction(date: Date.current, account: @account, name: "AMZN Mktp US")+ @miss = create_transaction(date: Date.current, account: @account, name: "Corner shop")+ end++ test "a regex rule applies to the matching rows only" do+ rule = regex_rule('^amzn\s')++ assert_equal 1, rule.apply++ assert_equal @category, @hit.reload.transaction.category+ assert_nil @miss.reload.transaction.category+ end++ # A pattern is bound as written, so it is matched against the name as stored:+ # collapsing the name's whitespace would leave a pattern that spells out a+ # run of spaces, a tab or an edge with nothing to match.+ test "a regex matches the name as stored, whitespace included" do+ spaced = create_transaction(date: Date.current, account: @account, name: "POS PURCHASE 4411")+ edged = create_transaction(date: Date.current, account: @account, name: " Leading space")++ assert_equal [ spaced.entryable_id ], regex_rule("POS PURCHASE").matching_scope.pluck(:id)+ assert_equal [ spaced.entryable_id ], regex_rule('POS\s{2}PURCHASE').matching_scope.pluck(:id)+ assert_equal [ edged.entryable_id ], regex_rule('^\sleading').matching_scope.pluck(:id)+ end++ test "a regex with one space does not match a name holding two" do+ create_transaction(date: Date.current, account: @account, name: "POS PURCHASE 4411")++ assert_empty regex_rule("POS PURCHASE").matching_scope.pluck(:id)+ assert_equal 1, regex_rule('POS\s+PURCHASE').matching_scope.count+ end++ test "a regex rule resolves its matches under the timeout" do+ rule = regex_rule("amzn")++ Rule::SafeRegex.expects(:with_timeout).yields.once++ rule.apply+ end++ test "a rule without a regex condition does not use the timeout" do+ rule = Rule.create!(+ family: @family, resource_type: "transaction",+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "amzn") ],+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @category.id) ]+ )++ Rule::SafeRegex.expects(:with_timeout).never++ assert_equal 1, rule.apply+ end++ # Rule#apply resolves its scope once and hands it to every action, so a broad+ # pattern is scanned (and materialised) once, not once per action.+ test "a regex is resolved once per apply however many actions the rule has" do+ rule = Rule.create!(+ family: @family, resource_type: "transaction",+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "matches_regex", value: "amzn") ],+ actions: [+ Rule::Action.new(action_type: "set_transaction_category", value: @category.id),+ Rule::Action.new(action_type: "exclude_transaction")+ ]+ )+ calls = 0+ Rule::SafeRegex.stubs(:with_timeout).with { |*| calls += 1; true }.yields.returns([ @hit.transaction.id ])++ rule.apply++ assert_equal 1, calls+ assert_equal @category, @hit.reload.transaction.category+ assert @hit.reload.excluded?, "the second action ran on the resolved match"+ end++ test "a later apply resolves the pattern again" do+ rule = regex_rule("amzn")+ calls = 0+ Rule::SafeRegex.stubs(:with_timeout).with { |*| calls += 1; true }.yields.returns([ @hit.transaction.id ])++ rule.apply+ rule.apply++ assert_equal 2, calls+ end++ test "a read after an apply resolves the pattern again" do+ rule = regex_rule("amzn")+ calls = 0+ Rule::SafeRegex.stubs(:with_timeout).with { |*| calls += 1; true }.yields.returns([ @hit.transaction.id ])++ rule.apply+ rule.matching_transaction_ids++ assert_equal 2, calls+ end++ # No stub on the timeout itself: a scope that really sleeps in Postgres is cancelled by+ # the statement timeout, and the error comes out of Rule#apply as TimeoutError.+ test "a regex rule whose match query outlives the limit is cancelled by Postgres and raises from apply" do+ rule = regex_rule("amzn")+ slow = rule.registry.resource_scope.where("(SELECT pg_sleep(1)) IS NOT NULL")+ Rule::Condition.any_instance.stubs(:apply).returns(slow)+ original = Rule::SafeRegex::EXECUTION_TIMEOUT_MS+ Rule::SafeRegex.send(:remove_const, :EXECUTION_TIMEOUT_MS)+ Rule::SafeRegex.const_set(:EXECUTION_TIMEOUT_MS, 30)++ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)+ assert_raises(Rule::SafeRegex::TimeoutError) { rule.apply }+ assert_operator Process.clock_gettime(Process::CLOCK_MONOTONIC) - started, :<, 0.9, "the query ran to completion instead of being cancelled"+ ensure+ Rule::SafeRegex.send(:remove_const, :EXECUTION_TIMEOUT_MS)+ Rule::SafeRegex.const_set(:EXECUTION_TIMEOUT_MS, original)+ end++ test "a regex inside a compound condition is also bounded" do+ rule = Rule.new(family: @family, resource_type: "transaction",+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @category.id) ])+ compound = rule.conditions.build(condition_type: "compound", operator: "or")+ compound.sub_conditions.build(condition_type: "transaction_name", operator: "matches_regex", value: "amzn")+ rule.save!++ Rule::SafeRegex.expects(:with_timeout).yields.once++ rule.apply+ end++ test "a timeout is raised from apply so the run is recorded as failed" do+ rule = regex_rule("amzn")+ Rule::SafeRegex.stubs(:with_timeout).raises(Rule::SafeRegex::TimeoutError)++ assert_raises(Rule::SafeRegex::TimeoutError) { rule.apply }++ assert_nil @hit.reload.transaction.category+ end++ # Rule::Runner records the failed run and RuleJob re-raises the requested rule's+ # error so the job is marked failed. For a timeout that would make Sidekiq retry+ # it, and the retry would time out again (and re-run every active rule above),+ # so the job is discarded instead; the failed run is the record of it.+ test "RuleJob records a failed run when the pattern times out, and does not raise for a retry" do+ rule = regex_rule("amzn")+ Rule::SafeRegex.stubs(:with_timeout).raises(Rule::SafeRegex::TimeoutError)++ assert_difference -> { rule.rule_runs.where(status: "failed").count }, 1 do+ assert_nothing_raised { RuleJob.perform_now(rule) }+ end+ end++ test "a rule whose pattern times out does not count as covering a transaction" do+ rule = regex_rule("amzn")+ Rule::SafeRegex.stubs(:with_timeout).raises(Rule::SafeRegex::TimeoutError)++ assert_not rule.matches_transaction?(@hit.transaction)+ end++ test "a regex rule reports whether it covers a transaction" do+ rule = regex_rule('^amzn\s')++ assert rule.matches_transaction?(@hit.transaction)+ assert_not rule.matches_transaction?(@miss.transaction)+ end++ # The prompt check asks about one transaction. Resolving the family's every+ # match first and then looking for that id scans the whole family per prompt.+ test "a regex rule's prompt check runs the pattern on that transaction only" do+ rule = regex_rule('^amzn\s')+ target = @hit.transaction++ queries = []+ callback = ->(*, payload) { queries << payload unless payload[:name] == "SCHEMA" }+ ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do+ assert rule.matches_transaction?(target)+ end++ regex_queries = queries.select { |payload| payload[:sql].include?("~*") }+ assert_equal 1, regex_queries.size, "the pattern runs once"++ regex_query = regex_queries.first+ assert_match(/"transactions"\."id" = (\$\d+|'#{target.id}')/, regex_query[:sql], "the regex query is filtered to one id")+ assert_includes Array(regex_query[:type_casted_binds]) + [ regex_query[:sql] ], target.id+ end++ test "the confirmation counts are 0 rather than an error when the pattern times out" do+ rule = regex_rule("amzn")+ Rule::SafeRegex.stubs(:with_timeout).raises(Rule::SafeRegex::TimeoutError)++ assert_equal 0, rule.affected_resource_count+ assert_equal 0, Rule.total_affected_resource_count([ rule ])+ end++ test "ApplyAllRulesJob carries on with the next rule after one times out" do+ slow = regex_rule("amzn", name: "slow")+ fine = Rule.create!(+ family: @family, resource_type: "transaction", name: "fine",+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "shop") ],+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @category.id) ]+ )+ Rule::SafeRegex.stubs(:with_timeout).raises(Rule::SafeRegex::TimeoutError)++ assert_nothing_raised { ApplyAllRulesJob.perform_now(@family) }++ assert_equal 1, slow.rule_runs.where(status: "failed").count+ assert_equal 1, fine.rule_runs.where(status: "success").count+ assert_equal @category, @miss.reload.transaction.category+ end++ test "an email-notification action whose baseline times out is still created, and the rule is switched off" do+ rule = regex_rule("amzn")+ rule.update!(active: true)+ Rule::SafeRegex.stubs(:with_timeout).raises(Rule::SafeRegex::TimeoutError)++ # after_create_commit does not fire under transactional tests, so the seeding+ # path is invoked directly (as send_email_notification_test.rb does).+ action = rule.actions.create!(action_type: "send_email_notification")+ assert_difference -> { DebugLogEntry.where(category: "rule_notification").count }, 1 do+ assert_nothing_raised { action.send(:seed_notification_baseline) }+ end+ assert_equal rule.id, DebugLogEntry.where(category: "rule_notification").last.metadata["rule_id"]++ # No baseline was recorded, so leaving the rule on would email every past match.+ assert_not rule.reload.active?+ assert_equal 0, NotificationDelivery.where(rule_id: rule.id).count+ assert action.persisted?+ end++ # Resolved ids go back into the query as one array parameter, as Rule::Runner+ # passes them (Rule#scope_for_transaction_ids). One bind per id would break past+ # PostgreSQL's 65,535-parameter limit on a broad pattern.+ test "a regex rule's matches are bound as one parameter however many there are" do+ rule = regex_rule("amzn|shop")+ one = bind_count { regex_rule("amzn").affected_resource_count }+ two = bind_count { assert_equal 2, rule.affected_resource_count }++ assert_equal one, two+ end++ # The ordered run (Rule::Runner) reads each rule's matches at its turn. A pattern+ # that times out fails that turn only: it claims and stops nothing, the rules+ # below it still run in order, and the timed-out rule sends no email.+ test "a pattern that times out in the ordered run fails its own turn only" do+ other = @family.categories.create!(name: "Other")+ timed_out = regex_rule("amzn", name: "timed out", active: true, stop_processing: true, email: true)+ stopper = ordered_rule("stopper", condition: name_condition("like", "amzn"), stop_processing: true,+ action: Rule::Action.new(action_type: "set_transaction_category", value: other.id))+ below = ordered_rule("below", condition: name_condition("is_not_null", nil),+ action: Rule::Action.new(action_type: "exclude_transaction"))+ assert_equal [ timed_out, stopper, below ].map(&:id), @family.rules.ordered.pluck(:id)+ Rule::SafeRegex.stubs(:with_timeout).raises(Rule::SafeRegex::TimeoutError)++ assert_no_difference -> { NotificationDelivery.where(rule: timed_out).count } do+ assert_no_enqueued_jobs(only: RuleEmailNotificationJob) do+ # One debug-log entry, for the one rule that failed.+ assert_difference -> { DebugLogEntry.where(category: "rule_run").count }, 1 do+ assert_nothing_raised { ApplyRulesJob.perform_now(@family) }+ end+ end+ end++ entry = DebugLogEntry.where(category: "rule_run").last+ assert_equal timed_out.id, entry.metadata["rule_id"]+ assert_equal @family, entry.family+ assert_equal [ "failed" ], timed_out.rule_runs.pluck(:status)+ assert_match "TimeoutError", timed_out.rule_runs.first.error_message+ assert_equal [ "success" ], stopper.rule_runs.pluck(:status)+ assert_equal [ "success" ], below.rule_runs.pluck(:status)+ assert_equal other, @hit.reload.transaction.category, "the rule below the timed-out one decided"+ assert_not @hit.reload.excluded?, "stop processing still held for the rule below"+ assert @miss.reload.excluded?+ end++ test "applying a rule below a pattern that times out records that failure and runs the rule" do+ timed_out = regex_rule("amzn", name: "timed out", active: true, stop_processing: true)+ below = ordered_rule("below", condition: name_condition("is_not_null", nil),+ action: Rule::Action.new(action_type: "exclude_transaction"))+ Rule::SafeRegex.stubs(:with_timeout).raises(Rule::SafeRegex::TimeoutError)++ assert_nothing_raised { RuleJob.perform_now(below) }++ assert_equal [ "failed" ], timed_out.rule_runs.pluck(:status)+ assert_equal [ "success" ], below.rule_runs.pluck(:status)+ assert @hit.reload.excluded?, "the timed-out rule above stopped nothing"+ end++ # The other half of the timeout contract: an email rule whose baseline timed out+ # when it was switched on is left off, so the sync's ordered run skips it even+ # once the pattern runs in time again, and its history is never emailed.+ test "an email rule left off by a timed-out baseline is skipped by the sync run" do+ rule = regex_rule("amzn", email: true)+ Rule::SafeRegex.stubs(:with_timeout).raises(Rule::SafeRegex::TimeoutError)+ rule.update!(active: true)+ assert_not rule.reload.active?+ Rule::SafeRegex.unstub(:with_timeout)++ assert_no_enqueued_jobs(only: RuleEmailNotificationJob) do+ assert_no_difference -> { RuleRun.where(rule: rule).count } do+ ApplyRulesJob.perform_now(@family)+ end+ end+ assert_equal 0, NotificationDelivery.where(rule: rule).count+ end++ private+ def regex_rule(pattern, name: nil, active: false, stop_processing: false, email: false)+ actions = [ Rule::Action.new(action_type: "set_transaction_category", value: @category.id) ]+ actions << Rule::Action.new(action_type: "send_email_notification") if email++ rule = Rule.create!(+ family: @family, resource_type: "transaction", name: name, active: active, stop_processing: stop_processing,+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "matches_regex", value: pattern) ],+ actions: actions+ )+ # A create-time baseline (if the action records one) is cleared, so each+ # test states the baseline it relies on.+ NotificationDelivery.where(rule: rule).delete_all+ rule+ end++ def ordered_rule(name, condition:, action:, stop_processing: false)+ Rule.create!(+ family: @family, resource_type: "transaction", name: name, active: true, stop_processing: stop_processing,+ conditions: [ condition ], actions: [ action ]+ )+ end++ def name_condition(operator, value)+ Rule::Condition.new(condition_type: "transaction_name", operator: operator, value: value)+ end++ def bind_count+ binds = []+ callback = ->(*, payload) { binds << Array(payload[:binds]).size if payload[:sql].include?("COUNT") }+ ActiveSupport::Notifications.subscribed(callback, "sql.active_record") { yield }+ binds.last+ end+enddiff --git a/test/models/rule/safe_regex_test.rb b/test/models/rule/safe_regex_test.rbnew file mode 100644index 0000000000..4d5245014c--- /dev/null+++ b/test/models/rule/safe_regex_test.rb@@ -0,0 +1,74 @@+require "test_helper"++class Rule::SafeRegexTest < ActiveSupport::TestCase+ test "an ordinary pattern is accepted" do+ assert_nil Rule::SafeRegex.error_for('^amzn\s+mktp')+ assert_nil Rule::SafeRegex.error_for("(coffee|tea) shop$")+ end++ test "a nested-quantifier pattern is accepted because Postgres runs it in linear time" do+ assert_nil Rule::SafeRegex.error_for("(a+)+$")++ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)+ matched = ActiveRecord::Base.connection.select_value(+ ActiveRecord::Base.sanitize_sql_array([ "SELECT ? ~* ?", "#{'a' * 30_000}b", "(a+)+$" ])+ )+ elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started++ assert_equal false, matched+ assert_operator elapsed, :<, 1.0+ end++ test "blank and whitespace-only patterns are refused" do+ assert_equal :blank, Rule::SafeRegex.error_for(nil)+ assert_equal :blank, Rule::SafeRegex.error_for(" ")+ end++ test "length is capped at the boundary" do+ assert_nil Rule::SafeRegex.error_for("a" * Rule::SafeRegex::MAX_LENGTH)+ assert_equal :too_long, Rule::SafeRegex.error_for("a" * (Rule::SafeRegex::MAX_LENGTH + 1))+ end++ test "back-references are refused" do+ assert_equal :backreference, Rule::SafeRegex.error_for('(a*)*\1c')+ assert_equal :backreference, Rule::SafeRegex.error_for('(x)(y)\2')+ end++ test "an escaped backslash followed by a digit is not a back-reference" do+ assert_nil Rule::SafeRegex.error_for('a\\\\1')+ end++ test "a pattern Postgres rejects is refused at save time, not at run time" do+ assert_equal :invalid, Rule::SafeRegex.error_for("(")+ assert_equal :invalid, Rule::SafeRegex.error_for("[a-")+ end++ test "a pattern Postgres calls too complex is refused" do+ assert_equal :invalid, Rule::SafeRegex.error_for("^(a{1,255}){1,255}(b)")+ end++ test "a database error that is not a regex error is not reported as an invalid pattern" do+ ActiveRecord::Base.connection.stubs(:select_value).raises(ActiveRecord::StatementInvalid.new("connection lost"))++ assert_raises(ActiveRecord::StatementInvalid) { Rule::SafeRegex.error_for("abc") }+ end++ test "a failed probe inside an open transaction does not poison it" do+ ActiveRecord::Base.transaction do+ assert_equal :invalid, Rule::SafeRegex.error_for("(")+ assert_equal 1, ActiveRecord::Base.connection.select_value("SELECT 1")+ end+ end++ test "with_timeout raises TimeoutError when the statement outlives the limit" do+ assert_raises(Rule::SafeRegex::TimeoutError) do+ Rule::SafeRegex.with_timeout(20) { ActiveRecord::Base.connection.execute("SELECT pg_sleep(1)") }+ end+ end++ test "with_timeout leaves the limit off once the block returns" do+ Rule::SafeRegex.with_timeout(20) { ActiveRecord::Base.connection.execute("SELECT 1") }++ assert_nothing_raised { ActiveRecord::Base.connection.execute("SELECT pg_sleep(0.05)") }+ end+end