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): defer email_user_history join past candidate LIMIT (#4290)
Evan Hutnik3c8872df2418
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rsindex 7d0f53f2cf..22cedbffcd 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs@@ -39,6 +39,16 @@ enum ThreadCandidateSource {Shared,}+/// `email_user_history` (`uh`) only drives ordering/cursoring for the+/// viewed-based sort modes. For every other mode it supplies just the+/// `viewed_at` output column, so the join can be deferred until after the+/// candidate `LIMIT` — joining once per returned row instead of once per+/// candidate thread. Returns true when the join must stay in the candidate+/// stage (i.e. it cannot be deferred).+fn sort_uses_view_history(sort_method_str: &str) -> bool {+ matches!(sort_method_str, "viewed_at" | "viewed_updated")+}+/// Pushes the `user_source_ids AS (…), SharedEmailThreads AS (…)` CTE pair/// (without the leading `WITH` keyword and without trailing comma) into the/// builder. Caller is responsible for emitting the `WITH` keyword and any@@ -83,6 +93,8 @@ fn push_thread_candidate_select(sort_ts_field: &str,source: ThreadCandidateSource,) {+ let defer_uh = !sort_uses_view_history(¶ms.sort_method_str);+builder.push(r#"SELECT@@ -95,25 +107,39 @@ fn push_thread_candidate_select("#,);- builder.push(format!(- r#"+ if defer_uh {+ // viewed-history isn't the sort key here, so `viewed_at` is projected+ // by the deferred outer join (see build_query) and effective_ts+ // collapses to the plain sort field — no `uh` reference in the+ // candidate stage.+ builder.push(format!(+ r#"+ {field} AS created_at,+ t.updated_at AS updated_at,+ {field} AS effective_ts"#,+ field = sort_ts_field+ ));+ } else {+ builder.push(format!(+ r#"{} AS created_at,t.updated_at AS updated_at,uh.updated_at AS viewed_at,CASE "#,- sort_ts_field- ));+ sort_ts_field+ ));- builder.push_bind(params.sort_method_str.clone());+ builder.push_bind(params.sort_method_str.clone());- builder.push(format!(- r#"+ builder.push(format!(+ r#"WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, {})ELSE {}END AS effective_ts"#,- sort_ts_field, sort_ts_field- ));+ sort_ts_field, sort_ts_field+ ));+ }// Team-scoped queries return one thread copy per team member on the// same conversation. Dedupe on the root message's RFC-822 Message-ID@@ -140,13 +166,22 @@ fn push_thread_candidate_select(builder.push(") AS is_own_link");}- builder.push(- r#"+ if defer_uh {+ builder.push(+ r#"+ FROM email_threads t+ WHERE+ "#,+ );+ } else {+ builder.push(+ r#"FROM email_threads tLEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_idWHERE"#,- );+ );+ }match source {ThreadCandidateSource::Owned => match params.team_id {@@ -224,6 +259,28 @@ fn push_thread_candidate_select(return;}+ if defer_uh {+ // effective_ts == sort_ts_field for these modes, so the cursor+ // compares the plain sort field directly — no `uh` reference.+ builder.push(+ r#"+ -- Cursor logic+ AND (("#,+ );+ builder.push_bind(params.cursor_timestamp);+ builder.push(format!(+ r#"::timestamptz IS NULL) OR (({}, t.id) < ("#,+ sort_ts_field+ ));+ builder.push_bind(params.cursor_timestamp);+ builder.push("::timestamptz, ");+ builder.push_bind(params.cursor_id_str.clone());+ // Three closes: right row operand, the grouped row-comparison, the+ // outer AND-group opened by `AND ((`.+ builder.push("::uuid)))");+ return;+ }+builder.push(r#"-- Cursor logic@@ -264,6 +321,10 @@ fn build_query() -> QueryBuilder<'static, Postgres> {let sort_ts_field = get_sort_timestamp_field(view);let view_message_filter = build_view_message_filter(view);+ // When viewed-history isn't the sort key, the `email_user_history` join is+ // pushed past the candidate `LIMIT` so it runs once per returned row+ // instead of once per candidate thread (see `sort_uses_view_history`).+ let defer_uh = !sort_uses_view_history(¶ms.sort_method_str);let needs_shared_cte = !matches!(params.shared, SharedEmailFilter::Exclude);// When the candidate stage pushes a full per-message EXISTS (importance,@@ -305,7 +366,20 @@ fn build_query(t.effective_ts AS sort_ts,t.created_at,t.updated_at,- t.viewed_at,+ "#,+ );++ // viewed_at comes from the deferred outer join (added below) when the sort+ // mode allowed deferral; otherwise it was computed per candidate as+ // `t.viewed_at`.+ if defer_uh {+ builder.push("uh.updated_at AS viewed_at,");+ } else {+ builder.push("t.viewed_at,");+ }++ builder.push(+ r#"t.project_id,lmp.subject AS name,lmp.snippet,@@ -460,7 +534,22 @@ fn build_query(LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id-- Step 4: Join to get the thread owner's macro user IDJOIN email_links el ON t.link_id = el.id- ORDER BY t.effective_ts DESC, t.id DESC+ "#,+ );++ // Step 5 (deferred): attach the caller's per-thread viewed_at. Kept out of+ // the candidate stage so it runs once per returned row rather than once per+ // candidate thread. `email_user_history` is unique per (link_id, thread_id),+ // so this LEFT JOIN can neither drop nor duplicate rows.+ if defer_uh {+ builder.push(+ r#" LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id+ "#,+ );+ }++ builder.push(+ r#" ORDER BY t.effective_ts DESC, t.id DESC"#,);@@ -481,7 +570,28 @@ pub(super) fn debug_build_query_sql_with_resolved(email_filter: &Expr<EmailLiteral>,resolved: ResolvedFilters,) -> String {- debug_build_query_sql_inner(view, email_filter, resolved, None)+ debug_build_query_sql_inner(+ view,+ email_filter,+ resolved,+ None,+ SimpleSortMethod::UpdatedAt,+ )+}++#[cfg(test)]+pub(super) fn debug_build_query_sql_with_sort(+ view: &PreviewView,+ email_filter: &Expr<EmailLiteral>,+ sort_method: SimpleSortMethod,+) -> String {+ debug_build_query_sql_inner(+ view,+ email_filter,+ ResolvedFilters::empty(),+ None,+ sort_method,+ )}#[cfg(test)]@@ -494,6 +604,7 @@ pub(super) fn debug_build_query_sql_team_scoped(email_filter,ResolvedFilters::empty(),Some(Uuid::nil()),+ SimpleSortMethod::UpdatedAt,)}@@ -503,6 +614,7 @@ fn debug_build_query_sql_inner(email_filter: &Expr<EmailLiteral>,resolved: ResolvedFilters,team_id: Option<Uuid>,+ sort_method: SimpleSortMethod,) -> String {use sqlx::Execute;@@ -517,7 +629,7 @@ fn debug_build_query_sql_inner(email_filter,QueryParams {link_ids: vec![Uuid::nil()],- sort_method_str: SimpleSortMethod::UpdatedAt.to_string(),+ sort_method_str: sort_method.to_string(),query_limit: 50,cursor_timestamp: None,cursor_id_str: None,diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rsindex cbd7be0a29..96019e3633 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs@@ -621,8 +621,80 @@ fn test_build_query_non_team_has_no_dedupe_machinery() {assert!(!sql.contains("DISTINCT ON"));assert!(!sql.contains("dedupe_key"));assert!(!sql.contains("is_own_link"));- // Cursor stays inside the candidate select on the per-mailbox path.- assert!(sql.contains("END, t.id"));+ // Cursor stays inside the candidate select on the per-mailbox path+ // (contrast with the team path, which moves it past the dedupe wrapper).+ // The default UpdatedAt sort defers the uh join, so the cursor is a plain+ // (ts, id) comparison rather than the viewed-history CASE.+ let cursor_pos = sql+ .find(", t.id) < (")+ .expect("per-mailbox cursor comparison missing");+ let lateral_pos = sql.find("CROSS JOIN LATERAL").expect("lateral missing");+ assert!(+ cursor_pos < lateral_pos,+ "cursor must sit inside the candidate select: {sql}"+ );+}++#[test]+fn test_build_query_defers_user_history_join_for_updated_at_sort() {+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Sent);+ let expr = Expr::Literal(EmailLiteral::Sender(Email::Domain("acme.com".to_string())));+ let sql = super::query::debug_build_query_sql_with_sort(+ &view,+ &expr,+ models_pagination::SimpleSortMethod::UpdatedAt,+ );++ // Exactly one uh join, deferred to the outer query (after email_links)+ // rather than living in the candidate stage.+ assert_eq!(+ sql.matches("LEFT JOIN email_user_history").count(),+ 1,+ "expected a single, deferred uh join: {sql}"+ );+ let uh_pos = sql.find("LEFT JOIN email_user_history").unwrap();+ let el_pos = sql.find("JOIN email_links el").unwrap();+ assert!(+ uh_pos > el_pos,+ "uh join must be deferred past the candidate LIMIT: {sql}"+ );++ // Sort/cursor no longer reference uh; effective_ts is the plain sort field,+ // and viewed_at is sourced from the deferred join.+ assert!(+ !sql.contains("WHEN 'viewed_at'"),+ "deferred sort must drop the uh CASE: {sql}"+ );+ assert!(sql.contains("t.latest_outbound_message_ts AS effective_ts"));+ assert!(sql.contains("uh.updated_at AS viewed_at"));+}++#[test]+fn test_build_query_keeps_user_history_join_inline_for_viewed_at_sort() {+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Sent);+ let expr = Expr::Literal(EmailLiteral::Sender(Email::Domain("acme.com".to_string())));+ let sql = super::query::debug_build_query_sql_with_sort(+ &view,+ &expr,+ models_pagination::SimpleSortMethod::ViewedAt,+ );++ // uh drives the sort key for viewed_at, so the join must stay in the+ // candidate stage (before email_links) and cannot be deferred.+ assert_eq!(+ sql.matches("LEFT JOIN email_user_history").count(),+ 1,+ "viewed_at sort must keep a single, inline uh join: {sql}"+ );+ let uh_pos = sql.find("LEFT JOIN email_user_history").unwrap();+ let el_pos = sql.find("JOIN email_links el").unwrap();+ assert!(+ uh_pos < el_pos,+ "uh join must stay in the candidate stage for viewed_at sort: {sql}"+ );+ assert!(sql.contains("WHEN 'viewed_at' THEN COALESCE(uh"));+ // viewed_at is the candidate's own column on this path.+ assert!(sql.contains("t.viewed_at,"));}const DEFAULT_SORT_TS: &str = "t.updated_at";diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rsindex 9cc01b02c3..dc64f615a3 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs@@ -2429,3 +2429,202 @@ async fn test_dynamic_query_created_at_and_updated_at_combined(Ok(())}++// ---------------------------------------------------------------------------+// viewed_at / email_user_history+//+// `email_user_history` supplies the per-user `viewed_at` column and drives the+// sort key for the viewed-based sort modes. Non-viewed modes defer the join+// past the candidate LIMIT (see query.rs::sort_uses_view_history); these tests+// pin down both the deferred projection and the inline viewed-sort behaviour.+// Inbox threads (1, 4, 5, 7) sort by latest_inbound_message_ts descending:+// thread 1 (2024-01-15), 4 (2024-01-12), 5 (2024-01-11), 7 (2024-01-09).+// ---------------------------------------------------------------------------++const THREAD_1: &str = "20000001-0000-0000-0000-000000000001";+const THREAD_4: &str = "20000004-0000-0000-0000-000000000004";+const THREAD_5: &str = "20000005-0000-0000-0000-000000000005";+const THREAD_7: &str = "20000007-0000-0000-0000-000000000007";++/// Records that `link_id` viewed `thread_id` at `viewed_at`, i.e. inserts an+/// `email_user_history` row whose `updated_at` is the supplied timestamp.+async fn record_view(+ pool: &Pool<Postgres>,+ link_id: Uuid,+ thread_id: &str,+ viewed_at: chrono::DateTime<Utc>,+) -> anyhow::Result<()> {+ sqlx::query(+ "INSERT INTO email_user_history (link_id, thread_id, created_at, updated_at) \+ VALUES ($1, $2, $3, $3)",+ )+ .bind(link_id)+ .bind(Uuid::parse_str(thread_id)?)+ .bind(viewed_at)+ .execute(pool)+ .await?;+ Ok(())+}++fn inbox_partial_query(+ sort: SimpleSortMethod,+) -> Query<Uuid, SimpleSortMethod, Arc<Expr<EmailLiteral>>> {+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(+ "example.com".to_string(),+ ))));+ Query::new(None, sort, filter)+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))+)]+async fn test_updated_at_sort_projects_viewed_at_via_deferred_join(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let viewed_1 = Utc.with_ymd_and_hms(2024, 3, 1, 0, 0, 0).unwrap();+ let viewed_5 = Utc.with_ymd_and_hms(2024, 3, 5, 0, 0, 0).unwrap();+ // Two of the four inbox threads have a view record; the other two don't.+ record_view(&pool, link_id, THREAD_1, viewed_1).await?;+ record_view(&pool, link_id, THREAD_5, viewed_5).await?;++ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);+ let results = dynamic::dynamic_email_thread_cursor(+ &pool,+ &[link_id],+ 50,+ &view,+ inbox_partial_query(SimpleSortMethod::UpdatedAt),+ "",+ None,+ )+ .await?;++ // Deferring the join must not change the result set or its order: still+ // ordered by latest_inbound_message_ts, not by viewed_at.+ let order: Vec<String> = results.iter().map(|r| r.id.to_string()).collect();+ assert_eq!(+ order,+ vec![+ THREAD_1.to_string(),+ THREAD_4.to_string(),+ THREAD_5.to_string(),+ THREAD_7.to_string(),+ ],+ "UpdatedAt sort must order by the view timestamp, not viewed_at"+ );++ let viewed_at = |id: &str| {+ results+ .iter()+ .find(|r| r.id.to_string() == id)+ .unwrap_or_else(|| panic!("missing thread {id}"))+ .viewed_at+ };+ // viewed_at is populated for threads with history (matched on thread_id AND+ // link_id), NULL for the rest.+ assert_eq!(viewed_at(THREAD_1), Some(viewed_1));+ assert_eq!(viewed_at(THREAD_5), Some(viewed_5));+ assert_eq!(viewed_at(THREAD_4), None);+ assert_eq!(viewed_at(THREAD_7), None);++ // sort_ts is the view timestamp (latest_inbound_message_ts), proving the+ // deferred viewed_at did not leak into the sort key.+ let thread_1 = results+ .iter()+ .find(|r| r.id.to_string() == THREAD_1)+ .unwrap();+ assert_eq!(+ thread_1.sort_ts,+ Utc.with_ymd_and_hms(2024, 1, 15, 10, 0, 0).unwrap()+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))+)]+async fn test_viewed_at_sort_orders_by_view_history(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let viewed_7 = Utc.with_ymd_and_hms(2024, 6, 1, 0, 0, 0).unwrap();+ let viewed_4 = Utc.with_ymd_and_hms(2024, 5, 1, 0, 0, 0).unwrap();+ // Threads 7 and 4 viewed recently; threads 1 and 5 never viewed.+ record_view(&pool, link_id, THREAD_7, viewed_7).await?;+ record_view(&pool, link_id, THREAD_4, viewed_4).await?;++ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);+ let query = inbox_partial_query(SimpleSortMethod::ViewedAt);+ let results =+ dynamic::dynamic_email_thread_cursor(&pool, &[link_id], 50, &view, query, "", None).await?;++ // Viewed threads first (most-recently-viewed first); unviewed threads fall+ // back to epoch and tie-break on id DESC (5 before 1).+ let order: Vec<String> = results.iter().map(|r| r.id.to_string()).collect();+ assert_eq!(+ order,+ vec![+ THREAD_7.to_string(),+ THREAD_4.to_string(),+ THREAD_5.to_string(),+ THREAD_1.to_string(),+ ],+ "ViewedAt sort must order by email_user_history.updated_at"+ );++ let top = &results[0];+ assert_eq!(top.viewed_at, Some(viewed_7));+ // effective_ts == viewed_at on this path (the inline CASE).+ assert_eq!(top.sort_ts, viewed_7);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))+)]+async fn test_viewed_updated_sort_falls_back_to_view_timestamp(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let viewed_7 = Utc.with_ymd_and_hms(2024, 6, 1, 0, 0, 0).unwrap();+ let viewed_4 = Utc.with_ymd_and_hms(2024, 5, 1, 0, 0, 0).unwrap();+ record_view(&pool, link_id, THREAD_7, viewed_7).await?;+ record_view(&pool, link_id, THREAD_4, viewed_4).await?;++ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);+ let query = inbox_partial_query(SimpleSortMethod::ViewedUpdated);+ let results =+ dynamic::dynamic_email_thread_cursor(&pool, &[link_id], 50, &view, query, "", None).await?;++ // Viewed threads use their view time; unviewed threads (1, 5) fall back to+ // latest_inbound_message_ts (2024-01-15, 2024-01-11), landing after the+ // 2024 views: 7, 4, 1, 5.+ let order: Vec<String> = results.iter().map(|r| r.id.to_string()).collect();+ assert_eq!(+ order,+ vec![+ THREAD_7.to_string(),+ THREAD_4.to_string(),+ THREAD_1.to_string(),+ THREAD_5.to_string(),+ ],+ "ViewedUpdated must coalesce viewed_at with the view timestamp"+ );++ // Unviewed thread 1 falls back to its inbound timestamp for effective_ts.+ let thread_1 = results+ .iter()+ .find(|r| r.id.to_string() == THREAD_1)+ .unwrap();+ assert_eq!(thread_1.viewed_at, None);+ assert_eq!(+ thread_1.sort_ts,+ Utc.with_ymd_and_hms(2024, 1, 15, 10, 0, 0).unwrap()+ );++ Ok(())+}diff --git a/rust/cloud-storage/macro_db_client/migrations/20260623200718_email_sent_index.sql b/rust/cloud-storage/macro_db_client/migrations/20260623200718_email_sent_index.sqlnew file mode 100644index 0000000000..194f0b4a78--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260623200718_email_sent_index.sql@@ -0,0 +1,4 @@+-- no-transaction++CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_email_user_history_thread_link+ ON public.email_user_history USING btree (thread_id, link_id);\ No newline at end of file