iachat/app/mailboxes
Pranav ffa124d0d5
fix: Use .find_by instead .where().first (#12402)
While investigating a customer-reported issue, I found that some emails
were appearing late in Chatwoot. The root cause was query timeouts.

It only happened for emails with an in_reply_to header. In these cases,
Chatwoot first checks if a message exists with message_id = in_reply_to.
If not, it falls back to checking conversations where
additional_attributes->>'in_reply_to' = ?.

We were using:
```rb
@inbox.conversations.where("additional_attributes->>'in_reply_to' = ?", in_reply_to).first
```
This looked harmless, but .first caused timeouts. Without .first, the
query ran fine. The issue was the generated SQL:
```sql
SELECT * 
FROM conversations 
WHERE inbox_id = $1 
  AND (additional_attributes->>'in_reply_to' = '<in-reply-to-id>') 
ORDER BY id ASC 
LIMIT $2;
```
The ORDER BY id forced a full scan, even with <10k records.

The fix was to replace .first with .find_by:
```rb
@inbox.conversations.find_by("additional_attributes->>'in_reply_to' = ?", in_reply_to)
```
This generates:

```sql
SELECT * 
FROM conversations 
WHERE inbox_id = $1 
  AND (additional_attributes->>'in_reply_to' = '<in-reply-to-id>') 
LIMIT $2;
```
This avoids the scan and runs quickly without needing an index.

By the way, Cursor and Claude failed
[here](https://github.com/chatwoot/chatwoot/pull/12401), it just kept on
adding the index without figuring out the root cause.

Co-authored-by: Muhsin Keloth <muhsinkeramam@gmail.com>
2025-09-10 10:08:37 +05:30
..
imap fix: Use .find_by instead .where().first (#12402) 2025-09-10 10:08:37 +05:30
application_mailbox.rb chore: upgrade ruby version to 3.4.4 (#11524) 2025-05-21 19:40:07 +05:30
default_mailbox.rb Feature: Conversation Continuity with Email (#770) 2020-04-30 20:20:26 +05:30
incoming_email_validity_helper.rb fix: Disable automations on auto-reply emails (#12101) 2025-08-05 13:17:06 +05:30
mailbox_helper.rb fix: Process non-image inline attachments as regular attachments (#10998) 2025-02-28 13:33:48 -08:00
reply_mailbox.rb fix: change email conversation not found exception to log (#8785) 2024-01-25 22:36:02 +05:30
support_mailbox.rb fix: Disable automations on auto-reply emails (#12101) 2025-08-05 13:17:06 +05:30