Rules: starts_with, ends_with, matches_regex and explicit priority (11.1, #130)
Summary
Part of #130 (11.1). Completes the 11.1 row of its triage plan: three new text operators for rule conditions, and an explicit run order for rules. Two of #130's exit criteria are covered here: the regex one and the priority one.
starts_with/ends_with/matches_regexon the name and notes conditions.matches_regexruns in Postgres (~*). Its matcher is not a backtracking engine:(a+)+$over 30,000 characters returns in under 1 ms (asserted insafe_regex_test.rb). The unsafe inputs are back-references (exponential) and patterns Postgres rejects only at execution (regular expression is too complex, unbalanced groups), which would leave a saved, active rule failing on every sync.Rule::SafeRegexrefuses back-references, blank and over-length (> 200) patterns, and probes Postgres once at save. Execution is bounded: a rule with a regex condition resolves its matching ids under a statement timeout.rules.priority(backfilled per family bycreated_at, id),Rule.prioritised(a total order),Rule#move, up/down controls on the rules index (default sort is now priority).
Scope and dependencies
- Issue: #130 (11.1)
- Parent PR/branch, if stacked: none, branched from
mainataf2c49c - Intentionally out of scope: drag-and-drop reordering; regex on
TransactionDetails(it keeps its own operator list); a case-sensitive regex flag; CSV rule export/import (positional columns, so imported rules are simply appended in file order); API index order (stayscreated_at, idfor stable pagination,priorityis exposed as a field).
Blast radius: who else hits these lines, and what do they pass?
OPERATORS_MAP["text"]is read byTransactionNameandTransactionNotesonly;TransactionDetails#operatorshard-codes its own list and is pinned unchanged by a test.Rule#matching_resources_scopeis reached byaffected_resource_count(confirm screens; a timeout reads as 0),total_affected_resource_count(same),matching_transaction_ids(unchanged, notification baseline) andapply(a timeout raises, soRuleJobrecords a failed run).family.rulesordering is reached by every runner:ApplyAllRulesJob,Family::Syncer#perform_post_sync,Financekit::Downstream. The last two used to enqueue oneRuleJobper active rule (any order, concurrent); both now enqueue one orderedApplyAllRulesJob(active_only: true, ignore_attribute_locks: false).ApplyAllRulesJobalso no longer stops at the first rule that raises;RuleJobhas already recorded the failed run.
Sibling grep (what else reads what changed)
| Reader | Handled? |
|---|---|
Family::DataExporter NDJSON / Family::DataImporter | carry priority; absent ⇒ appended |
API rule JSON, spec/swagger_helper.rb, docs/api/openapi.yaml | priority added (hunk applied by hand; regenerating also rewrote unrelated loan text already out of sync on main) |
Family::DataExporter CSV, RuleImport | deliberately unchanged, see above |
API index order | deliberately unchanged |
Rule.create_from_grouping | gets a priority from the create callback |
Behaviour to know about (decision for the owner). Rule actions do not lock what they write (only user edits and AI categorisation lock), so on every path the later rule overwrites the earlier one. Priority therefore means "runs earlier"; the rules page says so ("Rules run from top to bottom. When two rules set the same field on a transaction, the lower one wins."). The plan in #130 had this backwards (it said the first rule wins on the lock path); it was wrong and is corrected in the issue. If you would rather the top rule win, it is a one-line change to reverse the run order; say so.
Evidence checklist
- Each issue in this PR has its own acceptance criteria and no unrelated issue work is included.
- Contract rows touched by this change name existing tests. (not applicable: no portfolio contract rows)
- Any gate test has an observed failing mutation transcript attached. (not applicable: no gate test; mutation results below)
- Fixtures used as evidence assert internal consistency.
- Financial calculations use
BigDecimaland documented rounding points. (not applicable) - De-identification uses token-shape allowlists; no personal data is included.
- Files changed, decisions, tests/runtime, risks, and next unblocked issue are documented below.
Validation
Tests were written first and watched fail for the right reason (Unsupported operator, undefined method prioritised, unknown keywords: active_only, etc.).
Commands and results (Ruby 3.3.6 in this environment, repo pins 3.4.9; Postgres 16):
bin/rails test(full): 11427 runs, 49367 assertions, 4 failures, 1 error, 33 skips. The same 4 failures and 1 error occur on untouchedorigin/main(Settings::HostingsControllerTestx3 andProvider::RegistryTestbecauseANTHROPIC_BASE_URLis set in this environment;Provider::OpenaiTest#extra_headers_stringifies_nested_values_Ruby-stylebecause Ruby 3.3 and 3.4 print hashes differently). None touches rules.bin/rails test test/models/rule test/controllers/rules_controller_test.rb test/controllers/api/v1/rules_controller_test.rb test/models/family test/models/financekit: green.bin/rubocopon changed Ruby files: no offenses.erb_lintonrules/_ruleandrules/index: no errors.bin/brakeman --no-pager: no warnings.npm run lint(Biome) not run: no JavaScript changed andnode_modulesis not installed in this environment.- Checked against upstream
AGENTS.md(fetched fromwe-promise/suremainon 2026-10-01; identical to this fork's copy): tests via Minitest + fixtures, rswag only for docs,Current.family, i18n viat(), DS primitives and functional tokens, no new dependency, no migration run automatically (the migration was run once locally to regeneratedb/schema.rb; only its own hunks are committed).
Mutation pass (each change reverted, named test must fail):
| Change broken | Result |
|---|---|
Rule.apply_in_priority_order without prioritised | caught by rules run by priority, not by creation or physical order (an earlier version of the test passed on physical order alone; fixed) |
regex ids resolved without with_timeout | 6 failures in regex_execution_test.rb |
| back-reference check removed | back-references are refused fails |
| probe wrapper removed | error in safe_regex_test.rb |
sanitize_sql_like removed from starts/ends | wildcard test fails |
Rule::Condition validation removed | 6 failures in condition_regex_test.rb |
| syncer back to one job per rule | 2 failures (syncer_test, priority_test) |
A real defect found on the way: SET LOCAL statement_timeout survives a released savepoint, so the save-time probe would have left a 250 ms limit on the rest of the save's transaction. with_timeout now restores the previous value; with_timeout leaves the limit off once the block returns pins it.
Risks, blockers, and follow-up
- Which rule wins (see above) is a product decision, flagged for the owner.
- The post-sync pass now runs active rules sequentially in one job rather than in parallel jobs; correct for ordering, slower for families with many rules.
- Only the English locale carries the new strings (the other rules locale files already lack
does_not_containand fall back to English). - Migration adds a column with a default and an index to
rules, a small table; the backfill is a singleUPDATE. - Gatekeeper review fires automatically on this draft; it is not handled here.
Generated by Claude Code