Rules: starts_with, ends_with, matches_regex and explicit priority (11.1, #130)

Merged
JA
2mo ago
+1319-37

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_regex on the name and notes conditions.
  • matches_regex runs in Postgres (~*). Its matcher is not a backtracking engine: (a+)+$ over 30,000 characters returns in under 1 ms (asserted in safe_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::SafeRegex refuses 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 by created_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 main at af2c49c
  • 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 (stays created_at, id for stable pagination, priority is exposed as a field).

Blast radius: who else hits these lines, and what do they pass?

  • OPERATORS_MAP["text"] is read by TransactionName and TransactionNotes only; TransactionDetails#operators hard-codes its own list and is pinned unchanged by a test.
  • Rule#matching_resources_scope is reached by affected_resource_count (confirm screens; a timeout reads as 0), total_affected_resource_count (same), matching_transaction_ids (unchanged, notification baseline) and apply (a timeout raises, so RuleJob records a failed run).
  • family.rules ordering is reached by every runner: ApplyAllRulesJob, Family::Syncer#perform_post_sync, Financekit::Downstream. The last two used to enqueue one RuleJob per active rule (any order, concurrent); both now enqueue one ordered ApplyAllRulesJob(active_only: true, ignore_attribute_locks: false). ApplyAllRulesJob also no longer stops at the first rule that raises; RuleJob has already recorded the failed run.

Sibling grep (what else reads what changed)

ReaderHandled?
Family::DataExporter NDJSON / Family::DataImportercarry priority; absent ⇒ appended
API rule JSON, spec/swagger_helper.rb, docs/api/openapi.yamlpriority added (hunk applied by hand; regenerating also rewrote unrelated loan text already out of sync on main)
Family::DataExporter CSV, RuleImportdeliberately unchanged, see above
API index orderdeliberately unchanged
Rule.create_from_groupinggets 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 BigDecimal and 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 untouched origin/main (Settings::HostingsControllerTest x3 and Provider::RegistryTest because ANTHROPIC_BASE_URL is set in this environment; Provider::OpenaiTest#extra_headers_stringifies_nested_values_Ruby-style because 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/rubocop on changed Ruby files: no offenses. erb_lint on rules/_rule and rules/index: no errors. bin/brakeman --no-pager: no warnings.
  • npm run lint (Biome) not run: no JavaScript changed and node_modules is not installed in this environment.
  • Checked against upstream AGENTS.md (fetched from we-promise/sure main on 2026-10-01; identical to this fork's copy): tests via Minitest + fixtures, rswag only for docs, Current.family, i18n via t(), DS primitives and functional tokens, no new dependency, no migration run automatically (the migration was run once locally to regenerate db/schema.rb; only its own hunks are committed).

Mutation pass (each change reverted, named test must fail):

Change brokenResult
Rule.apply_in_priority_order without prioritisedcaught 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_timeout6 failures in regex_execution_test.rb
back-reference check removedback-references are refused fails
probe wrapper removederror in safe_regex_test.rb
sanitize_sql_like removed from starts/endswildcard test fails
Rule::Condition validation removed6 failures in condition_regex_test.rb
syncer back to one job per rule2 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_contain and fall back to English).
  • Migration adds a column with a default and an index to rules, a small table; the backfill is a single UPDATE.
  • Gatekeeper review fires automatically on this draft; it is not handled here.

Generated by Claude Code