Automation rules for an event execute in undefined (Postgres heap) order
Describe the bug
Automation rules for the same event run in whatever order PostgreSQL happens to return them, not in a defined order.
AutomationRuleListener#current_account_rules builds the relation without an order:
and the listener then runs the rules sequentially, evaluating each rule's conditions against the conversation after the previous rule's actions have been applied. Because actions such as changing status, assigning a team or adding a label mutate the conversation, the outcome of a later rule can depend on which rules ran before it.
Without ORDER BY, Postgres returns rows in physical (heap) order. That is usually insertion order for a small table, but every UPDATE writes a new tuple, so editing a rule (or toggling it off and on) silently moves it to the end of the execution order. The Automations index endpoint (Api::V1::Accounts::AutomationRulesController#index) has no ordering either, so what the dashboard shows is not a promise about execution order.
To Reproduce
- Create rule A on Conversation Updated: if status is open → assign team Support.
- Create rule B on Conversation Updated: if label "billing" is added → change status to pending.
- Add the "billing" label to an open conversation. With A then B the team is assigned and the status becomes pending. With B then A the status becomes pending first, so A's condition no longer matches and no team is assigned.
- Edit rule A (for example change its description) and repeat step 3: the order has changed, because the updated row now sits after B in the heap.
Expected behavior
Rules run in a deterministic order that admins can reason about. The smallest change is .order(:id) in current_account_rules (creation order) and the same on the index endpoint, so the list in the dashboard matches the execution order. A user-controlled position would be nicer but is a larger change.
Happy to open a PR for the .order(:id) version with a spec if that is the direction you want.
Environment
Self-hosted (also present on current develop, d4b5441)
Cloud Provider
No response
Platform
Docker
Operating system
Linux
Browser and version
Not browser-specific
Docker (if applicable)
chatwoot/chatwoot:v4.18.0
Additional context
Related: #16064 (attribute_changed AND/OR casing), a separate bug in the same rule evaluation path.
Source: chatwoot/chatwoot