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
perf(search): split email contact search into two queries (#2297)
gbirman064406c67589
diff --git a/rust/cloud-storage/email_contact_search/.sqlx/query-60004bd7cba2abe02dd61396b9cd73d9f2aaac7364ab9e58aa0d891fc9e07ef9.json b/rust/cloud-storage/email_contact_search/.sqlx/query-60004bd7cba2abe02dd61396b9cd73d9f2aaac7364ab9e58aa0d891fc9e07ef9.jsondeleted file mode 100644index dcbbbb7056..0000000000--- a/rust/cloud-storage/email_contact_search/.sqlx/query-60004bd7cba2abe02dd61396b9cd73d9f2aaac7364ab9e58aa0d891fc9e07ef9.json+++ /dev/null@@ -1,56 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n WITH matches AS (\n SELECT thread_id, message_id, contact_name, contact_email, contact_type\n FROM email_contact_search_index\n WHERE link_id = (SELECT id FROM email_links WHERE macro_id = $1)\n AND (contact_name ILIKE $2 OR contact_email ILIKE $2)\n ),\n paginated_threads AS (\n SELECT t.id, t.latest_non_spam_message_ts\n FROM email_threads t\n JOIN (SELECT DISTINCT thread_id FROM matches) mt ON mt.thread_id = t.id\n WHERE t.latest_non_spam_message_ts IS NOT NULL\n AND (\n $4::timestamptz IS NULL\n OR (t.latest_non_spam_message_ts, t.id) < ($4, $5)\n )\n ORDER BY t.latest_non_spam_message_ts DESC, t.id DESC\n LIMIT $3\n )\n SELECT\n pt.id as \"thread_id!\",\n pt.latest_non_spam_message_ts as \"updated_at!\",\n m.message_id as \"message_id!\",\n m.contact_name as \"contact_name?\",\n m.contact_email as \"contact_email!\",\n m.contact_type as \"contact_type!\"\n FROM paginated_threads pt\n JOIN matches m ON m.thread_id = pt.id\n ORDER BY pt.latest_non_spam_message_ts DESC, pt.id DESC\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "thread_id!",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "updated_at!",- "type_info": "Timestamptz"- },- {- "ordinal": 2,- "name": "message_id!",- "type_info": "Uuid"- },- {- "ordinal": 3,- "name": "contact_name?",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "contact_email!",- "type_info": "Text"- },- {- "ordinal": 5,- "name": "contact_type!",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "Text",- "Int8",- "Timestamptz",- "Uuid"- ]- },- "nullable": [- false,- true,- false,- true,- false,- false- ]- },- "hash": "60004bd7cba2abe02dd61396b9cd73d9f2aaac7364ab9e58aa0d891fc9e07ef9"-}diff --git a/rust/cloud-storage/email_contact_search/.sqlx/query-de211130c2f52ea8c722382e14f1667389a880beb4e63ce85625b3901670e540.json b/rust/cloud-storage/email_contact_search/.sqlx/query-de211130c2f52ea8c722382e14f1667389a880beb4e63ce85625b3901670e540.jsonnew file mode 100644index 0000000000..4fe5ff4b88--- /dev/null+++ b/rust/cloud-storage/email_contact_search/.sqlx/query-de211130c2f52ea8c722382e14f1667389a880beb4e63ce85625b3901670e540.json@@ -0,0 +1,48 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n ecsi.thread_id as \"thread_id!\",\n ecsi.message_id as \"message_id!\",\n ecsi.contact_name as \"contact_name?\",\n ecsi.contact_email as \"contact_email!\",\n ecsi.contact_type as \"contact_type!\"\n FROM email_contact_search_index ecsi\n WHERE ecsi.link_id = (SELECT id FROM email_links WHERE macro_id = $1)\n AND ecsi.thread_id = ANY($2)\n AND (ecsi.contact_name ILIKE $3 OR ecsi.contact_email ILIKE $3)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "thread_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "message_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "contact_name?",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "contact_email!",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "contact_type!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "UuidArray",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ false,+ false+ ]+ },+ "hash": "de211130c2f52ea8c722382e14f1667389a880beb4e63ce85625b3901670e540"+}diff --git a/rust/cloud-storage/email_contact_search/.sqlx/query-e810dc79f4e3314d1879335813476bb5fbbd9217eda4c91f37a38eda6aec3a4e.json b/rust/cloud-storage/email_contact_search/.sqlx/query-e810dc79f4e3314d1879335813476bb5fbbd9217eda4c91f37a38eda6aec3a4e.jsonnew file mode 100644index 0000000000..8d995ef0b6--- /dev/null+++ b/rust/cloud-storage/email_contact_search/.sqlx/query-e810dc79f4e3314d1879335813476bb5fbbd9217eda4c91f37a38eda6aec3a4e.json@@ -0,0 +1,32 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT t.id as \"thread_id!\", t.latest_non_spam_message_ts as \"updated_at!\"\n FROM email_threads t\n WHERE t.id IN (\n SELECT DISTINCT ecsi.thread_id\n FROM email_contact_search_index ecsi\n WHERE ecsi.link_id = (SELECT id FROM email_links WHERE macro_id = $1)\n AND (ecsi.contact_name ILIKE $2 OR ecsi.contact_email ILIKE $2)\n )\n AND t.latest_non_spam_message_ts IS NOT NULL\n AND (\n $4::timestamptz IS NULL\n OR (t.latest_non_spam_message_ts, t.id) < ($4, $5)\n )\n ORDER BY t.latest_non_spam_message_ts DESC, t.id DESC\n LIMIT $3\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "thread_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "updated_at!",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Int8",+ "Timestamptz",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "e810dc79f4e3314d1879335813476bb5fbbd9217eda4c91f37a38eda6aec3a4e"+}diff --git a/rust/cloud-storage/email_contact_search/fixtures/email_contacts.sql b/rust/cloud-storage/email_contact_search/fixtures/email_contacts.sqlindex 86e676de87..4e6549185f 100644--- a/rust/cloud-storage/email_contact_search/fixtures/email_contacts.sql+++ b/rust/cloud-storage/email_contact_search/fixtures/email_contacts.sql@@ -27,6 +27,10 @@ VALUES-- Contact with NULL name (should use message-level override)('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '00000000-0000-0001-0000-000000000001', '[email protected]', NULL, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),+ -- Contacts for cursor tie-breaking tests+ ('a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1', '00000000-0000-0001-0000-000000000001', '[email protected]', 'Sam Taylor', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),+ ('a2a2a2a2-a2a2-a2a2-a2a2-a2a2a2a2a2a2', '00000000-0000-0001-0000-000000000001', '[email protected]', 'Pat Taylor', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),+-- Contacts for user2's link (for isolation testing)('ffffffff-ffff-ffff-ffff-ffffffffffff', '00000000-0000-0002-0000-000000000002', '[email protected]', 'Frank Wilson', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00');@@ -46,7 +50,12 @@ VALUES('44444444-4444-4444-4444-444444444444', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-03 10:00:00+00', '2024-04-01 10:00:00+00', '2024-12-03 10:00:00+00'),-- Thread 5: Thread with NULL latest_non_spam_message_ts- ('55555555-5555-5555-5555-555555555555', '00000000-0000-0001-0000-000000000001', true, false, NULL, '2024-05-01 10:00:00+00', '2024-05-01 10:00:00+00');+ ('55555555-5555-5555-5555-555555555555', '00000000-0000-0001-0000-000000000001', true, false, NULL, '2024-05-01 10:00:00+00', '2024-05-01 10:00:00+00'),++ -- Threads 6 and 7: Same latest_non_spam_message_ts for cursor tie-breaking tests+ -- Thread 7 has a higher UUID so it sorts first in DESC order+ ('77777777-7777-7777-7777-777777777777', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-02 10:00:00+00', '2024-06-01 10:00:00+00', '2024-12-02 10:00:00+00'),+ ('66666666-6666-6666-6666-666666666666', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-02 10:00:00+00', '2024-06-01 10:00:00+00', '2024-12-02 10:00:00+00');-- Email threads for user2 (for isolation testing)INSERT INTO email_threads (id, link_id, inbox_visible, is_read, latest_non_spam_message_ts, created_at, updated_at)@@ -79,6 +88,16 @@ INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name,VALUES('10000000-0005-0000-0000-000000000001', '55555555-5555-5555-5555-555555555555', '00000000-0000-0001-0000-000000000001', 'dddddddd-dddd-dddd-dddd-dddddddddddd', NULL, 'Subject 5', '2024-05-01 10:00:00+00', false, false, '2024-05-01 10:00:00+00', '2024-05-01 10:00:00+00');+-- Thread 6: Sam Taylor is the sender (tied timestamp with thread 7)+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)+VALUES+ ('10000000-0006-0000-0000-000000000001', '66666666-6666-6666-6666-666666666666', '00000000-0000-0001-0000-000000000001', 'a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1', NULL, 'Subject 6', '2024-06-01 10:00:00+00', false, false, '2024-06-01 10:00:00+00', '2024-06-01 10:00:00+00');++-- Thread 7: Pat Taylor is the sender (tied timestamp with thread 6)+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)+VALUES+ ('10000000-0007-0000-0000-000000000001', '77777777-7777-7777-7777-777777777777', '00000000-0000-0001-0000-000000000001', 'a2a2a2a2-a2a2-a2a2-a2a2-a2a2a2a2a2a2', NULL, 'Subject 7', '2024-06-01 10:00:00+00', false, false, '2024-06-01 10:00:00+00', '2024-06-01 10:00:00+00');+-- Email messages for user2's threads (for isolation testing)INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)VALUESdiff --git a/rust/cloud-storage/email_contact_search/src/lib.rs b/rust/cloud-storage/email_contact_search/src/lib.rsindex 24b3c2b7a4..c5909c46d0 100644--- a/rust/cloud-storage/email_contact_search/src/lib.rs+++ b/rust/cloud-storage/email_contact_search/src/lib.rs@@ -110,36 +110,26 @@ pub async fn search_email_contacts<'a>(// Fetch limit + 1 to determine if there are more resultslet fetch_limit = limit as i64 + 1;- let rows = sqlx::query!(+ // Find threads with matching contacts, sorted by most recent activity.+ // Uses trigram indexes on contact_name/email for the ILIKE search, then+ // joins email_threads for timestamp-based ordering and cursor pagination.+ let thread_rows = sqlx::query!(r#"- WITH matches AS (- SELECT thread_id, message_id, contact_name, contact_email, contact_type- FROM email_contact_search_index- WHERE link_id = (SELECT id FROM email_links WHERE macro_id = $1)- AND (contact_name ILIKE $2 OR contact_email ILIKE $2)- ),- paginated_threads AS (- SELECT t.id, t.latest_non_spam_message_ts- FROM email_threads t- JOIN (SELECT DISTINCT thread_id FROM matches) mt ON mt.thread_id = t.id- WHERE t.latest_non_spam_message_ts IS NOT NULL- AND (- $4::timestamptz IS NULL- OR (t.latest_non_spam_message_ts, t.id) < ($4, $5)- )- ORDER BY t.latest_non_spam_message_ts DESC, t.id DESC- LIMIT $3+ SELECT t.id as "thread_id!", t.latest_non_spam_message_ts as "updated_at!"+ FROM email_threads t+ WHERE t.id IN (+ SELECT DISTINCT ecsi.thread_id+ FROM email_contact_search_index ecsi+ WHERE ecsi.link_id = (SELECT id FROM email_links WHERE macro_id = $1)+ AND (ecsi.contact_name ILIKE $2 OR ecsi.contact_email ILIKE $2))- SELECT- pt.id as "thread_id!",- pt.latest_non_spam_message_ts as "updated_at!",- m.message_id as "message_id!",- m.contact_name as "contact_name?",- m.contact_email as "contact_email!",- m.contact_type as "contact_type!"- FROM paginated_threads pt- JOIN matches m ON m.thread_id = pt.id- ORDER BY pt.latest_non_spam_message_ts DESC, pt.id DESC+ AND t.latest_non_spam_message_ts IS NOT NULL+ AND (+ $4::timestamptz IS NULL+ OR (t.latest_non_spam_message_ts, t.id) < ($4, $5)+ )+ ORDER BY t.latest_non_spam_message_ts DESC, t.id DESC+ LIMIT $3"#,macro_user_id.as_ref(),search_pattern,@@ -150,52 +140,85 @@ pub async fn search_email_contacts<'a>(.fetch_all(db).await?;- let results: Vec<EmailContactMatchThreadResult> = rows- .into_iter()- .map(|row| EmailContactMatchThreadResult {+ let thread_entries: Vec<ThreadPaginationEntry> = thread_rows+ .iter()+ .map(|row| ThreadPaginationEntry {thread_id: row.thread_id,- message_id: row.message_id,- contact_name: row.contact_name,- contact_email: row.contact_email,- contact_type: match row.contact_type.as_str() {- "TO" => ContactType::To,- "CC" => ContactType::Cc,- "BCC" => ContactType::Bcc,- _ => ContactType::From,- },updated_at: row.updated_at,}).collect();- // Collect unique threads for pagination (preserving order)- let mut seen_threads = std::collections::HashSet::new();- let thread_entries: Vec<ThreadPaginationEntry> = results+ let paginated_threads = SearchCursorOption::paginate(thread_entries, limit as usize);++ let thread_ids: Vec<uuid::Uuid> = paginated_threads+ .items.iter()- .filter(|r| seen_threads.insert(r.thread_id))- .map(|r| ThreadPaginationEntry {- thread_id: r.thread_id,- updated_at: r.updated_at,- })+ .map(|t| t.thread_id).collect();- // Use paginate helper to determine cursor- let paginated_threads = SearchCursorOption::paginate(thread_entries, limit as usize);+ if thread_ids.is_empty() {+ return Ok(PaginatedResult {+ items: vec![],+ cursor: paginated_threads.cursor,+ });+ }- // Get the thread IDs we want to keep- let threads_to_keep: std::collections::HashSet<_> = paginated_threads+ let thread_ts_map: std::collections::HashMap<uuid::Uuid, DateTime<Utc>> = paginated_threads.items.iter()- .map(|t| t.thread_id)+ .map(|t| (t.thread_id, t.updated_at)).collect();- // Filter results to only include matches from kept threads- let filtered_results: Vec<_> = results+ // Fetch contact details for the paginated threads using the idx_ecsi_link_thread+ // btree index. This avoids re-running the expensive trigram scan from the previous query.+ let contact_rows = sqlx::query!(+ r#"+ SELECT+ ecsi.thread_id as "thread_id!",+ ecsi.message_id as "message_id!",+ ecsi.contact_name as "contact_name?",+ ecsi.contact_email as "contact_email!",+ ecsi.contact_type as "contact_type!"+ FROM email_contact_search_index ecsi+ WHERE ecsi.link_id = (SELECT id FROM email_links WHERE macro_id = $1)+ AND ecsi.thread_id = ANY($2)+ AND (ecsi.contact_name ILIKE $3 OR ecsi.contact_email ILIKE $3)+ "#,+ macro_user_id.as_ref(),+ &thread_ids,+ search_pattern,+ )+ .fetch_all(db)+ .await?;++ let mut results: Vec<EmailContactMatchThreadResult> = contact_rows.into_iter()- .filter(|r| threads_to_keep.contains(&r.thread_id))+ .filter_map(|row| {+ let updated_at = *thread_ts_map.get(&row.thread_id)?;+ Some(EmailContactMatchThreadResult {+ thread_id: row.thread_id,+ message_id: row.message_id,+ contact_name: row.contact_name,+ contact_email: row.contact_email,+ contact_type: match row.contact_type.as_str() {+ "TO" => ContactType::To,+ "CC" => ContactType::Cc,+ "BCC" => ContactType::Bcc,+ _ => ContactType::From,+ },+ updated_at,+ })+ }).collect();+ results.sort_by(|a, b| {+ b.updated_at+ .cmp(&a.updated_at)+ .then(b.thread_id.cmp(&a.thread_id))+ });+Ok(PaginatedResult {- items: filtered_results,+ items: results,cursor: paginated_threads.cursor,})}diff --git a/rust/cloud-storage/email_contact_search/src/test.rs b/rust/cloud-storage/email_contact_search/src/test.rsindex fbc384cbef..ebce400083 100644--- a/rust/cloud-storage/email_contact_search/src/test.rs+++ b/rust/cloud-storage/email_contact_search/src/test.rs@@ -484,3 +484,58 @@ async fn test_search_email_contacts_by_email_address(pool: Pool<Postgres>) -> anOk(())}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_cursor_tiebreak_on_identical_timestamps(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ // Threads 6 (66666666) and 7 (77777777) both have latest_non_spam_message_ts = 2024-12-02.+ // ORDER BY ts DESC, id DESC means thread 7 (higher UUID) comes first.+ let thread_7 = uuid::Uuid::parse_str("77777777-7777-7777-7777-777777777777").unwrap();+ let thread_6 = uuid::Uuid::parse_str("66666666-6666-6666-6666-666666666666").unwrap();++ // Page 1: limit=1 should return thread 7+ let page1 =+ search_email_contacts(&pool, user_id.clone(), "Taylor".to_string(), 1, None).await?;++ let page1_thread_ids: Vec<_> = {+ let mut seen = std::collections::HashSet::new();+ page1+ .items+ .iter()+ .filter(|r| seen.insert(r.thread_id))+ .map(|r| r.thread_id)+ .collect()+ };+ assert_eq!(page1_thread_ids, vec![thread_7]);+ assert!(page1.cursor.has_more());++ // Page 2: should return thread 6+ let cursor = match page1.cursor {+ SearchCursorOption::NotDone(c) => c,+ SearchCursorOption::Done => panic!("Expected more results"),+ };++ let page2 = search_email_contacts(&pool, user_id, "Taylor".to_string(), 1, cursor).await?;++ let page2_thread_ids: Vec<_> = {+ let mut seen = std::collections::HashSet::new();+ page2+ .items+ .iter()+ .filter(|r| seen.insert(r.thread_id))+ .map(|r| r.thread_id)+ .collect()+ };+ assert_eq!(page2_thread_ids, vec![thread_6]);+ assert!(page2.cursor.is_done());++ Ok(())+}diff --git a/rust/cloud-storage/macro_db_client/migrations/20260331150856_email_contact_search_index_link_thread.sql b/rust/cloud-storage/macro_db_client/migrations/20260331150856_email_contact_search_index_link_thread.sqlnew file mode 100644index 0000000000..3425db7080--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260331150856_email_contact_search_index_link_thread.sql@@ -0,0 +1,4 @@+-- no-transaction++CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ecsi_link_thread+ON email_contact_search_index (link_id, thread_id);