Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(email-service): Attachment upload race condition (#1350)
Evan Hutnikd678276b97e7
diff --git a/rust/cloud-storage/email_db_client/fixtures/upload_claim_tests.sql b/rust/cloud-storage/email_db_client/fixtures/upload_claim_tests.sqlnew file mode 100644index 0000000000..5986ca422e--- /dev/null+++ b/rust/cloud-storage/email_db_client/fixtures/upload_claim_tests.sql@@ -0,0 +1,160 @@+-- SQL fixture for upload claim tests+-- Tests that new_email_document_atts and new_email_media_atts atomically claim attachments++------------------------------------------------------------+-- 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-000000000c01', 'macro|[email protected]', '00000000-0000-0000-0000-000000000c01',+ '[email protected]', 'GMAIL', true, NOW(), NOW());++------------------------------------------------------------+-- Contacts+------------------------------------------------------------++INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-00000c0c0001',+ '00000000-0000-0000-0000-000000000c01',+ '[email protected]',+ NOW(), NOW());++------------------------------------------------------------+-- Thread for document claim test+------------------------------------------------------------++INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-00000000c101',+ '00000000-0000-0000-0000-000000000c01',+ false, false, NOW(), NOW());++-- Message with document attachment (is_sent = true to meet condition 1)+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-0000000ec101',+ '00000000-0000-0000-0000-00000000c101',+ '00000000-0000-0000-0000-000000000c01',+ 'claim-test-doc-msg',+ TRUE,+ '00000000-0000-0000-0000-00000c0c0001',+ '2025-01-01 10:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- Document attachment to be claimed+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-00000c1a0101',+ '00000000-0000-0000-0000-0000000ec101',+ 'claim-test-doc-att',+ 'claimable_doc.pdf',+ 'application/pdf',+ NOW());++-- Second document attachment to test multiple claims+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-00000c1a0102',+ '00000000-0000-0000-0000-0000000ec101',+ 'claim-test-doc-att-2',+ 'claimable_doc_2.pdf',+ 'application/pdf',+ NOW());++------------------------------------------------------------+-- Thread for media claim test+------------------------------------------------------------++INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-00000000c201',+ '00000000-0000-0000-0000-000000000c01',+ false, false, NOW(), NOW());++-- Message with media attachment+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-0000000ec201',+ '00000000-0000-0000-0000-00000000c201',+ '00000000-0000-0000-0000-000000000c01',+ 'claim-test-media-msg',+ FALSE,+ '00000000-0000-0000-0000-00000c0c0001',+ '2025-01-01 11:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- Media attachment to be claimed+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-00000c2a0201',+ '00000000-0000-0000-0000-0000000ec201',+ 'claim-test-media-att',+ 'claimable_image.jpg',+ 'image/jpeg',+ NOW());++-- Second media attachment+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-00000c2a0202',+ '00000000-0000-0000-0000-0000000ec201',+ 'claim-test-media-att-2',+ 'claimable_video.mp4',+ 'video/mp4',+ NOW());++------------------------------------------------------------+-- Thread for pre-claimed attachment test+------------------------------------------------------------++INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-00000000c301',+ '00000000-0000-0000-0000-000000000c01',+ false, false, NOW(), NOW());++-- Message with pre-claimed attachment (is_sent = true to meet condition 1)+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-0000000ec301',+ '00000000-0000-0000-0000-00000000c301',+ '00000000-0000-0000-0000-000000000c01',+ 'claim-test-preclaimed-msg',+ TRUE,+ '00000000-0000-0000-0000-00000c0c0001',+ '2025-01-01 12:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- Pre-claimed document attachment (already has upload_claimed_at set)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, upload_claimed_at, created_at)+VALUES ('00000000-0000-0000-0000-00000c3a0301',+ '00000000-0000-0000-0000-0000000ec301',+ 'claim-test-preclaimed-att',+ 'preclaimed_doc.pdf',+ 'application/pdf',+ NOW(),+ NOW());++------------------------------------------------------------+-- Thread for pre-claimed media test+------------------------------------------------------------++INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-00000000c401',+ '00000000-0000-0000-0000-000000000c01',+ false, false, NOW(), NOW());++-- Message with pre-claimed media attachment+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-0000000ec401',+ '00000000-0000-0000-0000-00000000c401',+ '00000000-0000-0000-0000-000000000c01',+ 'claim-test-preclaimed-media-msg',+ FALSE,+ '00000000-0000-0000-0000-00000c0c0001',+ '2025-01-01 13:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- Pre-claimed media attachment (already has upload_claimed_at set)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, upload_claimed_at, created_at)+VALUES ('00000000-0000-0000-0000-00000c4a0401',+ '00000000-0000-0000-0000-0000000ec401',+ 'claim-test-preclaimed-media-att',+ 'preclaimed_image.jpg',+ 'image/jpeg',+ NOW(),+ NOW());diff --git a/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rs b/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rsindex 6547f417ba..0746f1eb69 100644--- a/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rs+++ b/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rs@@ -217,15 +217,18 @@ pub async fn fetch_job_attachments_for_backfill(Ok(attachments)}-/// fetch attachments for a specific message to upload to Macro. This is called when a new email is-/// inserted for a user. Attachments for the message should be uploaded if any message in the-/// message's thread meets any of the following criteria:+/// Fetch and atomically claim attachments for a specific message to upload to Macro.+/// This is called when a new email is inserted for a user. Attachments for the message+/// should be uploaded if any message in the message's thread meets any of the following criteria:/// 1. the user sent the message/// 2. the message has the IMPORTANT label/// 3. the message came from someone with the same domain as the user/// 4. the domain the email was sent from is part of the whitelisted domains/// 5. the user has previously sent a message to any participant in the thread///+/// The query atomically claims attachments (sets upload_claimed_at) to prevent duplicate+/// uploads from concurrent workers processing the same message.+////// For simplicity's sake, conditions 1 2 3 and 4 are evaluated in the first query, and condition 5/// is evaluated in a separate query. These queries are very similar to fetch_thread_attachments_for_backfill/// and fetch_job_attachments_for_backfill respectively, except they also verify the attachment@@ -235,9 +238,46 @@ pub async fn new_email_document_atts(db: &Pool<Postgres>,message_provider_id: &str,) -> anyhow::Result<Vec<AttachmentUploadMetadata>> {- // query for conditions 1 2 and 3+ // query for conditions 1-4: claim attachments atomically and return metadatalet query1 = format!(r#"+ WITH 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+ LEFT JOIN document_email de ON de.email_attachment_id = a.id+ WHERE m.provider_id = $1+ AND a.filename IS NOT NULL+ {}+ 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))+ )+ {}+ )+ )+ )+ RETURNING id+ )SELECTa.id AS attachment_db_id,m.provider_id as email_provider_id,@@ -252,35 +292,7 @@ pub async fn new_email_document_atts(FROM email_attachments aJOIN email_messages m ON a.message_id = m.idJOIN email_contacts from_contact ON m.from_contact_id = from_contact.id- LEFT JOIN document_email de ON de.email_attachment_id = a.id- WHERE m.provider_id = $1- AND a.filename IS NOT NULL- -- attachment mime type filters injected below- {}- AND de.email_attachment_id IS NULL- 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 = m.thread_id -- check against the message's thread- 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))- )- -- whitelisted domain check injected below- {}- )- )+ WHERE a.id IN (SELECT id FROM claimed)ORDER BY a.id"#,ATTACHMENT_MIME_TYPE_FILTERS, ATTACHMENT_WHITELISTED_DOMAINS@@ -296,57 +308,66 @@ pub async fn new_email_document_atts(.map(map_row_to_attachment_metadata).collect();- // if one or more condition has already been met, return - don't need to check condition 5+ // if one or more condition has already been met, returnif !attachments.is_empty() {return Ok(attachments);}- // query for condition 4+ // query for condition 5: claim attachments atomically and return metadatalet query2 = format!(r#"- -- Step 1: Get the user's own email address and thread_id from the messageWITHmessage_info AS (SELECT m.thread_id, l.email_address as user_email, m.link_id- FROM public.email_messages m- JOIN public.email_threads t ON m.thread_id = t.id- JOIN public.email_links l ON t.link_id = l.id+ FROM email_messages m+ JOIN email_threads t ON m.thread_id = t.id+ JOIN email_links l ON t.link_id = l.idWHERE m.provider_id = $1),-- -- 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+ FROM email_messages em+ JOIN email_message_recipients emr ON em.id = emr.message_id+ JOIN email_contacts ec ON emr.contact_id = ec.idWHERE em.link_id = (SELECT link_id FROM message_info)AND em.is_sent = trueAND ec.email_address != (SELECT user_email FROM message_info)),-- -- Step 3: For the message's thread, create a complete list of OTHER participant email addresses.thread_participants AS (- -- Get all senders in the thread (excluding the user)SELECT DISTINCT ec.email_address- FROM public.email_messages em- JOIN public.email_contacts ec ON em.from_contact_id = ec.id+ FROM email_messages em+ JOIN email_contacts ec ON em.from_contact_id = ec.idWHERE em.thread_id = (SELECT thread_id FROM message_info)AND ec.email_address != (SELECT user_email FROM message_info)-UNION-- -- Get all recipients in the thread (excluding the user)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+ FROM email_messages em+ JOIN email_message_recipients emr ON em.id = emr.message_id+ JOIN email_contacts ec ON emr.contact_id = ec.idWHERE em.thread_id = (SELECT thread_id FROM message_info)AND ec.email_address != (SELECT user_email FROM message_info)+ ),+ 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+ LEFT JOIN document_email de ON de.email_attachment_id = a.id+ WHERE m.provider_id = $1+ AND de.email_attachment_id IS NULL+ AND a.upload_claimed_at IS NULL+ AND a.filename IS NOT NULL+ {}+ AND EXISTS (+ SELECT 1+ FROM thread_participants tp+ INNER JOIN previously_contacted_emails pce ON tp.email_address = pce.email_address+ )+ )+ RETURNING id)-- -- Final Step: Select attachments from the specific message if AT LEAST ONE of the OTHER participants- -- in the thread is in the list of OTHER previously_contacted_emails.SELECTa.id AS attachment_db_id,m.provider_id as email_provider_id,@@ -358,20 +379,10 @@ pub async fn new_email_document_atts(m.thread_id as thread_db_id,from_contact.email_address as sender_email,m.subject as subject- 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- LEFT JOIN public.document_email de ON de.email_attachment_id = a.id- WHERE m.provider_id = $1- AND de.email_attachment_id IS NULL- AND EXISTS (- SELECT 1- FROM thread_participants tp- INNER JOIN previously_contacted_emails pce ON tp.email_address = pce.email_address- )- -- attachment mime type filters injected below- {}- AND a.filename IS NOT NULL+ 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+ WHERE a.id IN (SELECT id FROM claimed)ORDER BY a.id"#,ATTACHMENT_MIME_TYPE_FILTERS@@ -390,15 +401,33 @@ pub async fn new_email_document_atts(Ok(attachments)}-/// fetch videos and inline images for a new email for insertion into sfs. we insert them into-/// sfs so we can display thumbnails for them in the FE.+/// Fetch and atomically claim videos and inline images for a new email for insertion into sfs.+/// We insert them into sfs so we can display thumbnails for them in the FE.+///+/// The query atomically claims attachments (sets upload_claimed_at) to prevent duplicate+/// uploads from concurrent workers processing the same message.#[tracing::instrument(skip(db), err)]pub async fn new_email_media_atts(db: &Pool<Postgres>,message_provider_id: &str,) -> anyhow::Result<Vec<AttachmentUploadMetadata>> {- let query1 = format!(+ let query = format!(r#"+ WITH 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+ LEFT JOIN email_attachments_sfs eas ON eas.attachment_id = a.id+ WHERE m.provider_id = $1+ AND {}+ AND eas.attachment_id IS NULL+ AND a.upload_claimed_at IS NULL+ )+ RETURNING id+ )SELECTa.id AS attachment_db_id,m.provider_id as email_provider_id,@@ -413,22 +442,18 @@ pub async fn new_email_media_atts(FROM email_attachments aJOIN email_messages m ON a.message_id = m.idJOIN email_contacts from_contact ON m.from_contact_id = from_contact.id- LEFT JOIN email_attachments_sfs eas ON eas.attachment_id = a.id- WHERE m.provider_id = $1- -- attachment mime type filters injected below- AND {}- AND eas.attachment_id IS NULL+ WHERE a.id IN (SELECT id FROM claimed)ORDER BY a.id"#,ATTACHMENT_MIME_TYPE_FILTERS_WITH_MEDIA);- let rows = sqlx::query(&query1)+ let rows = sqlx::query(&query).bind(message_provider_id).fetch_all(db).await?;- let attachments: Vec<AttachmentUploadMetadata> = rows+ let attachments = rows.into_iter().map(map_row_to_attachment_metadata).collect();diff --git a/rust/cloud-storage/email_db_client/src/attachments/provider/upload/test.rs b/rust/cloud-storage/email_db_client/src/attachments/provider/upload/test.rsindex 5c97e64da8..8e4cfc3e6a 100644--- a/rust/cloud-storage/email_db_client/src/attachments/provider/upload/test.rs+++ b/rust/cloud-storage/email_db_client/src/attachments/provider/upload/test.rs@@ -562,3 +562,129 @@ async fn new_email_media_returns_empty_for_nonexistent_message(pool: Pool<PostgrOk(())}++// ============================================================================+// Upload claim tests - verify attachments are atomically claimed+// ============================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("upload_claim_tests"))+)]+async fn new_email_document_atts_claims_attachments(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let message_provider_id = "claim-test-doc-msg";++ // First call should return attachments and claim them+ let res = new_email_document_atts(&pool, message_provider_id).await?;+ assert_eq!(res.len(), 2);++ // Verify the attachments were claimed (upload_claimed_at is now set)+ let attachment_ids: Vec<Uuid> = res.iter().map(|a| a.attachment_db_id).collect();+ for attachment_id in &attachment_ids {+ let row: (Option<chrono::DateTime<chrono::Utc>>,) =+ sqlx::query_as(r#"SELECT upload_claimed_at FROM email_attachments WHERE id = $1"#)+ .bind(attachment_id)+ .fetch_one(&pool)+ .await?;+ assert!(+ row.0.is_some(),+ "Attachment should have upload_claimed_at set after being returned"+ );+ }++ // Second call should return empty (attachments already claimed)+ let res2 = new_email_document_atts(&pool, message_provider_id).await?;+ assert_eq!(+ res2.len(),+ 0,+ "Second call should return empty since attachments are already claimed"+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("upload_claim_tests"))+)]+async fn new_email_media_atts_claims_attachments(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let message_provider_id = "claim-test-media-msg";++ // First call should return attachments and claim them+ let res = new_email_media_atts(&pool, message_provider_id).await?;+ assert_eq!(res.len(), 2);++ // Verify the attachments were claimed (upload_claimed_at is now set)+ let attachment_ids: Vec<Uuid> = res.iter().map(|a| a.attachment_db_id).collect();+ for attachment_id in &attachment_ids {+ let row: (Option<chrono::DateTime<chrono::Utc>>,) =+ sqlx::query_as(r#"SELECT upload_claimed_at FROM email_attachments WHERE id = $1"#)+ .bind(attachment_id)+ .fetch_one(&pool)+ .await?;+ assert!(+ row.0.is_some(),+ "Attachment should have upload_claimed_at set after being returned"+ );+ }++ // Second call should return empty (attachments already claimed)+ let res2 = new_email_media_atts(&pool, message_provider_id).await?;+ assert_eq!(+ res2.len(),+ 0,+ "Second call should return empty since attachments are already claimed"+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("upload_claim_tests"))+)]+async fn new_email_document_atts_excludes_preclaimed_attachments(+ pool: Pool<Postgres>,+) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ // This message has an attachment that was pre-claimed (upload_claimed_at already set)+ let message_provider_id = "claim-test-preclaimed-msg";++ let res = new_email_document_atts(&pool, message_provider_id).await?;++ // Should return 0 attachments since the attachment is already claimed+ assert_eq!(+ res.len(),+ 0,+ "Pre-claimed attachments should not be returned"+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("upload_claim_tests"))+)]+async fn new_email_media_atts_excludes_preclaimed_attachments(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ // This message has an attachment that was pre-claimed (upload_claimed_at already set)+ let message_provider_id = "claim-test-preclaimed-media-msg";++ let res = new_email_media_atts(&pool, message_provider_id).await?;++ // Should return 0 attachments since the attachment is already claimed+ assert_eq!(+ res.len(),+ 0,+ "Pre-claimed attachments should not be returned"+ );++ Ok(())+}diff --git a/rust/cloud-storage/macro_db_client/migrations/20260204000000_add_document_upload_claimed_at.sql b/rust/cloud-storage/macro_db_client/migrations/20260204000000_add_document_upload_claimed_at.sqlnew file mode 100644index 0000000000..5df842f314--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260204000000_add_document_upload_claimed_at.sql@@ -0,0 +1 @@+ALTER TABLE email_attachments ADD COLUMN upload_claimed_at TIMESTAMPTZ;