Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(email): email optimize attachments and backfill (#5448)

Will Hutchinson9362a31c505e
diff --git a/crates/email_db_client/fixtures/fetch_insertable_attachments_for_new_email.sql b/crates/email_db_client/fixtures/fetch_insertable_attachments_for_new_email.sql
index 7cc9024a4b..15678dcab9 100644
--- a/crates/email_db_client/fixtures/fetch_insertable_attachments_for_new_email.sql
+++ b/crates/email_db_client/fixtures/fetch_insertable_attachments_for_new_email.sql
@@ -10,15 +10,20 @@
-- NOTE:
-- - All UUIDs are hard-coded so tests can reference them
--- - User email: [email protected]
+-- - User email: [email protected]
------------------------------------------------------------
-- User Link
------------------------------------------------------------
INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
-VALUES ('00000000-0000-0000-0000-00000000001a', 'macro|[email protected]', '00000000-0000-0000-0000-00000000001a',
- '[email protected]', 'GMAIL', true, NOW(), NOW());
+VALUES ('00000000-0000-0000-0000-00000000001a', 'macro|[email protected]', '00000000-0000-0000-0000-00000000001a',
+ '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+-- Link B intentionally has no email_contacts row for its own address.
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000002a', 'macro|[email protected]', '00000000-0000-0000-0000-00000000002a',
+ '[email protected]', 'GMAIL', true, NOW(), NOW());
------------------------------------------------------------
-- Labels
@@ -39,11 +44,11 @@ VALUES ('00000000-0000-0000-0000-0000000a0001',
-- Contacts
------------------------------------------------------------
--- Same domain contact ([email protected] -> [email protected])
+-- Same domain contact ([email protected] -> [email protected])
INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
VALUES ('00000000-0000-0000-0000-0000000c0001',
'00000000-0000-0000-0000-00000000001a',
NOW(), NOW());
-- Different domain contact
@@ -74,6 +79,38 @@ VALUES ('00000000-0000-0000-0000-0000000c0005',
NOW(), NOW());
+-- Contact whose domain only has the user's domain as a suffix
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c0006',
+ '00000000-0000-0000-0000-00000000001a',
+ NOW(), NOW());
+
+-- Contact with the exact user domain in mixed case
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c0007',
+ '00000000-0000-0000-0000-00000000001a',
+ NOW(), NOW());
+
+-- The link owner's contact rows, used to ensure self does not satisfy condition 5 case-insensitively.
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c0008',
+ '00000000-0000-0000-0000-00000000001a',
+ NOW(), NOW()),
+ ('00000000-0000-0000-0000-0000000c000a',
+ '00000000-0000-0000-0000-00000000001a',
+ NOW(), NOW());
+
+-- A real contacted participant on Link B, which intentionally has no self-contact row.
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c0009',
+ '00000000-0000-0000-0000-00000000002a',
+ NOW(), NOW());
+
------------------------------------------------------------
-- Threads
------------------------------------------------------------
@@ -126,6 +163,33 @@ VALUES ('00000000-0000-0000-0000-000000000108',
'00000000-0000-0000-0000-00000000001a',
false, false, NOW(), NOW());
+-- Thread 9: Domain suffix must not qualify as the same domain
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000109',
+ '00000000-0000-0000-0000-00000000001a',
+ false, false, NOW(), NOW());
+
+-- Thread 10: Exact domain with mixed case must qualify as the same domain
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000110',
+ '00000000-0000-0000-0000-00000000001a',
+ false, false, NOW(), NOW());
+
+-- Thread 11: Self is the only contacted participant.
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000111',
+ '00000000-0000-0000-0000-00000000001a',
+ false, false, NOW(), NOW());
+
+-- Threads 12 and 13 establish and test contact on a link without a self-contact row.
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000112',
+ '00000000-0000-0000-0000-00000000002a',
+ false, false, NOW(), NOW()),
+ ('00000000-0000-0000-0000-000000000113',
+ '00000000-0000-0000-0000-00000000002a',
+ false, false, NOW(), NOW());
+
------------------------------------------------------------
-- Thread 5: Establish "previously contacted" relationship
------------------------------------------------------------
@@ -236,7 +300,7 @@ VALUES ('00000000-0000-0000-0000-0000000e0301',
'00000000-0000-0000-0000-00000000001a',
'target-msg-301',
FALSE,
- '00000000-0000-0000-0000-0000000c0001', -- from [email protected]
+ '00000000-0000-0000-0000-0000000c0001', -- from [email protected]
'2025-01-02 12:00:00 +00:00',
true, false, false, false, NOW(), NOW());
@@ -349,17 +413,127 @@ VALUES ('00000000-0000-0000-0000-0000008a0801',
'application/pdf',
NOW());
+------------------------------------------------------------
+-- Thread 9: Domain suffix does not match
+------------------------------------------------------------
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000e0901',
+ '00000000-0000-0000-0000-000000000109',
+ '00000000-0000-0000-0000-00000000001a',
+ 'target-msg-901',
+ FALSE,
+ '00000000-0000-0000-0000-0000000c0006',
+ '2025-01-02 17:00:00 +00:00',
+ true, false, false, false, NOW(), NOW());
+
+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)
+VALUES ('00000000-0000-0000-0000-0000009a0901',
+ '00000000-0000-0000-0000-0000000e0901',
+ 'provider-att-901',
+ 'suffix_domain_doc.pdf',
+ 'application/pdf',
+ NOW());
+
+------------------------------------------------------------
+-- Thread 10: Exact domain matches case-insensitively
+------------------------------------------------------------
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000e1001',
+ '00000000-0000-0000-0000-000000000110',
+ '00000000-0000-0000-0000-00000000001a',
+ 'target-msg-1001',
+ FALSE,
+ '00000000-0000-0000-0000-0000000c0007',
+ '2025-01-02 18:00:00 +00:00',
+ true, false, false, false, NOW(), NOW());
+
+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)
+VALUES ('00000000-0000-0000-0000-000000aa1001',
+ '00000000-0000-0000-0000-0000000e1001',
+ 'provider-att-1001',
+ 'mixed_case_domain_doc.pdf',
+ 'application/pdf',
+ NOW());
+
+------------------------------------------------------------
+-- Thread 11: Only self has previously been contacted
+------------------------------------------------------------
+
+-- Establish a sent-message recipient record for self.
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000e1101',
+ '00000000-0000-0000-0000-000000000105',
+ '00000000-0000-0000-0000-00000000001a',
+ 'self-contact-history', TRUE, NULL, '2025-01-01 11:00:00 +00:00',
+ false, false, false, false, NOW(), NOW());
+
+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type)
+VALUES ('00000000-0000-0000-0000-0000000e1101',
+ '00000000-0000-0000-0000-0000000c0008',
+ 'TO');
+
+-- The target has an uncontacted sender and self as a recipient.
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000e1102',
+ '00000000-0000-0000-0000-000000000111',
+ '00000000-0000-0000-0000-00000000001a',
+ 'target-msg-1101', FALSE, '00000000-0000-0000-0000-0000000c0004', '2025-01-02 19:00:00 +00:00',
+ true, false, false, false, NOW(), NOW());
+
+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type)
+VALUES ('00000000-0000-0000-0000-0000000e1102',
+ '00000000-0000-0000-0000-0000000c0008',
+ 'TO');
+
+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)
+VALUES ('00000000-0000-0000-0000-000000aa1101',
+ '00000000-0000-0000-0000-0000000e1102',
+ 'provider-att-1101', 'self_only_contacted.pdf', 'application/pdf', NOW());
+
+------------------------------------------------------------
+-- Link B: Real contacted participant without a self-contact row
+------------------------------------------------------------
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000e1201',
+ '00000000-0000-0000-0000-000000000112',
+ '00000000-0000-0000-0000-00000000002a',
+ 'missing-self-history', TRUE, NULL, '2025-01-01 12:00:00 +00:00',
+ false, false, false, false, NOW(), NOW()),
+ ('00000000-0000-0000-0000-0000000e1301',
+ '00000000-0000-0000-0000-000000000113',
+ '00000000-0000-0000-0000-00000000002a',
+ 'target-msg-1301', FALSE, '00000000-0000-0000-0000-0000000c0009', '2025-01-02 20:00:00 +00:00',
+ true, false, false, false, NOW(), NOW());
+
+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type)
+VALUES ('00000000-0000-0000-0000-0000000e1201',
+ '00000000-0000-0000-0000-0000000c0009',
+ 'TO');
+
+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)
+VALUES ('00000000-0000-0000-0000-000000aa1301',
+ '00000000-0000-0000-0000-0000000e1301',
+ 'provider-att-1301', 'missing_self_contact.pdf', 'application/pdf', NOW());
+
-- Macro user for the User table foreign key
INSERT INTO "macro_user" (id, username, email, stripe_customer_id)
VALUES ('00000000-0000-0000-0000-00000000001a',
'user_a',
'cus_test123');
-- User for the document owner
INSERT INTO "User" (id, email, name, macro_user_id)
VALUES ('00000000-0000-0000-0000-00000000001a',
'User A',
'00000000-0000-0000-0000-00000000001a');
diff --git a/crates/email_db_client/fixtures/fetch_job_attachments_for_backfill.sql b/crates/email_db_client/fixtures/fetch_job_attachments_for_backfill.sql
index fb7aca7df5..48bcf3ffd2 100644
--- a/crates/email_db_client/fixtures/fetch_job_attachments_for_backfill.sql
+++ b/crates/email_db_client/fixtures/fetch_job_attachments_for_backfill.sql
@@ -20,6 +20,17 @@ VALUES ('00000000-0000-0000-0000-00000000001a', 'macro|[email protected]', '000
-- Contacts
------------------------------------------------------------
+-- The user's own contacts, used to verify self-only threads are excluded case-insensitively.
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c0000',
+ '00000000-0000-0000-0000-00000000001a',
+ NOW(), NOW()),
+ ('00000000-0000-0000-0000-0000000c0005',
+ '00000000-0000-0000-0000-00000000001a',
+ NOW(), NOW());
+
-- Previously contacted person (user sent email to this person)
INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
VALUES ('00000000-0000-0000-0000-0000000c0001',
@@ -89,6 +100,9 @@ VALUES ('00000000-0000-0000-0000-0000000e0401',
INSERT INTO email_message_recipients (message_id, contact_id, recipient_type)
VALUES ('00000000-0000-0000-0000-0000000e0401',
'00000000-0000-0000-0000-0000000c0001', -- [email protected]
+ 'TO'),
+ ('00000000-0000-0000-0000-0000000e0401',
+ '00000000-0000-0000-0000-0000000c0000', -- the user's own contact
'TO');
-- User sent message to [email protected] (creates another relationship)
@@ -241,5 +255,100 @@ VALUES ('00000000-0000-0000-0000-0000003a0302',
NOW());
------------------------------------------------------------
+-- Additional completion-sweep edge cases
+
+-- Self-only eligible thread: self is contacted above but must not qualify.
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000105', '00000000-0000-0000-0000-00000000001a', false, false, NOW(), NOW());
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000e0501', '00000000-0000-0000-0000-000000000105',
+ '00000000-0000-0000-0000-00000000001a', 'provider-msg-501', FALSE,
+ '00000000-0000-0000-0000-0000000c0000', '2025-01-02 14:00:00 +00:00',
+ true, false, false, false, NOW(), NOW());
+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)
+VALUES ('00000000-0000-0000-0000-0000005a0501', '00000000-0000-0000-0000-0000000e0501',
+ 'provider-att-501', 'self_only.pdf', 'application/pdf', NOW());
+
+-- Attachment-bearing, contacted threads whose only attachments are filtered.
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000106', '00000000-0000-0000-0000-00000000001a', false, false, NOW(), NOW()),
+ ('00000000-0000-0000-0000-000000000107', '00000000-0000-0000-0000-00000000001a', false, false, NOW(), NOW());
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000e0601', '00000000-0000-0000-0000-000000000106',
+ '00000000-0000-0000-0000-00000000001a', 'provider-msg-601', FALSE,
+ '00000000-0000-0000-0000-0000000c0001', '2025-01-02 15:00:00 +00:00',
+ true, false, false, false, NOW(), NOW()),
+ ('00000000-0000-0000-0000-0000000e0701', '00000000-0000-0000-0000-000000000107',
+ '00000000-0000-0000-0000-00000000001a', 'provider-msg-701', FALSE,
+ '00000000-0000-0000-0000-0000000c0001', '2025-01-02 16:00:00 +00:00',
+ true, false, false, false, NOW(), NOW());
+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)
+VALUES ('00000000-0000-0000-0000-0000006a0601', '00000000-0000-0000-0000-0000000e0601',
+ 'provider-att-601', 'filtered_image.jpg', 'image/jpeg', NOW()),
+ ('00000000-0000-0000-0000-0000007a0701', '00000000-0000-0000-0000-0000000e0701',
+ 'provider-att-701', NULL, 'application/pdf', NOW());
+
+-- Contacted participant without attachments: not eligible.
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000108', '00000000-0000-0000-0000-00000000001a', false, false, NOW(), NOW());
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000e0801', '00000000-0000-0000-0000-000000000108',
+ '00000000-0000-0000-0000-00000000001a', 'provider-msg-801', FALSE,
+ '00000000-0000-0000-0000-0000000c0001', '2025-01-02 17:00:00 +00:00',
+ false, false, false, false, NOW(), NOW());
+
+-- Link B intentionally has no self-contact row.
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000002a', 'macro|[email protected]',
+ '00000000-0000-0000-0000-00000000002a', '[email protected]', 'GMAIL', true, NOW(), NOW());
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c0021', '00000000-0000-0000-0000-00000000002a',
+ '[email protected]', NOW(), NOW());
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000201', '00000000-0000-0000-0000-00000000002a', false, false, NOW(), NOW()),
+ ('00000000-0000-0000-0000-000000000202', '00000000-0000-0000-0000-00000000002a', false, false, NOW(), NOW());
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000e2001', '00000000-0000-0000-0000-000000000201',
+ '00000000-0000-0000-0000-00000000002a', 'provider-msg-2001', TRUE, NULL,
+ '2025-01-03 10:00:00 +00:00', false, false, false, false, NOW(), NOW()),
+ ('00000000-0000-0000-0000-0000000e2002', '00000000-0000-0000-0000-000000000202',
+ '00000000-0000-0000-0000-00000000002a', 'provider-msg-2002', FALSE,
+ '00000000-0000-0000-0000-0000000c0021', '2025-01-03 11:00:00 +00:00',
+ true, false, false, false, NOW(), NOW());
+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type)
+VALUES ('00000000-0000-0000-0000-0000000e2001', '00000000-0000-0000-0000-0000000c0021', 'TO');
+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)
+VALUES ('00000000-0000-0000-0000-0000002a2002', '00000000-0000-0000-0000-0000000e2002',
+ 'provider-att-2002', 'missing_self_contact.pdf', 'application/pdf', NOW());
+
+-- Link C has an independently eligible contacted thread that must not leak into Link A.
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000003a', 'macro|[email protected]',
+ '00000000-0000-0000-0000-00000000003a', '[email protected]', 'GMAIL', true, NOW(), NOW());
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c0031', '00000000-0000-0000-0000-00000000003a',
+ '[email protected]', NOW(), NOW());
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000301', '00000000-0000-0000-0000-00000000003a', false, false, NOW(), NOW()),
+ ('00000000-0000-0000-0000-000000000302', '00000000-0000-0000-0000-00000000003a', false, false, NOW(), NOW());
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000e3001', '00000000-0000-0000-0000-000000000301',
+ '00000000-0000-0000-0000-00000000003a', 'provider-msg-3001', TRUE, NULL,
+ '2025-01-04 10:00:00 +00:00', false, false, false, false, NOW(), NOW()),
+ ('00000000-0000-0000-0000-0000000e3002', '00000000-0000-0000-0000-000000000302',
+ '00000000-0000-0000-0000-00000000003a', 'provider-msg-3002', FALSE,
+ '00000000-0000-0000-0000-0000000c0031', '2025-01-04 11:00:00 +00:00',
+ true, false, false, false, NOW(), NOW());
+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type)
+VALUES ('00000000-0000-0000-0000-0000000e3001', '00000000-0000-0000-0000-0000000c0031', 'TO');
+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)
+VALUES ('00000000-0000-0000-0000-0000003a3002', '00000000-0000-0000-0000-0000000e3002',
+ 'provider-att-3002', 'other_link_document.pdf', 'application/pdf', NOW());
+
-- End of fixture
------------------------------------------------------------
\ No newline at end of file
diff --git a/crates/email_db_client/fixtures/fetch_thread_attachments_for_backfill.sql b/crates/email_db_client/fixtures/fetch_thread_attachments_for_backfill.sql
index 46a9bcae52..5b04e4dde5 100644
--- a/crates/email_db_client/fixtures/fetch_thread_attachments_for_backfill.sql
+++ b/crates/email_db_client/fixtures/fetch_thread_attachments_for_backfill.sql
@@ -1,7 +1,7 @@
-- SQL fixture for fetch_thread_attachments_for_backfill tests
-- This file seeds:
--- - 5 threads (4 matching the conditions, 1 control with no matches)
+-- - 7 threads covering eligibility conditions and exact-domain matching
-- - Messages, contacts, labels, attachments
-- NOTE:
@@ -12,11 +12,11 @@
-- Common: links + threads
------------------------------------------------------------
--- Link A: user email is [email protected]
+-- Link A: user email is [email protected]
INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at,
updated_at)
-VALUES ('00000000-0000-0000-0000-00000000001a', 'macro|[email protected]', '00000000-0000-0000-0000-00000000001a',
- '[email protected]', 'GMAIL', true, '2025-11-11 17:48:26.664688 +00:00',
+VALUES ('00000000-0000-0000-0000-00000000001a', 'macro|[email protected]', '00000000-0000-0000-0000-00000000001a',
+ '[email protected]', 'GMAIL', true, '2025-11-11 17:48:26.664688 +00:00',
'2025-11-11 17:48:26.664688 +00:00');
-- Thread 1: used for condition 1 (is_sent = true)
@@ -64,6 +64,24 @@ VALUES ('00000000-0000-0000-0000-000000000105',
NOW(),
NOW());
+-- Thread 6: domain suffix must not qualify as the same domain
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000106',
+ '00000000-0000-0000-0000-00000000001a',
+ false,
+ false,
+ NOW(),
+ NOW());
+
+-- Thread 7: exact domain with mixed case must qualify as the same domain
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000107',
+ '00000000-0000-0000-0000-00000000001a',
+ false,
+ false,
+ NOW(),
+ NOW());
+
------------------------------------------------------------
-- Labels
------------------------------------------------------------
@@ -83,11 +101,11 @@ VALUES ('00000000-0000-0000-0000-0000000a0001',
-- Contacts
------------------------------------------------------------
--- Contact with same domain as [email protected]
+-- Contact with same domain as [email protected]
INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
VALUES ('00000000-0000-0000-0000-0000000c0001',
'00000000-0000-0000-0000-00000000001a',
NOW(),
NOW());
@@ -107,6 +125,22 @@ VALUES ('00000000-0000-0000-0000-0000000c0003',
NOW(),
NOW());
+-- Contact whose domain only has the user's domain as a suffix
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c0004',
+ '00000000-0000-0000-0000-00000000001a',
+ NOW(),
+ NOW());
+
+-- Contact with the exact user domain in mixed case
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c0005',
+ '00000000-0000-0000-0000-00000000001a',
+ NOW(),
+ NOW());
+
------------------------------------------------------------
-- Thread 1: Condition 1 - is_sent = true
------------------------------------------------------------
@@ -374,6 +408,52 @@ VALUES ('00000000-0000-0000-0000-0000005a0501',
'application/pdf',
NOW());
+------------------------------------------------------------
+-- Thread 6: domain suffix does not match
+------------------------------------------------------------
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000e601',
+ '00000000-0000-0000-0000-000000000106',
+ '00000000-0000-0000-0000-00000000001a',
+ 'provider-msg-601',
+ FALSE,
+ '00000000-0000-0000-0000-0000000c0004',
+ NOW(),
+ true, false, false, false, NOW(), NOW());
+
+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)
+VALUES ('00000000-0000-0000-0000-0000006a0601',
+ '00000000-0000-0000-0000-00000000e601',
+ 'provider-att-601',
+ 'suffix_domain_doc.pdf',
+ 'application/pdf',
+ NOW());
+
+------------------------------------------------------------
+-- Thread 7: exact domain matches case-insensitively
+------------------------------------------------------------
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000e701',
+ '00000000-0000-0000-0000-000000000107',
+ '00000000-0000-0000-0000-00000000001a',
+ 'provider-msg-701',
+ FALSE,
+ '00000000-0000-0000-0000-0000000c0005',
+ NOW(),
+ true, false, false, false, NOW(), NOW());
+
+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)
+VALUES ('00000000-0000-0000-0000-0000007a0701',
+ '00000000-0000-0000-0000-00000000e701',
+ 'provider-att-701',
+ 'mixed_case_domain_doc.pdf',
+ 'application/pdf',
+ NOW());
+
------------------------------------------------------------
-- End of fixture
------------------------------------------------------------
\ No newline at end of file
diff --git a/crates/email_db_client/src/attachments/provider/upload.rs b/crates/email_db_client/src/attachments/provider/upload.rs
index 1ac922f63e..0b06bd1e92 100644
--- a/crates/email_db_client/src/attachments/provider/upload.rs
+++ b/crates/email_db_client/src/attachments/provider/upload.rs
@@ -25,6 +25,22 @@ pub async fn thread_document_atts_for_backfill(
) -> anyhow::Result<Vec<AttachmentUploadMetadata>> {
let query = format!(
r#"
+ WITH
+ thread_info AS MATERIALIZED (
+ SELECT
+ t.id AS thread_id,
+ t.link_id,
+ LOWER(SPLIT_PART(link.email_address, '@', 2)) AS user_domain
+ FROM email_threads t
+ JOIN email_links link ON link.id = t.link_id
+ WHERE t.id = $1
+ ),
+ important_label AS MATERIALIZED (
+ SELECT l.id
+ FROM email_labels l
+ JOIN thread_info ti ON l.link_id = ti.link_id
+ WHERE l.name = 'IMPORTANT'
+ )
SELECT
a.id AS attachment_db_id,
m.provider_id as email_provider_id,
@@ -39,32 +55,39 @@ pub async fn thread_document_atts_for_backfill(
FROM email_attachments a
JOIN email_messages m ON a.message_id = m.id
JOIN email_contacts from_contact ON m.from_contact_id = from_contact.id
+ JOIN thread_info ti ON m.thread_id = ti.thread_id
WHERE m.thread_id = $1
AND a.filename IS NOT NULL
-- attachment mime type filters injected below
{}
- AND EXISTS ( -- only fetch if at least one message in the thread meets any of the criteria
- SELECT 1
- FROM email_messages m2
- LEFT JOIN email_message_labels ml ON m2.id = ml.message_id
- LEFT JOIN email_labels l ON ml.label_id = l.id
- LEFT JOIN email_contacts c ON m2.from_contact_id = c.id
- JOIN email_threads t ON m2.thread_id = t.id
- JOIN email_links link ON t.link_id = link.id
- WHERE m2.thread_id = $1
- AND (
- m2.is_sent = true -- condition 1
- OR l.name = 'IMPORTANT' -- condition 2
- OR (
- -- condition 3
- c.email_address IS NOT NULL
- AND RIGHT(c.email_address, LENGTH(RIGHT(link.email_address,
- LENGTH(link.email_address) - POSITION('@' IN link.email_address)))) =
- RIGHT(link.email_address, LENGTH(link.email_address) - POSITION('@' IN link.email_address))
+ AND (
+ -- condition 1: the thread contains a sent message
+ EXISTS (
+ SELECT 1
+ FROM email_messages sent_message
+ WHERE sent_message.thread_id = ti.thread_id
+ AND sent_message.is_sent = true
+ )
+ -- condition 2: the thread contains a message with the link's IMPORTANT label
+ OR EXISTS (
+ SELECT 1
+ FROM important_label il
+ JOIN email_message_labels ml ON ml.label_id = il.id
+ JOIN email_messages labeled_message ON labeled_message.id = ml.message_id
+ WHERE labeled_message.thread_id = ti.thread_id
+ )
+ -- conditions 3 and 4 share one sender pass
+ OR EXISTS (
+ SELECT 1
+ FROM email_messages sender_message
+ JOIN email_contacts c ON c.id = sender_message.from_contact_id
+ WHERE sender_message.thread_id = ti.thread_id
+ AND (
+ LOWER(SPLIT_PART(c.email_address, '@', 2)) = ti.user_domain
+ -- whitelisted domain check injected below
+ {}
)
- -- whitelisted domain check injected below
- {}
- )
+ )
)
ORDER BY a.id
"#,
@@ -142,47 +165,52 @@ pub async fn fetch_job_attachments_for_backfill(
) -> anyhow::Result<Vec<AttachmentUploadMetadata>> {
let query = format!(
r#"
- -- Step 1: Get the user's own email address from the link_id. This is our exclusion criteria.
WITH
- user_email AS (
- SELECT email_address
- FROM public.email_links
- WHERE id = $1
+ eligible_threads AS (
+ SELECT DISTINCT thread_id
+ FROM public.email_messages
+ WHERE link_id = $1
+ AND has_attachments = true
),
-
- -- Step 2: Create a distinct list of OTHER people this user has ever sent mail to.
- previously_contacted_emails AS (
- SELECT DISTINCT ec.email_address
- FROM public.email_messages em
- JOIN public.email_message_recipients emr ON em.id = emr.message_id
- JOIN public.email_contacts ec ON emr.contact_id = ec.id
- WHERE em.link_id = $1
- AND em.is_sent = true
- AND ec.email_address != (SELECT email_address FROM user_email)
+ self_contact AS (
+ SELECT c.id
+ FROM public.email_links l
+ JOIN public.email_contacts c
+ ON c.link_id = l.id
+ AND LOWER(c.email_address) = LOWER(l.email_address)
+ WHERE l.id = $1
),
-
- -- Step 3: For each thread, create a complete list of OTHER participant email addresses.
- thread_participants AS (
- -- Get all senders in each thread (excluding the user)
- SELECT DISTINCT em.thread_id, ec.email_address
- FROM public.email_messages em
- JOIN public.email_contacts ec ON em.from_contact_id = ec.id
- WHERE em.link_id = $1
- AND ec.email_address != (SELECT email_address FROM user_email)
+ contacted AS (
+ SELECT DISTINCT emr.contact_id
+ FROM public.email_messages sent_message
+ JOIN public.email_message_recipients emr ON emr.message_id = sent_message.id
+ WHERE sent_message.link_id = $1
+ AND sent_message.is_sent = true
+ ),
+ participants AS (
+ SELECT message.thread_id, message.from_contact_id AS contact_id
+ FROM eligible_threads eligible
+ JOIN public.email_messages message ON message.thread_id = eligible.thread_id
+ WHERE message.from_contact_id IS NOT NULL
UNION
- -- Get all recipients in each thread (excluding the user)
- SELECT DISTINCT em.thread_id, ec.email_address
- FROM public.email_messages em
- JOIN public.email_message_recipients emr ON em.id = emr.message_id
- JOIN public.email_contacts ec ON emr.contact_id = ec.id
- WHERE em.link_id = $1
- AND ec.email_address != (SELECT email_address FROM user_email)
+ SELECT message.thread_id, recipient.contact_id
+ FROM eligible_threads eligible
+ JOIN public.email_messages message ON message.thread_id = eligible.thread_id
+ JOIN public.email_message_recipients recipient ON recipient.message_id = message.id
+ ),
+ qualified_threads AS (
+ SELECT DISTINCT participant.thread_id
+ FROM participants participant
+ JOIN contacted ON contacted.contact_id = participant.contact_id
+ WHERE NOT EXISTS (
+ SELECT 1
+ FROM self_contact
+ WHERE self_contact.id = participant.contact_id
+ )
)
- -- Final Step: Select attachments from threads where AT LEAST ONE of the OTHER participants
- -- is in the list of OTHER previously_contacted_emails.
SELECT
a.id AS attachment_db_id,
m.provider_id as email_provider_id,
@@ -197,11 +225,7 @@ pub async fn fetch_job_attachments_for_backfill(
FROM public.email_attachments a
JOIN public.email_messages m ON a.message_id = m.id
JOIN public.email_contacts from_contact ON m.from_contact_id = from_contact.id
- WHERE m.thread_id IN (
- SELECT DISTINCT tp.thread_id
- FROM thread_participants tp
- INNER JOIN previously_contacted_emails pce ON tp.email_address = pce.email_address
- )
+ WHERE m.thread_id IN (SELECT thread_id FROM qualified_threads)
-- attachment mime type filters injected below
{}
AND a.filename IS NOT NULL
@@ -296,13 +320,32 @@ pub async fn new_email_document_atts(
// query for conditions 1-4: claim attachments atomically and return metadata
let query1 = format!(
r#"
- WITH claimed AS (
+ WITH
+ thread_info AS MATERIALIZED (
+ SELECT
+ t.id AS thread_id,
+ t.link_id,
+ LOWER(SPLIT_PART(link.email_address, '@', 2)) AS user_domain
+ FROM email_messages target_message
+ JOIN email_threads t ON t.id = target_message.thread_id
+ JOIN email_links link ON link.id = t.link_id
+ WHERE target_message.link_id = $2
+ AND target_message.provider_id = $1
+ ),
+ important_label AS MATERIALIZED (
+ SELECT l.id
+ FROM email_labels l
+ JOIN thread_info ti ON l.link_id = ti.link_id
+ WHERE l.name = 'IMPORTANT'
+ ),
+ claimed AS (
UPDATE email_attachments
SET upload_claimed_at = NOW()
WHERE id IN (
SELECT a.id
FROM email_attachments a
JOIN email_messages m ON a.message_id = m.id
+ JOIN thread_info ti ON m.thread_id = ti.thread_id
LEFT JOIN document_email de ON de.email_attachment_id = a.id
WHERE m.link_id = $2
AND m.provider_id = $1
@@ -310,26 +353,33 @@ pub async fn new_email_document_atts(
{}
AND de.email_attachment_id IS NULL
AND a.upload_claimed_at IS NULL
- AND EXISTS (
- SELECT 1
- FROM email_messages m2
- LEFT JOIN email_message_labels ml ON m2.id = ml.message_id
- LEFT JOIN email_labels l ON ml.label_id = l.id
- LEFT JOIN email_contacts c ON m2.from_contact_id = c.id
- JOIN email_threads t ON m2.thread_id = t.id
- JOIN email_links link ON t.link_id = link.id
- WHERE m2.thread_id = m.thread_id
- AND (
- m2.is_sent = true
- OR l.name = 'IMPORTANT'
- OR (
- c.email_address IS NOT NULL
- AND RIGHT(c.email_address, LENGTH(RIGHT(link.email_address,
- LENGTH(link.email_address) - POSITION('@' IN link.email_address)))) =
- RIGHT(link.email_address, LENGTH(link.email_address) - POSITION('@' IN link.email_address))
+ AND (
+ -- condition 1: the thread contains a sent message
+ EXISTS (
+ SELECT 1
+ FROM email_messages sent_message
+ WHERE sent_message.thread_id = ti.thread_id
+ AND sent_message.is_sent = true
+ )
+ -- condition 2: the thread contains a message with the link's IMPORTANT label
+ OR EXISTS (
+ SELECT 1
+ FROM important_label il
+ JOIN email_message_labels ml ON ml.label_id = il.id
+ JOIN email_messages labeled_message ON labeled_message.id = ml.message_id
+ WHERE labeled_message.thread_id = ti.thread_id
+ )
+ -- conditions 3 and 4 share one sender pass
+ OR EXISTS (
+ SELECT 1
+ FROM email_messages sender_message
+ JOIN email_contacts c ON c.id = sender_message.from_contact_id
+ WHERE sender_message.thread_id = ti.thread_id
+ AND (
+ LOWER(SPLIT_PART(c.email_address, '@', 2)) = ti.user_domain
+ {}
)
- {}
- )
+ )
)
)
RETURNING id
@@ -375,35 +425,29 @@ pub async fn new_email_document_atts(
r#"
WITH
message_info AS (
- SELECT m.thread_id, l.email_address as user_email, m.link_id
- FROM email_messages m
- JOIN email_threads t ON m.thread_id = t.id
- JOIN email_links l ON t.link_id = l.id
- WHERE m.link_id = $2
- AND m.provider_id = $1
+ SELECT thread_id
+ FROM email_messages
+ WHERE link_id = $2
+ AND provider_id = $1
),
- previously_contacted_emails AS (
- SELECT DISTINCT ec.email_address
- FROM email_messages em
- JOIN email_message_recipients emr ON em.id = emr.message_id
- JOIN email_contacts ec ON emr.contact_id = ec.id
- WHERE em.link_id = (SELECT link_id FROM message_info)
- AND em.is_sent = true
- AND ec.email_address != (SELECT user_email FROM message_info)
+ self_contact AS (
+ SELECT c.id
+ FROM email_links l
+ JOIN email_contacts c
+ ON c.link_id = l.id
+ AND LOWER(c.email_address) = LOWER(l.email_address)
+ WHERE l.id = $2
),
- thread_participants AS (
- SELECT DISTINCT ec.email_address
+ participants AS (
+ SELECT em.from_contact_id AS contact_id
FROM email_messages em
- JOIN email_contacts ec ON em.from_contact_id = ec.id
WHERE em.thread_id = (SELECT thread_id FROM message_info)
- AND ec.email_address != (SELECT user_email FROM message_info)
+ AND em.from_contact_id IS NOT NULL
UNION
- SELECT DISTINCT ec.email_address
+ SELECT emr.contact_id
FROM email_messages em
- JOIN email_message_recipients emr ON em.id = emr.message_id
- JOIN email_contacts ec ON emr.contact_id = ec.id
+ JOIN email_message_recipients emr ON emr.message_id = em.id
WHERE em.thread_id = (SELECT thread_id FROM message_info)
- AND ec.email_address != (SELECT user_email FROM message_info)
),
claimed AS (
UPDATE email_attachments
@@ -421,8 +465,20 @@ pub async fn new_email_document_atts(
{}
AND EXISTS (
SELECT 1
- FROM thread_participants tp
- INNER JOIN previously_contacted_emails pce ON tp.email_address = pce.email_address
+ FROM participants p
+ WHERE NOT EXISTS (
+ SELECT 1
+ FROM self_contact
+ WHERE self_contact.id = p.contact_id
+ )
+ AND EXISTS (
+ SELECT 1
+ FROM email_message_recipients emr
+ JOIN email_messages sent_message ON sent_message.id = emr.message_id
+ WHERE emr.contact_id = p.contact_id
+ AND sent_message.link_id = $2
+ AND sent_message.is_sent = true
+ )
)
)
RETURNING id
diff --git a/crates/email_db_client/src/attachments/provider/upload/test.rs b/crates/email_db_client/src/attachments/provider/upload/test.rs
index a7929d0ae0..bc56f16767 100644
--- a/crates/email_db_client/src/attachments/provider/upload/test.rs
+++ b/crates/email_db_client/src/attachments/provider/upload/test.rs
@@ -2,6 +2,36 @@ use super::*;
use anyhow::Result;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use sqlx::{Pool, Postgres};
+
+async fn remove_message_labels(pool: &Pool<Postgres>, message_id: Uuid) -> Result<()> {
+ sqlx::query!(
+ r#"
+ DELETE FROM email_message_labels
+ WHERE message_id = $1
+ "#,
+ message_id
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
+async fn attachment_is_claimed(pool: &Pool<Postgres>, attachment_id: Uuid) -> Result<bool> {
+ let claimed_at = sqlx::query_scalar!(
+ r#"
+ SELECT upload_claimed_at
+ FROM email_attachments
+ WHERE id = $1
+ "#,
+ attachment_id
+ )
+ .fetch_one(pool)
+ .await?;
+
+ Ok(claimed_at.is_some())
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
@@ -45,6 +75,32 @@ async fn thread_attachments_for_backfill_condition_2(pool: Pool<Postgres>) -> Re
Ok(())
}
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("fetch_thread_attachments_for_backfill")
+ )
+)]
+async fn thread_attachments_for_backfill_requires_important_label(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ remove_message_labels(
+ &pool,
+ Uuid::parse_str("00000000-0000-0000-0000-0000002a0201")?,
+ )
+ .await?;
+
+ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000102")?;
+ let res = thread_document_atts_for_backfill(&pool, thread_id).await?;
+
+ assert!(res.is_empty());
+
+ Ok(())
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
@@ -65,6 +121,48 @@ async fn thread_attachments_for_backfill_condition_3(pool: Pool<Postgres>) -> Re
Ok(())
}
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("fetch_thread_attachments_for_backfill")
+ )
+)]
+async fn thread_attachments_for_backfill_rejects_domain_suffix(pool: Pool<Postgres>) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000106")?;
+ let res = thread_document_atts_for_backfill(&pool, thread_id).await?;
+
+ assert!(res.is_empty());
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("fetch_thread_attachments_for_backfill")
+ )
+)]
+async fn thread_attachments_for_backfill_matches_domain_case_insensitively(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000107")?;
+ let res = thread_document_atts_for_backfill(&pool, thread_id).await?;
+
+ assert_eq!(res.len(), 1);
+ assert_eq!(
+ res[0].filename,
+ Some("mixed_case_domain_doc.pdf".to_string())
+ );
+
+ Ok(())
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
@@ -120,23 +218,89 @@ async fn job_attachments_for_backfill_includes_previously_contacted_participants
let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?;
let res = fetch_job_attachments_for_backfill(&pool, link_id).await?;
- // Should return 3 attachments:
- // 1. valid_document.pdf from Thread 1 (previously contacted participant)
- // 2. mixed_thread_doc.pdf from Thread 3 (has previously contacted participant)
- // 3. also_included_doc.docx from Thread 3 (same thread as #2)
- assert_eq!(res.len(), 3);
+ let filenames: Vec<&str> = res
+ .iter()
+ .map(|attachment| attachment.filename.as_deref().unwrap())
+ .collect();
+ assert_eq!(
+ filenames,
+ vec![
+ "also_included_doc.docx",
+ "mixed_thread_doc.pdf",
+ "valid_document.pdf"
+ ]
+ );
- // Check that the correct attachments are returned
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("fetch_job_attachments_for_backfill")
+ )
+)]
+async fn job_attachments_for_backfill_excludes_ineligible_and_filtered_attachments(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?;
+ let res = fetch_job_attachments_for_backfill(&pool, link_id).await?;
let filenames: Vec<&str> = res
.iter()
- .map(|a| a.filename.as_ref().map(|s| s.as_str()).unwrap())
+ .filter_map(|attachment| attachment.filename.as_deref())
.collect();
- assert!(filenames.contains(&"valid_document.pdf"));
- assert!(filenames.contains(&"mixed_thread_doc.pdf"));
- assert!(filenames.contains(&"also_included_doc.docx"));
- // Verify excluded_document.pdf is NOT included (from thread with no contacted participants)
assert!(!filenames.contains(&"excluded_document.pdf"));
+ assert!(!filenames.contains(&"self_only.pdf"));
+ assert!(!filenames.contains(&"filtered_image.jpg"));
+ assert_eq!(res.len(), 3);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("fetch_job_attachments_for_backfill")
+ )
+)]
+async fn job_attachments_for_backfill_allows_missing_self_contact(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000002a")?;
+ let res = fetch_job_attachments_for_backfill(&pool, link_id).await?;
+
+ assert_eq!(res.len(), 1);
+ assert_eq!(res[0].filename.as_deref(), Some("missing_self_contact.pdf"));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("fetch_job_attachments_for_backfill")
+ )
+)]
+async fn job_attachments_for_backfill_does_not_leak_other_links(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?;
+ let res = fetch_job_attachments_for_backfill(&pool, link_id).await?;
+
+ assert!(
+ res.iter()
+ .all(|attachment| attachment.filename.as_deref() != Some("other_link_document.pdf"))
+ );
Ok(())
}
@@ -197,6 +361,34 @@ async fn insertable_attachments_condition_2_important_label(pool: Pool<Postgres>
Ok(())
}
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("fetch_insertable_attachments_for_new_email")
+ )
+)]
+async fn insertable_attachments_require_important_label(pool: Pool<Postgres>) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ remove_message_labels(
+ &pool,
+ Uuid::parse_str("00000000-0000-0000-0000-0000000e0201")?,
+ )
+ .await?;
+
+ let res = new_email_document_atts(
+ &pool,
+ Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?,
+ "target-msg-201",
+ )
+ .await?;
+
+ assert!(res.is_empty());
+
+ Ok(())
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
@@ -225,6 +417,56 @@ async fn insertable_attachments_condition_3_same_domain(pool: Pool<Postgres>) ->
Ok(())
}
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("fetch_insertable_attachments_for_new_email")
+ )
+)]
+async fn insertable_attachments_rejects_domain_suffix(pool: Pool<Postgres>) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let res = new_email_document_atts(
+ &pool,
+ Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?,
+ "target-msg-901",
+ )
+ .await?;
+
+ assert!(res.is_empty());
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("fetch_insertable_attachments_for_new_email")
+ )
+)]
+async fn insertable_attachments_matches_domain_case_insensitively(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let res = new_email_document_atts(
+ &pool,
+ Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?,
+ "target-msg-1001",
+ )
+ .await?;
+
+ assert_eq!(res.len(), 1);
+ assert_eq!(
+ res[0].filename,
+ Some("mixed_case_domain_doc.pdf".to_string())
+ );
+
+ Ok(())
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
@@ -263,12 +505,11 @@ async fn insertable_attachments_condition_4_whitelisted_domain(pool: Pool<Postgr
scripts("fetch_insertable_attachments_for_new_email")
)
)]
-async fn insertable_attachments_condition_5_previously_contacted(
+async fn insertable_attachments_condition_5_contacted_participant_claims(
pool: Pool<Postgres>,
) -> Result<()> {
const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
- // Test condition 4: user has previously contacted a thread participant
let message_provider_id = "target-msg-401";
let res = new_email_document_atts(
&pool,
@@ -277,8 +518,6 @@ async fn insertable_attachments_condition_5_previously_contacted(
)
.await?;
- // Should return 1 attachment (previously_contacted_doc.pdf)
- // This should be found by the second query (condition 4)
assert_eq!(res.len(), 1);
assert_eq!(
res[0].filename,
@@ -287,13 +526,58 @@ async fn insertable_attachments_condition_5_previously_contacted(
assert_eq!(res[0].mime_type, "application/pdf");
assert_eq!(res[0].email_provider_id, "target-msg-401");
- let second_res = new_email_document_atts(
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("fetch_insertable_attachments_for_new_email")
+ )
+)]
+async fn insertable_attachments_condition_5_repeated_invocation_does_not_reclaim(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?;
+ let first_res = new_email_document_atts(&pool, link_id, "target-msg-401").await?;
+ let second_res = new_email_document_atts(&pool, link_id, "target-msg-401").await?;
+
+ assert_eq!(first_res.len(), 1);
+ assert!(second_res.is_empty());
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("fetch_insertable_attachments_for_new_email")
+ )
+)]
+async fn insertable_attachments_condition_5_never_contacted_participant_does_not_claim(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let res = new_email_document_atts(
&pool,
- Uuid::parse_str("00000000-0000-0000-0000-00000000001a").unwrap(),
- message_provider_id,
+ Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?,
+ "target-msg-601",
)
.await?;
- assert!(second_res.is_empty());
+
+ assert!(res.is_empty());
+ assert!(
+ !attachment_is_claimed(
+ &pool,
+ Uuid::parse_str("00000000-0000-0000-0000-0000006a0601")?
+ )
+ .await?
+ );
Ok(())
}
@@ -305,20 +589,51 @@ async fn insertable_attachments_condition_5_previously_contacted(
scripts("fetch_insertable_attachments_for_new_email")
)
)]
-async fn insertable_attachments_no_conditions_met(pool: Pool<Postgres>) -> Result<()> {
+async fn insertable_attachments_condition_5_self_is_only_contacted_participant(
+ pool: Pool<Postgres>,
+) -> Result<()> {
const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
- // Test control case: no conditions met
- let message_provider_id = "target-msg-601";
let res = new_email_document_atts(
&pool,
- Uuid::parse_str("00000000-0000-0000-0000-00000000001a").unwrap(),
- message_provider_id,
+ Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?,
+ "target-msg-1101",
)
.await?;
- // Should return 0 attachments
- assert_eq!(res.len(), 0);
+ assert!(res.is_empty());
+ assert!(
+ !attachment_is_claimed(
+ &pool,
+ Uuid::parse_str("00000000-0000-0000-0000-000000aa1101")?
+ )
+ .await?
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("fetch_insertable_attachments_for_new_email")
+ )
+)]
+async fn insertable_attachments_condition_5_missing_self_contact_allows_contacted_participant(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let res = new_email_document_atts(
+ &pool,
+ Uuid::parse_str("00000000-0000-0000-0000-00000000002a")?,
+ "target-msg-1301",
+ )
+ .await?;
+
+ assert_eq!(res.len(), 1);
+ assert_eq!(res[0].filename.as_deref(), Some("missing_self_contact.pdf"));
Ok(())
}
@@ -393,21 +708,46 @@ async fn insertable_attachments_filters_mime_types(pool: Pool<Postgres>) -> Resu
async fn insertable_attachments_thread_exists_logic(pool: Pool<Postgres>) -> Result<()> {
const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
- // Test that attachments are returned when ANY message in the thread meets conditions
- // Even if the specific target message doesn't meet the condition itself
+ let target_message_id = Uuid::parse_str("00000000-0000-0000-0000-0000000e0202")?;
+ sqlx::query!(
+ r#"
+ INSERT INTO email_messages (
+ id, provider_id, thread_id, link_id, from_contact_id, internal_date_ts
+ )
+ VALUES (
+ $1,
+ 'other-msg-202',
+ '00000000-0000-0000-0000-000000000102',
+ '00000000-0000-0000-0000-00000000001a',
+ '00000000-0000-0000-0000-0000000c0002',
+ NOW()
+ )
+ "#,
+ target_message_id
+ )
+ .execute(&pool)
+ .await?;
+
+ sqlx::query!(
+ r#"
+ UPDATE email_attachments
+ SET message_id = $1
+ WHERE message_id = '00000000-0000-0000-0000-0000000e0201'
+ "#,
+ target_message_id
+ )
+ .execute(&pool)
+ .await?;
- // target-msg-202 is in Thread 2, which contains target-msg-201 with IMPORTANT label
- let message_provider_id = "other-msg-202";
let res = new_email_document_atts(
&pool,
- Uuid::parse_str("00000000-0000-0000-0000-00000000001a").unwrap(),
- message_provider_id,
+ Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?,
+ "other-msg-202",
)
.await?;
- // Should return 0 because other-msg-202 has no attachments
- // But the EXISTS clause should still evaluate to true due to target-msg-201 having IMPORTANT
- assert_eq!(res.len(), 0);
+ assert_eq!(res.len(), 1);
+ assert_eq!(res[0].filename, Some("important_doc.pdf".to_string()));
Ok(())
}
diff --git a/crates/email_db_client/src/attachments/provider/upload_filters.rs b/crates/email_db_client/src/attachments/provider/upload_filters.rs
index 1c89d16c6c..f11a30ea41 100644
--- a/crates/email_db_client/src/attachments/provider/upload_filters.rs
+++ b/crates/email_db_client/src/attachments/provider/upload_filters.rs
@@ -94,85 +94,101 @@ pub fn attachment_is_media(mime_type: &str) -> bool {
.any(|prefix| mime_type.starts_with(prefix))
}
-/// always insert attachments sent from these domains.
-pub const ATTACHMENT_WHITELISTED_DOMAINS: &str = r#"
- OR (
- -- condition 4: email from whitelisted domain
- c.email_address IS NOT NULL
- AND (
- c.email_address LIKE '%@docusign.com'
- OR c.email_address LIKE '%@hellosign.com'
- OR c.email_address LIKE '%@dropboxsign.com'
- OR c.email_address LIKE '%@adobesign.com'
- OR c.email_address LIKE '%@signnow.com'
- OR c.email_address LIKE '%@pandadoc.com'
- OR c.email_address LIKE '%@quickbooks.com'
- OR c.email_address LIKE '%@xero.com'
- OR c.email_address LIKE '%@stripe.com'
- OR c.email_address LIKE '%@paypal.com'
- OR c.email_address LIKE '%@squareup.com'
- OR c.email_address LIKE '%@bill.com'
- OR c.email_address LIKE '%@gusto.com'
- OR c.email_address LIKE '%@justworks.com'
- OR c.email_address LIKE '%@rippling.com'
- OR c.email_address LIKE '%@intuit.com'
- OR c.email_address LIKE '%@chase.com'
- OR c.email_address LIKE '%@bankofamerica.com'
- OR c.email_address LIKE '%@wellsfargo.com'
- OR c.email_address LIKE '%@capitalone.com'
- OR c.email_address LIKE '%@amex.com'
- OR c.email_address LIKE '%@citibank.com'
- OR c.email_address LIKE '%@robinhood.com'
- OR c.email_address LIKE '%@etrade.com'
- OR c.email_address LIKE '%@fidelity.com'
- OR c.email_address LIKE '%@schwab.com'
- OR c.email_address LIKE '%@interactivebrokers.com'
- OR c.email_address LIKE '%@vanguard.com'
- OR c.email_address LIKE '%@plaid.com'
- OR c.email_address LIKE '%@irs.gov'
- OR c.email_address LIKE '%@ssa.gov'
- OR c.email_address LIKE '%@uscis.gov'
- OR c.email_address LIKE '%@treasury.gov'
- OR c.email_address LIKE '%@efiletexas.gov'
- OR c.email_address LIKE '%@efilemanager.com'
- OR c.email_address LIKE '%@efile.ca.gov'
- OR c.email_address LIKE '%@sec.gov'
- OR c.email_address LIKE '%@greenhouse.io'
- OR c.email_address LIKE '%@lever.co'
- OR c.email_address LIKE '%@bamboohr.com'
- OR c.email_address LIKE '%@workday.com'
- OR c.email_address LIKE '%@sap.com'
- OR c.email_address LIKE '%@indeed.com'
- OR c.email_address LIKE '%@linkedin.com'
- OR c.email_address LIKE '%@ziprecruiter.com'
- OR c.email_address LIKE '%@docusign.net'
- OR c.email_address LIKE '%@dropbox.com'
- OR c.email_address LIKE '%@box.com'
- OR c.email_address LIKE '%@drive.google.com'
- OR c.email_address LIKE '%@sharepoint.com'
- OR c.email_address LIKE '%@onedrive.live.com'
- OR c.email_address LIKE '%@wetransfer.com'
- OR c.email_address LIKE '%@figma.com'
- OR c.email_address LIKE '%@canva.com'
- OR c.email_address LIKE '%@notion.so'
- OR c.email_address LIKE '%@clickup.com'
- OR c.email_address LIKE '%@airtable.com'
- OR c.email_address LIKE '%@unitedhealthcare.com'
- OR c.email_address LIKE '%@aetna.com'
- OR c.email_address LIKE '%@cigna.com'
- OR c.email_address LIKE '%@metlife.com'
- OR c.email_address LIKE '%@anthem.com'
- OR c.email_address LIKE '%@oscarhealth.com'
- OR c.email_address LIKE '%@delta-dental.com'
- OR c.email_address LIKE '%@vanguardbenefits.com'
- OR c.email_address LIKE '%@fidelitybenefits.com'
- OR c.email_address LIKE '%@aws.amazon.com'
- OR c.email_address LIKE '%@cloudflare.com'
- OR c.email_address LIKE '%@digitalocean.com'
- OR c.email_address LIKE '%@github.com'
- OR c.email_address LIKE '%@gitlab.com'
- OR c.email_address LIKE '%@atlassian.com'
- OR c.email_address LIKE '%@openai.com'
- OR c.email_address LIKE '%@anthropic.com'
- )
- )"#;
+macro_rules! define_attachment_whitelist {
+ ($($domain:literal,)* ; $last_domain:literal) => {
+ /// Domains whose attachments are always inserted.
+ pub const ATTACHMENT_WHITELIST_DOMAINS: &[&str] = &[
+ $($domain,)*
+ $last_domain,
+ ];
+
+ /// SQL predicate for attachments sent from whitelisted domains.
+ pub const ATTACHMENT_WHITELISTED_DOMAINS: &str = concat!(
+ "\n OR (\n",
+ " -- condition 4: email from whitelisted domain\n",
+ " c.email_address IS NOT NULL\n",
+ " AND LOWER(SPLIT_PART(c.email_address, '@', 2)) IN (\n",
+ $(" '", $domain, "',\n",)*
+ " '", $last_domain, "'\n",
+ " )\n",
+ " )",
+ );
+ };
+}
+
+define_attachment_whitelist! {
+ "docusign.com",
+ "hellosign.com",
+ "dropboxsign.com",
+ "adobesign.com",
+ "signnow.com",
+ "pandadoc.com",
+ "quickbooks.com",
+ "xero.com",
+ "stripe.com",
+ "paypal.com",
+ "squareup.com",
+ "bill.com",
+ "gusto.com",
+ "justworks.com",
+ "rippling.com",
+ "intuit.com",
+ "chase.com",
+ "bankofamerica.com",
+ "wellsfargo.com",
+ "capitalone.com",
+ "amex.com",
+ "citibank.com",
+ "robinhood.com",
+ "etrade.com",
+ "fidelity.com",
+ "schwab.com",
+ "interactivebrokers.com",
+ "vanguard.com",
+ "plaid.com",
+ "irs.gov",
+ "ssa.gov",
+ "uscis.gov",
+ "treasury.gov",
+ "efiletexas.gov",
+ "efilemanager.com",
+ "efile.ca.gov",
+ "sec.gov",
+ "greenhouse.io",
+ "lever.co",
+ "bamboohr.com",
+ "workday.com",
+ "sap.com",
+ "indeed.com",
+ "linkedin.com",
+ "ziprecruiter.com",
+ "docusign.net",
+ "dropbox.com",
+ "box.com",
+ "drive.google.com",
+ "sharepoint.com",
+ "onedrive.live.com",
+ "wetransfer.com",
+ "figma.com",
+ "canva.com",
+ "notion.so",
+ "clickup.com",
+ "airtable.com",
+ "unitedhealthcare.com",
+ "aetna.com",
+ "cigna.com",
+ "metlife.com",
+ "anthem.com",
+ "oscarhealth.com",
+ "delta-dental.com",
+ "vanguardbenefits.com",
+ "fidelitybenefits.com",
+ "aws.amazon.com",
+ "cloudflare.com",
+ "digitalocean.com",
+ "github.com",
+ "gitlab.com",
+ "atlassian.com",
+ "openai.com",
+ ; "anthropic.com"
+}
diff --git a/crates/email_db_client/src/attachments/provider/upload_filters/test.rs b/crates/email_db_client/src/attachments/provider/upload_filters/test.rs
index 0a3b8c5895..84faa38843 100644
--- a/crates/email_db_client/src/attachments/provider/upload_filters/test.rs
+++ b/crates/email_db_client/src/attachments/provider/upload_filters/test.rs
@@ -121,3 +121,25 @@ fn media_filter_is_case_sensitive_and_rejects_other_types() {
assert!(!attachment_is_media("application/pdf"));
assert!(!attachment_is_media("text/plain"));
}
+
+#[test]
+fn every_whitelisted_domain_appears_once_in_the_generated_predicate() {
+ for domain in ATTACHMENT_WHITELIST_DOMAINS {
+ let quoted_domain = format!("'{domain}'");
+ assert_eq!(
+ ATTACHMENT_WHITELISTED_DOMAINS
+ .match_indices(&quoted_domain)
+ .count(),
+ 1,
+ "expected {domain} to appear exactly once"
+ );
+ }
+}
+
+#[test]
+fn whitelist_predicate_uses_exact_case_insensitive_domains() {
+ assert!(
+ ATTACHMENT_WHITELISTED_DOMAINS.contains("LOWER(SPLIT_PART(c.email_address, '@', 2)) IN (")
+ );
+ assert!(!ATTACHMENT_WHITELISTED_DOMAINS.contains("LIKE '%@"));
+}
diff --git a/crates/macro_db_client/migrations/20260805175719_make_sent_messages_index_covering.sql b/crates/macro_db_client/migrations/20260805175719_make_sent_messages_index_covering.sql
new file mode 100644
index 0000000000..3e9b692d46
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260805175719_make_sent_messages_index_covering.sql
@@ -0,0 +1,4 @@
+-- no-transaction
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_email_messages_link_id_sent_covering
+ ON email_messages (link_id) INCLUDE (id)
+ WHERE is_sent = true;
diff --git a/crates/macro_db_client/migrations/20260805180650_drop_old_sent_messages_index.sql b/crates/macro_db_client/migrations/20260805180650_drop_old_sent_messages_index.sql
new file mode 100644
index 0000000000..f6c6e20531
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260805180650_drop_old_sent_messages_index.sql
@@ -0,0 +1,2 @@
+-- no-transaction
+DROP INDEX CONCURRENTLY IF EXISTS idx_email_messages_link_id_sent;
diff --git a/crates/macro_db_client/migrations/20260805185740_index_attachment_bearing_email_threads.sql b/crates/macro_db_client/migrations/20260805185740_index_attachment_bearing_email_threads.sql
new file mode 100644
index 0000000000..189cdc8f20
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260805185740_index_attachment_bearing_email_threads.sql
@@ -0,0 +1,4 @@
+-- no-transaction
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_email_messages_link_id_thread_id_has_atts
+ ON email_messages (link_id, thread_id)
+ WHERE has_attachments = true;