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): paginate email signal on filtered rows, not raw recency (#3870)
gbirman46995536d0cd
diff --git a/rust/cloud-storage/email/fixtures/email_importance_pagination.sql b/rust/cloud-storage/email/fixtures/email_importance_pagination.sqlnew file mode 100644index 0000000000..6a3ce16037--- /dev/null+++ b/rust/cloud-storage/email/fixtures/email_importance_pagination.sql@@ -0,0 +1,90 @@+-- Fixture for importance-filter pagination tests.+--+-- Two inbox links. On each link the most-recent threads are not important and+-- the important threads are older, so an importance match cannot be satisfied+-- by taking the most-recent threads alone.+--+-- Link 1 (a1111111…): 3 recent non-important + 4 older important inbox threads.+-- Link 2 (b2222222…): 2 important inbox threads.++INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)+VALUES+ ('a1111111-1111-1111-1111-111111111111', 'macro1', 'fa1', '[email protected]', 'GMAIL', true, NOW(), NOW()),+ ('b2222222-2222-2222-2222-222222222222', 'macro2', 'fa2', '[email protected]', 'GMAIL', true, NOW(), NOW());++INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)+VALUES+ ('c0000001-0000-0000-0000-000000000001', 'a1111111-1111-1111-1111-111111111111', '[email protected]', 'Sender One', NOW(), NOW()),+ ('c0000002-0000-0000-0000-000000000002', 'b2222222-2222-2222-2222-222222222222', '[email protected]', 'Sender Two', NOW(), NOW());++-- Per-link labels. CATEGORY_PERSONAL is a priority label (important);+-- CATEGORY_PROMOTIONS is a depriority label (not important when no priority).+INSERT INTO email_labels (id, link_id, provider_label_id, name, message_list_visibility, label_list_visibility, type, created_at)+VALUES+ ('1a000001-0000-0000-0000-000000000001', 'a1111111-1111-1111-1111-111111111111', 'INBOX', 'INBOX', 'Show', 'LabelShow', 'System', NOW()),+ ('1a000002-0000-0000-0000-000000000002', 'a1111111-1111-1111-1111-111111111111', 'TRASH', 'TRASH', 'Hide', 'LabelHide', 'System', NOW()),+ ('1a000003-0000-0000-0000-000000000003', 'a1111111-1111-1111-1111-111111111111', 'CATEGORY_PERSONAL', 'CATEGORY_PERSONAL', 'Show', 'LabelShow', 'System', NOW()),+ ('1a000004-0000-0000-0000-000000000004', 'a1111111-1111-1111-1111-111111111111', 'CATEGORY_PROMOTIONS', 'CATEGORY_PROMOTIONS', 'Show', 'LabelShow', 'System', NOW()),+ ('1b000001-0000-0000-0000-000000000001', 'b2222222-2222-2222-2222-222222222222', 'INBOX', 'INBOX', 'Show', 'LabelShow', 'System', NOW()),+ ('1b000002-0000-0000-0000-000000000002', 'b2222222-2222-2222-2222-222222222222', 'TRASH', 'TRASH', 'Hide', 'LabelHide', 'System', NOW()),+ ('1b000003-0000-0000-0000-000000000003', 'b2222222-2222-2222-2222-222222222222', 'CATEGORY_PERSONAL', 'CATEGORY_PERSONAL', 'Show', 'LabelShow', 'System', NOW()),+ ('1b000004-0000-0000-0000-000000000004', 'b2222222-2222-2222-2222-222222222222', 'CATEGORY_PROMOTIONS', 'CATEGORY_PROMOTIONS', 'Show', 'LabelShow', 'System', NOW());++INSERT INTO email_threads (+ id, provider_id, link_id, inbox_visible, is_read,+ latest_inbound_message_ts, latest_outbound_message_ts, latest_non_spam_message_ts,+ created_at, updated_at+)+VALUES+ -- Link 1: 3 most-recent non-important inbox threads+ ('2a000001-0000-0000-0000-000000000001', 'na1', 'a1111111-1111-1111-1111-111111111111', true, false, '2024-02-10 10:00:00+00', NULL, '2024-02-10 10:00:00+00', NOW(), NOW()),+ ('2a000002-0000-0000-0000-000000000002', 'na2', 'a1111111-1111-1111-1111-111111111111', true, false, '2024-02-09 10:00:00+00', NULL, '2024-02-09 10:00:00+00', NOW(), NOW()),+ ('2a000003-0000-0000-0000-000000000003', 'na3', 'a1111111-1111-1111-1111-111111111111', true, false, '2024-02-08 10:00:00+00', NULL, '2024-02-08 10:00:00+00', NOW(), NOW()),+ -- Link 1: 4 older important inbox threads+ ('2a000004-0000-0000-0000-000000000004', 'ia1', 'a1111111-1111-1111-1111-111111111111', true, false, '2024-02-07 10:00:00+00', NULL, '2024-02-07 10:00:00+00', NOW(), NOW()),+ ('2a000005-0000-0000-0000-000000000005', 'ia2', 'a1111111-1111-1111-1111-111111111111', true, false, '2024-02-06 10:00:00+00', NULL, '2024-02-06 10:00:00+00', NOW(), NOW()),+ ('2a000006-0000-0000-0000-000000000006', 'ia3', 'a1111111-1111-1111-1111-111111111111', true, false, '2024-02-05 10:00:00+00', NULL, '2024-02-05 10:00:00+00', NOW(), NOW()),+ ('2a000007-0000-0000-0000-000000000007', 'ia4', 'a1111111-1111-1111-1111-111111111111', true, false, '2024-02-04 10:00:00+00', NULL, '2024-02-04 10:00:00+00', NOW(), NOW()),+ -- Link 2: 2 important inbox threads+ ('2b000001-0000-0000-0000-000000000001', 'ib1', 'b2222222-2222-2222-2222-222222222222', true, false, '2024-02-03 10:00:00+00', NULL, '2024-02-03 10:00:00+00', NOW(), NOW()),+ ('2b000002-0000-0000-0000-000000000002', 'ib2', 'b2222222-2222-2222-2222-222222222222', true, false, '2024-02-02 10:00:00+00', NULL, '2024-02-02 10:00:00+00', NOW(), NOW());++INSERT INTO email_messages (+ id, thread_id, link_id, provider_id, from_contact_id,+ subject, snippet, internal_date_ts,+ is_draft, is_sent, is_starred, is_read,+ created_at, updated_at+)+VALUES+ ('3a000001-0000-0000-0000-000000000001', '2a000001-0000-0000-0000-000000000001', 'a1111111-1111-1111-1111-111111111111', 'na1', 'c0000001-0000-0000-0000-000000000001', 'Promo 1', 'promo', '2024-02-10 10:00:00+00', false, false, false, false, NOW(), NOW()),+ ('3a000002-0000-0000-0000-000000000002', '2a000002-0000-0000-0000-000000000002', 'a1111111-1111-1111-1111-111111111111', 'na2', 'c0000001-0000-0000-0000-000000000001', 'Promo 2', 'promo', '2024-02-09 10:00:00+00', false, false, false, false, NOW(), NOW()),+ ('3a000003-0000-0000-0000-000000000003', '2a000003-0000-0000-0000-000000000003', 'a1111111-1111-1111-1111-111111111111', 'na3', 'c0000001-0000-0000-0000-000000000001', 'Promo 3', 'promo', '2024-02-08 10:00:00+00', false, false, false, false, NOW(), NOW()),+ ('3a000004-0000-0000-0000-000000000004', '2a000004-0000-0000-0000-000000000004', 'a1111111-1111-1111-1111-111111111111', 'ia1', 'c0000001-0000-0000-0000-000000000001', 'Important 1', 'important', '2024-02-07 10:00:00+00', false, false, false, false, NOW(), NOW()),+ ('3a000005-0000-0000-0000-000000000005', '2a000005-0000-0000-0000-000000000005', 'a1111111-1111-1111-1111-111111111111', 'ia2', 'c0000001-0000-0000-0000-000000000001', 'Important 2', 'important', '2024-02-06 10:00:00+00', false, false, false, false, NOW(), NOW()),+ ('3a000006-0000-0000-0000-000000000006', '2a000006-0000-0000-0000-000000000006', 'a1111111-1111-1111-1111-111111111111', 'ia3', 'c0000001-0000-0000-0000-000000000001', 'Important 3', 'important', '2024-02-05 10:00:00+00', false, false, false, false, NOW(), NOW()),+ ('3a000007-0000-0000-0000-000000000007', '2a000007-0000-0000-0000-000000000007', 'a1111111-1111-1111-1111-111111111111', 'ia4', 'c0000001-0000-0000-0000-000000000001', 'Important 4', 'important', '2024-02-04 10:00:00+00', false, false, false, false, NOW(), NOW()),+ ('3b000001-0000-0000-0000-000000000001', '2b000001-0000-0000-0000-000000000001', 'b2222222-2222-2222-2222-222222222222', 'ib1', 'c0000002-0000-0000-0000-000000000002', 'Important 5', 'important', '2024-02-03 10:00:00+00', false, false, false, false, NOW(), NOW()),+ ('3b000002-0000-0000-0000-000000000002', '2b000002-0000-0000-0000-000000000002', 'b2222222-2222-2222-2222-222222222222', 'ib2', 'c0000002-0000-0000-0000-000000000002', 'Important 6', 'important', '2024-02-02 10:00:00+00', false, false, false, false, NOW(), NOW());++INSERT INTO email_message_labels (message_id, label_id)+VALUES+ -- Non-important: INBOX + CATEGORY_PROMOTIONS (depriority, no priority label)+ ('3a000001-0000-0000-0000-000000000001', '1a000001-0000-0000-0000-000000000001'),+ ('3a000001-0000-0000-0000-000000000001', '1a000004-0000-0000-0000-000000000004'),+ ('3a000002-0000-0000-0000-000000000002', '1a000001-0000-0000-0000-000000000001'),+ ('3a000002-0000-0000-0000-000000000002', '1a000004-0000-0000-0000-000000000004'),+ ('3a000003-0000-0000-0000-000000000003', '1a000001-0000-0000-0000-000000000001'),+ ('3a000003-0000-0000-0000-000000000003', '1a000004-0000-0000-0000-000000000004'),+ -- Important: INBOX + CATEGORY_PERSONAL (priority label)+ ('3a000004-0000-0000-0000-000000000004', '1a000001-0000-0000-0000-000000000001'),+ ('3a000004-0000-0000-0000-000000000004', '1a000003-0000-0000-0000-000000000003'),+ ('3a000005-0000-0000-0000-000000000005', '1a000001-0000-0000-0000-000000000001'),+ ('3a000005-0000-0000-0000-000000000005', '1a000003-0000-0000-0000-000000000003'),+ ('3a000006-0000-0000-0000-000000000006', '1a000001-0000-0000-0000-000000000001'),+ ('3a000006-0000-0000-0000-000000000006', '1a000003-0000-0000-0000-000000000003'),+ ('3a000007-0000-0000-0000-000000000007', '1a000001-0000-0000-0000-000000000001'),+ ('3a000007-0000-0000-0000-000000000007', '1a000003-0000-0000-0000-000000000003'),+ ('3b000001-0000-0000-0000-000000000001', '1b000001-0000-0000-0000-000000000001'),+ ('3b000001-0000-0000-0000-000000000001', '1b000003-0000-0000-0000-000000000003'),+ ('3b000002-0000-0000-0000-000000000002', '1b000001-0000-0000-0000-000000000001'),+ ('3b000002-0000-0000-0000-000000000002', '1b000003-0000-0000-0000-000000000003');diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rsindex db517b2f6b..bf96ea321e 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs@@ -58,6 +58,15 @@ pub(super) fn has_message_literals(ast: &Expr<EmailLiteral>) -> bool {})}+pub(super) fn has_importance_literal(ast: &Expr<EmailLiteral>) -> bool {+ ast.collapse_frames(|frame| match frame {+ filter_ast::ExprFrame::And(a, b) | filter_ast::ExprFrame::Or(a, b) => a || b,+ filter_ast::ExprFrame::Not(a) => a,+ filter_ast::ExprFrame::Literal(EmailLiteral::Importance(_)) => true,+ filter_ast::ExprFrame::Literal(_) => false,+ })+}+#[derive(Clone, Copy)]enum AddressKind {Sender,@@ -456,6 +465,44 @@ pub(super) fn build_thread_address_filter(ast: &Expr<EmailLiteral>) -> SqlFragmeSqlFragment::raw(" AND t.id IN (SELECT thread_id FROM matching_threads)")}+/// True when the candidate WHERE must mirror the CROSS JOIN LATERAL's+/// message match via a correlated EXISTS rather than the address-only+/// `matching_threads` CTE. That's the case when the lateral applies a+/// per-message filter the address CTE doesn't model — an `Importance`+/// literal, or a non-empty view-level message filter (Starred / Drafts /+/// Important / …). Without this, the candidate `LIMIT` counts threads that+/// the lateral later drops, so the page under-fills while still emitting a+/// cursor.+pub(super) fn wants_message_exists_pushdown(ast: &Expr<EmailLiteral>, view: &PreviewView) -> bool {+ has_importance_literal(ast) || !build_view_message_filter(view).is_empty()+}++/// Builds the candidate-stage mirror of the lateral message match:+/// `AND EXISTS (SELECT 1 FROM email_messages m WHERE m.thread_id = t.id AND <lateral predicate>)`.+/// The predicate is the same trash exclusion + view message filter ++/// message-level email filter the lateral applies, so a thread enters the+/// candidate set iff it has a message the lateral will surface — making the+/// `LIMIT` count real results.+pub(super) fn build_thread_message_exists_filter(+ ast: &Expr<EmailLiteral>,+ view: &PreviewView,+ resolved: &ResolvedFilters,+) -> SqlFragment {+ let mut f = SqlFragment::raw(+ " AND EXISTS (SELECT 1 FROM email_messages m WHERE m.thread_id = t.id AND ",+ );+ f.extend(build_lateral_trash_exclusion(resolved));+ let view_message_filter = build_view_message_filter(view);+ if !view_message_filter.is_empty() {+ f.extend(view_message_filter);+ }+ if has_message_literals(ast) {+ f.extend(build_message_email_filter(ast, resolved));+ }+ f.push_raw(")");+ f+}+/// If `expr` is a flat OR-tree (no AND, no NOT) of single positive/// address literals, returns the list of `(kind, email)` leaves. Otherwise/// `None` — caller must use the combined-predicate path. UNION-of-branchesdiff --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 14f5bf9dae..2d9eac0f9b 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@@ -198,12 +198,15 @@ fn push_thread_candidate_select(build_thread_email_filter(email_filter, sort_ts_field).push_into(builder);}- // Push address (Sender/Cc/Bcc/Recipient) constraints into the candidate- // WHERE so pagination's LIMIT counts threads that actually contain a- // matching message. The actual matching set is materialized once in the- // top-level `matching_threads` CTE; the candidate WHERE just references- // it via `t.id IN (SELECT thread_id FROM matching_threads)`.- if has_address_literals(email_filter) {+ // Ensure the candidate LIMIT only counts threads that will survive the+ // CROSS JOIN LATERAL's message match. When a per-message filter is in+ // play (importance, or a view-level message filter) mirror the full+ // lateral predicate as a correlated EXISTS; otherwise push address-only+ // constraints through the index-driven `matching_threads` CTE referenced+ // via `t.id IN (SELECT thread_id FROM matching_threads)`.+ if wants_message_exists_pushdown(email_filter, view) {+ build_thread_message_exists_filter(email_filter, view, ¶ms.resolved).push_into(builder);+ } else if has_address_literals(email_filter) {build_thread_address_filter(email_filter).push_into(builder);}@@ -258,7 +261,15 @@ fn build_query(let view_message_filter = build_view_message_filter(view);let needs_shared_cte = !matches!(params.shared, SharedEmailFilter::Exclude);- let matching_threads_body = build_matching_threads_cte_body(email_filter, ¶ms.resolved);+ // When the candidate stage pushes a full per-message EXISTS (importance,+ // or a view-level message filter), it already enforces "thread has a+ // message the lateral will surface", so the address-only+ // `matching_threads` CTE is redundant.+ let matching_threads_body = if wants_message_exists_pushdown(email_filter, view) {+ None+ } else {+ build_matching_threads_cte_body(email_filter, ¶ms.resolved)+ };let mut builder = sqlx::QueryBuilder::new("");if needs_shared_cte || matching_threads_body.is_some() {diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/importance_pagination.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/importance_pagination.rsnew file mode 100644index 0000000000..433003f93b--- /dev/null+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/importance_pagination.rs@@ -0,0 +1,241 @@+use super::*;++// Pagination for email queries filtered by a per-message attribute+// (importance). A page must contain up to `limit` threads that actually match+// the filter, the cursor must advance across pages without repeating threads,+// an exhausted result must report no further pages, and an all-inboxes query+// must return the union of its per-inbox results.++fn importance_exclude_filter() -> Arc<Expr<EmailLiteral>> {+ Arc::new(Expr::and(+ Expr::Literal(EmailLiteral::Importance(true)),+ Expr::Literal(EmailLiteral::Shared(+ item_filters::SharedEmailFilter::Exclude,+ )),+ ))+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_importance_pagination"))+)]+async fn test_importance_inbox_pagination_fills_page_and_advances_cursor(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("a1111111-1111-1111-1111-111111111111")?;+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);+ let limit = 3;++ // Link 1 has 3 recent non-important + 4 older important inbox threads.+ // With limit=3 the first page must be a full page of the 3 most-recent+ // important threads; the recent non-important threads must not occupy the+ // limit.+ let query = Query::new(+ None,+ SimpleSortMethod::UpdatedAt,+ importance_exclude_filter(),+ );+ let page1 =+ dynamic::dynamic_email_thread_cursor(&pool, &[link_id], limit, &view, query, "", None)+ .await?;++ let page1_ids: Vec<String> = page1.iter().map(|r| r.id.to_string()).collect();+ assert_eq!(+ page1_ids,+ vec![+ "2a000004-0000-0000-0000-000000000004".to_string(),+ "2a000005-0000-0000-0000-000000000005".to_string(),+ "2a000006-0000-0000-0000-000000000006".to_string(),+ ],+ "first page should be a full page of the 3 most-recent important threads"+ );++ // Second page: the cursor advances onto the 4th important thread.+ let last = page1.last().unwrap();+ let cursor = Cursor {+ id: last.id,+ limit: limit as usize,+ val: CursorVal {+ sort_type: SimpleSortMethod::UpdatedAt,+ last_val: last.sort_ts,+ },+ filter: importance_exclude_filter(),+ };+ let query2 = Query::new(+ Some(cursor),+ SimpleSortMethod::UpdatedAt,+ importance_exclude_filter(),+ );+ let page2 =+ dynamic::dynamic_email_thread_cursor(&pool, &[link_id], limit, &view, query2, "", None)+ .await?;++ let page2_ids: Vec<String> = page2.iter().map(|r| r.id.to_string()).collect();+ assert_eq!(+ page2_ids,+ vec!["2a000007-0000-0000-0000-000000000007".to_string()],+ "second page should hold the remaining important thread"+ );++ // Third page: cursor is exhausted, no rows remain.+ let last2 = page2.last().unwrap();+ let cursor2 = Cursor {+ id: last2.id,+ limit: limit as usize,+ val: CursorVal {+ sort_type: SimpleSortMethod::UpdatedAt,+ last_val: last2.sort_ts,+ },+ filter: importance_exclude_filter(),+ };+ let query3 = Query::new(+ Some(cursor2),+ SimpleSortMethod::UpdatedAt,+ importance_exclude_filter(),+ );+ let page3 =+ dynamic::dynamic_email_thread_cursor(&pool, &[link_id], limit, &view, query3, "", None)+ .await?;+ assert!(+ page3.is_empty(),+ "pagination should terminate once important threads are exhausted"+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_importance_pagination"))+)]+async fn test_importance_inbox_underfilled_page_has_no_more(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("a1111111-1111-1111-1111-111111111111")?;+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);+ let limit = 50;++ // All importance-matching threads on link 1 sit below the limit, so the+ // page holds exactly them (non-matching threads excluded) and a follow-up+ // cursor page is empty — `len < limit` means last page, so no cursor.+ let query = Query::new(+ None,+ SimpleSortMethod::UpdatedAt,+ importance_exclude_filter(),+ );+ let page =+ dynamic::dynamic_email_thread_cursor(&pool, &[link_id], limit, &view, query, "", None)+ .await?;++ assert_eq!(+ page.len(),+ 4,+ "should return exactly the 4 important threads"+ );+ assert!(+ page.len() < limit as usize,+ "page is under the limit, so the caller treats it as the last page"+ );++ let last = page.last().unwrap();+ let cursor = Cursor {+ id: last.id,+ limit: limit as usize,+ val: CursorVal {+ sort_type: SimpleSortMethod::UpdatedAt,+ last_val: last.sort_ts,+ },+ filter: importance_exclude_filter(),+ };+ let query2 = Query::new(+ Some(cursor),+ SimpleSortMethod::UpdatedAt,+ importance_exclude_filter(),+ );+ let next =+ dynamic::dynamic_email_thread_cursor(&pool, &[link_id], limit, &view, query2, "", None)+ .await?;+ assert!(+ next.is_empty(),+ "no further pages once all important threads are returned"+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_importance_pagination"))+)]+async fn test_importance_pagination_multi_inbox_counts_agree(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let link1 = Uuid::parse_str("a1111111-1111-1111-1111-111111111111")?;+ let link2 = Uuid::parse_str("b2222222-2222-2222-2222-222222222222")?;+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);+ let limit = 50;++ let single1 = dynamic::dynamic_email_thread_cursor(+ &pool,+ &[link1],+ limit,+ &view,+ Query::new(+ None,+ SimpleSortMethod::UpdatedAt,+ importance_exclude_filter(),+ ),+ "",+ None,+ )+ .await?;+ let single2 = dynamic::dynamic_email_thread_cursor(+ &pool,+ &[link2],+ limit,+ &view,+ Query::new(+ None,+ SimpleSortMethod::UpdatedAt,+ importance_exclude_filter(),+ ),+ "",+ None,+ )+ .await?;+ let multi = dynamic::dynamic_email_thread_cursor(+ &pool,+ &[link1, link2],+ limit,+ &view,+ Query::new(+ None,+ SimpleSortMethod::UpdatedAt,+ importance_exclude_filter(),+ ),+ "",+ None,+ )+ .await?;++ assert_eq!(single1.len(), 4, "link 1 has 4 important inbox threads");+ assert_eq!(single2.len(), 2, "link 2 has 2 important inbox threads");+ assert_eq!(+ multi.len(),+ single1.len() + single2.len(),+ "all-inboxes count must equal the sum of the per-inbox counts"+ );++ // The all-inboxes page is exactly the union of both links' threads.+ let multi_ids: std::collections::HashSet<String> =+ multi.iter().map(|r| r.id.to_string()).collect();+ for r in single1.iter().chain(single2.iter()) {+ assert!(+ multi_ids.contains(&r.id.to_string()),+ "multi-inbox page missing thread {}",+ r.id+ );+ }++ Ok(())+}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rsindex 57f4de7609..c1a59199d7 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs@@ -1,6 +1,7 @@mod crm_scope_dynamic_query;mod draft;mod dynamic_query;+mod importance_pagination;mod labels;mod link;mod message;diff --git a/rust/cloud-storage/models_pagination/src/cursor.rs b/rust/cloud-storage/models_pagination/src/cursor.rsindex da81e1c116..f4287de39c 100644--- a/rust/cloud-storage/models_pagination/src/cursor.rs+++ b/rust/cloud-storage/models_pagination/src/cursor.rs@@ -30,46 +30,6 @@ impl<T, U> Paginated<T, U> {}}-impl<T, I, S: Sortable, F> PaginatedCursor<T, I, S, F>-where- T: Identify<Id = I>,- I: Serialize,- S: Serialize,- CursorVal<S>: Serialize,- F: Serialize,-{- /// Ensures a cursor is present as long as items is non-empty.- /// Useful when post-processing (e.g. CROSS JOIN LATERAL) may have filtered- /// rows after the initial limit, making the standard "len < limit means- /// last page" heuristic unreliable.- pub fn ensure_cursor(- self,- limit: usize,- mut cb: impl FnMut(&T) -> CursorVal<S>,- filter: F,- ) -> Self {- if self.next_cursor.is_some() || self.items.is_empty() {- return self;- }-- let next_cursor = self- .items- .last()- .map(|last| Cursor {- id: last.id(),- limit,- val: cb(last),- filter,- })- .map(Base64Str::encode_json);-- Paginated {- items: self.items,- next_cursor,- }- }-}-/// Top level cursor information encodes all the required information for paginating by [Cursor]#[derive(Debug, Serialize, Deserialize, Clone)]pub struct Cursor<Id, C, F> {diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rsindex 1d0657336a..008cbe4d93 100644--- a/rust/cloud-storage/soup/src/domain/service.rs+++ b/rust/cloud-storage/soup/src/domain/service.rs@@ -28,7 +28,7 @@ use frecency::domain::{use item_filters::ast::EntityFilterAst;use macro_user_id::user_id::MacroUserIdStr;use models_pagination::{- Cursor, CursorVal, Frecency, FrecencyValue, PaginateOn, Query, SimpleSortMethod, SortOn,+ Cursor, CursorVal, Frecency, FrecencyValue, PaginateOn, Query, SimpleSortMethod,};use models_soup::{call_record::SoupCallRecord,@@ -574,28 +574,10 @@ where.chain(crm_company_soup?).chain(foreign_entity_soup?).paginate_on(limit.into(), sort_method)- .filter_on(entity_filter.clone())+ .filter_on(entity_filter).sort_desc().into_page();- // Email queries use CROSS JOIN LATERAL which can filter out- // threads after the initial LIMIT, making the standard- // "len < limit means last page" heuristic unreliable.- // Force a cursor when emails are in the response.- let has_emails = page- .items- .iter()- .any(|item| matches!(&item.item, SoupItem::EmailThread(_)));- let page = if has_emails {- page.ensure_cursor(- limit.into(),- FrecencySoupItem::sort_on(sort_method),- entity_filter,- )- } else {- page- };-Ok(Either::Left(page))}SoupQuery::Frecency(FrecencyQueryInner(cursor)) => Ok(Either::Right(