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.

fix(email): dedupe team-member thread copies in CRM-scoped queries (#3709)

Evan Hutnik5e04e3227821
diff --git a/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_dedupe.sql b/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_dedupe.sql
new file mode 100644
index 0000000000..f09ebad83a
--- /dev/null
+++ b/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_dedupe.sql
@@ -0,0 +1,151 @@
+-- Fixture for testing team-scoped (CRM) dedupe of conversation copies.
+--
+-- Team Beta has two members (Dave, Erin). Four conversations, identified by
+-- the root message's RFC-822 Message-ID (email_messages.global_id):
+--
+-- • X — BOTH have a copy. Dave's copy also has a reply Erin wasn't on,
+-- so Dave's thread ts (10:00) is newer than Erin's (08:00).
+-- • Y — Erin only (09:00). Dave's queries must return Erin's copy.
+-- • Z — Dave only (11:00).
+-- • W — BOTH have a copy. Erin's copy has a reply Dave wasn't on, so
+-- Erin's thread ts (12:00) is NEWER than Dave's (07:00). Own-copy
+-- preference must still pick the caller's copy over the newer one.
+--
+-- Expected results for Sender(Domain("acme.com")) under team scope:
+-- Dave: td2(Z,11:00), td1(X,10:00), te2(Y,09:00), td3(W,07:00)
+-- Erin: te3(W,12:00), td2(Z,11:00), te2(Y,09:00), te1(X,08:00)
+
+-- == macro_user / User rows ==
+INSERT INTO "macro_user" (id, username, email, stripe_customer_id)
+VALUES
+ ('d1111111-1111-1111-1111-111111111111', '[email protected]', '[email protected]', 'stripe_dave'),
+ ('e1111111-1111-1111-1111-111111111111', '[email protected]', '[email protected]', 'stripe_erin');
+
+INSERT INTO "User" (id, email, name, macro_user_id)
+VALUES
+ ('macro|[email protected]', '[email protected]', 'Dave', 'd1111111-1111-1111-1111-111111111111'),
+ ('macro|[email protected]', '[email protected]', 'Erin', 'e1111111-1111-1111-1111-111111111111');
+
+-- == Team Beta + memberships ==
+INSERT INTO team (id, name, owner_id, seat_count)
+VALUES
+ ('e0000002-0000-0000-0000-000000000002', 'Team Beta', 'macro|[email protected]', 2);
+
+INSERT INTO team_user (team_id, user_id, team_role)
+VALUES
+ ('e0000002-0000-0000-0000-000000000002', 'macro|[email protected]', 'owner'),
+ ('e0000002-0000-0000-0000-000000000002', 'macro|[email protected]', 'member');
+
+INSERT INTO team_crm_settings (team_id, crm_enabled)
+VALUES
+ ('e0000002-0000-0000-0000-000000000002', TRUE);
+
+-- == Email links ==
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES
+ ('d0000001-0000-0000-0000-000000000001', 'macro|[email protected]', 'fa_dave', '[email protected]', 'GMAIL', true, NOW(), NOW()),
+ ('d0000002-0000-0000-0000-000000000002', 'macro|[email protected]', 'fa_erin', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+-- == Contacts — [email protected], one row per link ==
+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)
+VALUES
+ ('c1000001-0000-0000-0000-000000000001', 'd0000001-0000-0000-0000-000000000001', '[email protected]', 'Vendor', NOW(), NOW()),
+ ('c1000002-0000-0000-0000-000000000002', 'd0000002-0000-0000-0000-000000000002', '[email protected]', 'Vendor', NOW(), NOW());
+
+-- == Labels — INBOX + TRASH per link ==
+INSERT INTO email_labels (id, link_id, provider_label_id, name, message_list_visibility, label_list_visibility, type, created_at)
+VALUES
+ ('77770001-0000-0000-0000-000000000001', 'd0000001-0000-0000-0000-000000000001', 'INBOX', 'INBOX', 'Show', 'LabelShow', 'System', NOW()),
+ ('77770001-0000-0000-0000-000000000002', 'd0000001-0000-0000-0000-000000000001', 'TRASH', 'TRASH', 'Hide', 'LabelHide', 'System', NOW()),
+ ('77770002-0000-0000-0000-000000000001', 'd0000002-0000-0000-0000-000000000002', 'INBOX', 'INBOX', 'Show', 'LabelShow', 'System', NOW()),
+ ('77770002-0000-0000-0000-000000000002', 'd0000002-0000-0000-0000-000000000002', 'TRASH', 'TRASH', 'Hide', 'LabelHide', 'System', NOW());
+
+-- == Threads ==
+-- td1: dave's copy of X td2: dave's Z td3: dave's copy of W
+-- te1: erin's copy of X te2: erin's Y te3: erin's copy of W
+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
+ ('55550001-0000-0000-0000-000000000001', 'td1', 'd0000001-0000-0000-0000-000000000001',
+ true, false, '2026-05-01 10:00:00+00', NULL, '2026-05-01 10:00:00+00', NOW(), NOW()),
+ ('55550001-0000-0000-0000-000000000002', 'td2', 'd0000001-0000-0000-0000-000000000001',
+ true, false, '2026-05-01 11:00:00+00', NULL, '2026-05-01 11:00:00+00', NOW(), NOW()),
+ ('55550001-0000-0000-0000-000000000003', 'td3', 'd0000001-0000-0000-0000-000000000001',
+ true, false, '2026-05-01 07:00:00+00', NULL, '2026-05-01 07:00:00+00', NOW(), NOW()),
+ ('55550002-0000-0000-0000-000000000001', 'te1', 'd0000002-0000-0000-0000-000000000002',
+ true, false, '2026-05-01 08:00:00+00', NULL, '2026-05-01 08:00:00+00', NOW(), NOW()),
+ ('55550002-0000-0000-0000-000000000002', 'te2', 'd0000002-0000-0000-0000-000000000002',
+ true, false, '2026-05-01 09:00:00+00', NULL, '2026-05-01 09:00:00+00', NOW(), NOW()),
+ ('55550002-0000-0000-0000-000000000003', 'te3', 'd0000002-0000-0000-0000-000000000002',
+ true, false, '2026-05-01 12:00:00+00', NULL, '2026-05-01 12:00:00+00', NOW(), NOW());
+
+-- == Messages ==
+-- Copies of the same conversation share the root message's global_id.
+INSERT INTO email_messages (
+ id, thread_id, link_id, provider_id, from_contact_id,
+ subject, snippet, internal_date_ts, global_id,
+ is_draft, is_sent, is_starred, is_read,
+ created_at, updated_at
+)
+VALUES
+ -- X root — both copies
+ ('66660001-0000-0000-0000-000000000001', '55550001-0000-0000-0000-000000000001',
+ 'd0000001-0000-0000-0000-000000000001', 'md1', 'c1000001-0000-0000-0000-000000000001',
+ 'Conv X', 'x root (dave copy)', '2026-05-01 08:00:00+00', '<[email protected]>',
+ false, false, false, false, NOW(), NOW()),
+ ('66660002-0000-0000-0000-000000000001', '55550002-0000-0000-0000-000000000001',
+ 'd0000002-0000-0000-0000-000000000002', 'me1', 'c1000002-0000-0000-0000-000000000002',
+ 'Conv X', 'x root (erin copy)', '2026-05-01 08:00:00+00', '<[email protected]>',
+ false, false, false, false, NOW(), NOW()),
+ -- X reply — dave only (erin was dropped)
+ ('66660001-0000-0000-0000-000000000002', '55550001-0000-0000-0000-000000000001',
+ 'd0000001-0000-0000-0000-000000000001', 'md2', 'c1000001-0000-0000-0000-000000000001',
+ 'Conv X', 'x reply (dave only)', '2026-05-01 10:00:00+00', '<[email protected]>',
+ false, false, false, false, NOW(), NOW()),
+ -- Y root — erin only
+ ('66660002-0000-0000-0000-000000000002', '55550002-0000-0000-0000-000000000002',
+ 'd0000002-0000-0000-0000-000000000002', 'me2', 'c1000002-0000-0000-0000-000000000002',
+ 'Conv Y', 'y root (erin only)', '2026-05-01 09:00:00+00', '<[email protected]>',
+ false, false, false, false, NOW(), NOW()),
+ -- Z root — dave only
+ ('66660001-0000-0000-0000-000000000003', '55550001-0000-0000-0000-000000000002',
+ 'd0000001-0000-0000-0000-000000000001', 'md3', 'c1000001-0000-0000-0000-000000000001',
+ 'Conv Z', 'z root (dave only)', '2026-05-01 11:00:00+00', '<[email protected]>',
+ false, false, false, false, NOW(), NOW()),
+ -- W root — both copies
+ ('66660001-0000-0000-0000-000000000004', '55550001-0000-0000-0000-000000000003',
+ 'd0000001-0000-0000-0000-000000000001', 'md4', 'c1000001-0000-0000-0000-000000000001',
+ 'Conv W', 'w root (dave copy)', '2026-05-01 07:00:00+00', '<[email protected]>',
+ false, false, false, false, NOW(), NOW()),
+ ('66660002-0000-0000-0000-000000000003', '55550002-0000-0000-0000-000000000003',
+ 'd0000002-0000-0000-0000-000000000002', 'me3', 'c1000002-0000-0000-0000-000000000002',
+ 'Conv W', 'w root (erin copy)', '2026-05-01 07:00:00+00', '<[email protected]>',
+ false, false, false, false, NOW(), NOW()),
+ -- W reply — erin only (dave was dropped); makes erin's copy NEWER
+ ('66660002-0000-0000-0000-000000000004', '55550002-0000-0000-0000-000000000003',
+ 'd0000002-0000-0000-0000-000000000002', 'me4', 'c1000002-0000-0000-0000-000000000002',
+ 'Conv W', 'w reply (erin only)', '2026-05-01 12:00:00+00', '<[email protected]>',
+ false, false, false, false, NOW(), NOW()),
+ -- X draft on dave's copy — EARLIEST message in the thread WITH a
+ -- global_id (provider-synced drafts carry a mailbox-local Message-ID).
+ -- Root selection must skip it (is_draft = FALSE) or dave's dedupe key
+ -- becomes the draft's local Message-ID and X stops deduping.
+ ('66660001-0000-0000-0000-000000000005', '55550001-0000-0000-0000-000000000001',
+ 'd0000001-0000-0000-0000-000000000001', 'md5', NULL,
+ 'Conv X', 'x draft (dave only)', '2026-05-01 06:00:00+00', '<[email protected]>',
+ true, false, false, false, NOW(), NOW());
+
+-- == Message labels — everything in INBOX, nothing trashed ==
+INSERT INTO email_message_labels (message_id, label_id)
+VALUES
+ ('66660001-0000-0000-0000-000000000001', '77770001-0000-0000-0000-000000000001'),
+ ('66660001-0000-0000-0000-000000000002', '77770001-0000-0000-0000-000000000001'),
+ ('66660001-0000-0000-0000-000000000003', '77770001-0000-0000-0000-000000000001'),
+ ('66660001-0000-0000-0000-000000000004', '77770001-0000-0000-0000-000000000001'),
+ ('66660002-0000-0000-0000-000000000001', '77770002-0000-0000-0000-000000000001'),
+ ('66660002-0000-0000-0000-000000000002', '77770002-0000-0000-0000-000000000001'),
+ ('66660002-0000-0000-0000-000000000003', '77770002-0000-0000-0000-000000000001'),
+ ('66660002-0000-0000-0000-000000000004', '77770002-0000-0000-0000-000000000001');
diff --git a/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_dedupe_divergent.sql b/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_dedupe_divergent.sql
new file mode 100644
index 0000000000..88d68520b4
--- /dev/null
+++ b/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_dedupe_divergent.sql
@@ -0,0 +1,47 @@
+-- Add-on to email_dynamic_query_crm_dedupe.sql (load both).
+--
+-- Conversation V — Dave was added MID-THREAD, so his copy lacks the root
+-- message. Root-by-date keys diverge ('<v-2@...>' for dave vs '<v-1@...>'
+-- for erin) and both copies are returned. This is the documented, accepted
+-- degradation of root-global_id dedupe; if the key strategy changes (e.g.
+-- to any-shared-message matching), this fixture's expectations must too.
+
+-- tdv: dave's copy of V (joined at the reply) tev: erin's copy (full)
+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
+ ('55550001-0000-0000-0000-000000000004', 'tdv', 'd0000001-0000-0000-0000-000000000001',
+ true, false, '2026-05-01 13:00:00+00', NULL, '2026-05-01 13:00:00+00', NOW(), NOW()),
+ ('55550002-0000-0000-0000-000000000004', 'tev', 'd0000002-0000-0000-0000-000000000002',
+ true, false, '2026-05-01 13:00:00+00', NULL, '2026-05-01 13:00:00+00', NOW(), NOW());
+
+INSERT INTO email_messages (
+ id, thread_id, link_id, provider_id, from_contact_id,
+ subject, snippet, internal_date_ts, global_id,
+ is_draft, is_sent, is_starred, is_read,
+ created_at, updated_at
+)
+VALUES
+ -- V root — erin only (dave wasn't on the thread yet)
+ ('66660002-0000-0000-0000-000000000005', '55550002-0000-0000-0000-000000000004',
+ 'd0000002-0000-0000-0000-000000000002', 'me5', 'c1000002-0000-0000-0000-000000000002',
+ 'Conv V', 'v root (erin only)', '2026-05-01 12:30:00+00', '<[email protected]>',
+ false, false, false, false, NOW(), NOW()),
+ -- V reply — both copies (dave added here)
+ ('66660001-0000-0000-0000-000000000006', '55550001-0000-0000-0000-000000000004',
+ 'd0000001-0000-0000-0000-000000000001', 'md6', 'c1000001-0000-0000-0000-000000000001',
+ 'Conv V', 'v reply (dave copy)', '2026-05-01 13:00:00+00', '<[email protected]>',
+ false, false, false, false, NOW(), NOW()),
+ ('66660002-0000-0000-0000-000000000006', '55550002-0000-0000-0000-000000000004',
+ 'd0000002-0000-0000-0000-000000000002', 'me6', 'c1000002-0000-0000-0000-000000000002',
+ 'Conv V', 'v reply (erin copy)', '2026-05-01 13:00:00+00', '<[email protected]>',
+ false, false, false, false, NOW(), NOW());
+
+INSERT INTO email_message_labels (message_id, label_id)
+VALUES
+ ('66660002-0000-0000-0000-000000000005', '77770002-0000-0000-0000-000000000001'),
+ ('66660001-0000-0000-0000-000000000006', '77770001-0000-0000-0000-000000000001'),
+ ('66660002-0000-0000-0000-000000000006', '77770002-0000-0000-0000-000000000001');
diff --git a/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_dedupe_shared.sql b/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_dedupe_shared.sql
new file mode 100644
index 0000000000..3fd77f7d9d
--- /dev/null
+++ b/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_dedupe_shared.sql
@@ -0,0 +1,65 @@
+-- Add-on to email_dynamic_query_crm_dedupe.sql (load both).
+--
+-- Faye is NOT on Team Beta but has her own copy of conversation X (same
+-- root global_id '<[email protected]>'), directly shared with Dave via
+-- entity_access. Under team scope + SharedEmailFilter::Include her copy
+-- enters through the Shared candidate branch and must collapse into
+-- Dave's own copy (td1). Her thread ts (14:00) is the newest of all X
+-- copies, so a dedupe failure would surface it at the top of the list.
+
+INSERT INTO "macro_user" (id, username, email, stripe_customer_id)
+VALUES
+ ('f1111111-1111-1111-1111-111111111111', '[email protected]', '[email protected]', 'stripe_faye');
+
+INSERT INTO "User" (id, email, name, macro_user_id)
+VALUES
+ ('macro|[email protected]', '[email protected]', 'Faye', 'f1111111-1111-1111-1111-111111111111');
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES
+ ('d0000003-0000-0000-0000-000000000003', 'macro|[email protected]', 'fa_faye', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)
+VALUES
+ ('c1000003-0000-0000-0000-000000000003', 'd0000003-0000-0000-0000-000000000003', '[email protected]', 'Vendor', NOW(), NOW());
+
+INSERT INTO email_labels (id, link_id, provider_label_id, name, message_list_visibility, label_list_visibility, type, created_at)
+VALUES
+ ('77770003-0000-0000-0000-000000000001', 'd0000003-0000-0000-0000-000000000003', 'INBOX', 'INBOX', 'Show', 'LabelShow', 'System', NOW()),
+ ('77770003-0000-0000-0000-000000000002', 'd0000003-0000-0000-0000-000000000003', 'TRASH', 'TRASH', 'Hide', 'LabelHide', 'System', NOW());
+
+-- tf1: faye's copy of conversation X
+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
+ ('55550003-0000-0000-0000-000000000001', 'tf1', 'd0000003-0000-0000-0000-000000000003',
+ true, false, '2026-05-01 14:00:00+00', NULL, '2026-05-01 14:00:00+00', NOW(), NOW());
+
+INSERT INTO email_messages (
+ id, thread_id, link_id, provider_id, from_contact_id,
+ subject, snippet, internal_date_ts, global_id,
+ is_draft, is_sent, is_starred, is_read,
+ created_at, updated_at
+)
+VALUES
+ ('66660003-0000-0000-0000-000000000001', '55550003-0000-0000-0000-000000000001',
+ 'd0000003-0000-0000-0000-000000000003', 'mf1', 'c1000003-0000-0000-0000-000000000003',
+ 'Conv X', 'x root (faye copy)', '2026-05-01 08:00:00+00', '<[email protected]>',
+ false, false, false, false, NOW(), NOW()),
+ ('66660003-0000-0000-0000-000000000002', '55550003-0000-0000-0000-000000000001',
+ 'd0000003-0000-0000-0000-000000000003', 'mf2', 'c1000003-0000-0000-0000-000000000003',
+ 'Conv X', 'x reply (faye only)', '2026-05-01 14:00:00+00', '<[email protected]>',
+ false, false, false, false, NOW(), NOW());
+
+INSERT INTO email_message_labels (message_id, label_id)
+VALUES
+ ('66660003-0000-0000-0000-000000000001', '77770003-0000-0000-0000-000000000001'),
+ ('66660003-0000-0000-0000-000000000002', '77770003-0000-0000-0000-000000000001');
+
+-- Direct share of faye's thread with dave
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+VALUES
+ ('55550003-0000-0000-0000-000000000001'::uuid, 'thread', 'macro|[email protected]', 'user', 'view');
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.rs
index 5d3f75afc0..d0e0351289 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
@@ -25,6 +25,9 @@ struct QueryParams {
/// When `Some(team_id)`, the "Owned" candidate source expands from
/// `t.link_id = ANY($link_ids)` to `t.link_id IN (links of every member
/// of $team_id)`. Set only after CRM scope has been validated upstream.
+ /// Also switches the candidate select into dedupe mode: team-member
+ /// copies of the same conversation collapse to one row (see
+ /// [`build_query`]).
team_id: Option<Uuid>,
}
@@ -105,13 +108,42 @@ fn push_thread_candidate_select(
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
+ END AS effective_ts"#,
+ 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
+ // (email_messages.global_id) — stable across mailboxes, unlike
+ // provider thread ids. Drafts are excluded (their Message-IDs are
+ // mailbox-local), and threads with no usable global_id fall back to
+ // their own id and never dedupe. is_own_link feeds the DISTINCT ON
+ // preference in build_query so the caller's copy wins.
+ if params.team_id.is_some() {
+ builder.push(
+ r#",
+ COALESCE(
+ (SELECT m_root.global_id FROM email_messages m_root
+ WHERE m_root.thread_id = t.id
+ AND m_root.global_id IS NOT NULL
+ AND m_root.is_draft = FALSE
+ ORDER BY m_root.internal_date_ts ASC NULLS LAST, m_root.id ASC
+ LIMIT 1),
+ t.id::text
+ ) AS dedupe_key,
+ t.link_id = ANY("#,
+ );
+ builder.push_bind(params.link_ids.clone());
+ builder.push(") AS is_own_link");
+ }
+
+ builder.push(
+ r#"
FROM email_threads t
LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id
WHERE
"#,
- sort_ts_field, sort_ts_field
- ));
+ );
match source {
ThreadCandidateSource::Owned => match params.team_id {
@@ -175,6 +207,15 @@ fn push_thread_candidate_select(
build_thread_address_filter(email_filter).push_into(builder);
}
+ // Team-scoped: the cursor moves outside the dedupe wrapper (see
+ // build_query) so the representative choice is cursor-independent.
+ // Filtering before DISTINCT ON would let a copy excluded by the
+ // cursor on page N hand its conversation back to a duplicate copy
+ // on page N+1.
+ if params.team_id.is_some() {
+ return;
+ }
+
builder.push(
r#"
-- Cursor logic
@@ -284,6 +325,18 @@ fn build_query(
"#,
);
+ // Team-scoped: dedupe team-member copies of a conversation before the
+ // cursor is applied, so the chosen representative is stable across
+ // pages. The caller's own copy wins; ties break by recency then id.
+ if params.team_id.is_some() {
+ builder.push(
+ r#"
+ SELECT DISTINCT ON (dedupe_key) *
+ FROM (
+ "#,
+ );
+ }
+
match params.shared {
SharedEmailFilter::Exclude => push_thread_candidate_select(
&mut builder,
@@ -326,12 +379,33 @@ fn build_query(
),
}
- builder.push(
- r#"
+ if params.team_id.is_some() {
+ builder.push(
+ r#"
+ ) AS candidate_threads
+ ORDER BY dedupe_key, is_own_link DESC, effective_ts DESC, id DESC
+ ) AS deduped_threads
+ -- Cursor logic (post-dedupe, on the representative row)
+ WHERE (("#,
+ );
+ builder.push_bind(params.cursor_timestamp);
+ builder.push("::timestamptz IS NULL) OR ((effective_ts, id) < (");
+ builder.push_bind(params.cursor_timestamp);
+ builder.push("::timestamptz, ");
+ builder.push_bind(params.cursor_id_str.clone());
+ builder.push(
+ r#"::uuid)))
+ ORDER BY effective_ts DESC, id DESC
+ LIMIT "#,
+ );
+ } else {
+ builder.push(
+ r#"
) AS candidate_threads
ORDER BY effective_ts DESC, id DESC
LIMIT "#,
- );
+ );
+ }
builder.push_bind(params.query_limit);
@@ -389,6 +463,29 @@ pub(super) fn debug_build_query_sql_with_resolved(
view: &PreviewView,
email_filter: &Expr<EmailLiteral>,
resolved: ResolvedFilters,
+) -> String {
+ debug_build_query_sql_inner(view, email_filter, resolved, None)
+}
+
+#[cfg(test)]
+pub(super) fn debug_build_query_sql_team_scoped(
+ view: &PreviewView,
+ email_filter: &Expr<EmailLiteral>,
+) -> String {
+ debug_build_query_sql_inner(
+ view,
+ email_filter,
+ ResolvedFilters::empty(),
+ Some(Uuid::nil()),
+ )
+}
+
+#[cfg(test)]
+fn debug_build_query_sql_inner(
+ view: &PreviewView,
+ email_filter: &Expr<EmailLiteral>,
+ resolved: ResolvedFilters,
+ team_id: Option<Uuid>,
) -> String {
use sqlx::Execute;
@@ -411,7 +508,7 @@ pub(super) fn debug_build_query_sql_with_resolved(
shared,
user_id: "test-user".to_string(),
resolved,
- team_id: None,
+ team_id,
},
)
.build()
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.rs
index eac3c3ab59..cbd7be0a29 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
@@ -523,6 +523,108 @@ fn test_build_query_orders_by_id_to_match_cursor_tiebreak() {
assert!(!sql.contains("ORDER BY t.effective_ts DESC, t.updated_at DESC"));
}
+// ---------------------------------------------------------------------------
+// Team-scoped (CRM) dedupe: one row per conversation across team mailboxes
+// ---------------------------------------------------------------------------
+//
+// Two team members on the same email each have their own email_threads row
+// (different link_id), so a team-widened query returns the conversation
+// twice. The team-scoped query shape dedupes on the root message's RFC-822
+// Message-ID (email_messages.global_id) with the caller's own copy winning.
+
+#[test]
+fn test_build_query_team_scoped_dedupes_on_root_global_id() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);
+ let expr = Expr::Literal(EmailLiteral::Sender(Email::Domain("acme.com".to_string())));
+ let sql = super::query::debug_build_query_sql_team_scoped(&view, &expr);
+
+ assert!(
+ sql.contains("SELECT DISTINCT ON (dedupe_key) *"),
+ "missing dedupe wrapper: {sql}"
+ );
+ assert!(
+ sql.contains("m_root.global_id IS NOT NULL"),
+ "dedupe key must come from root-message global_id: {sql}"
+ );
+ assert!(
+ sql.contains("m_root.is_draft = FALSE"),
+ "drafts carry mailbox-local Message-IDs and must not be the key: {sql}"
+ );
+ assert!(
+ sql.contains("ORDER BY m_root.internal_date_ts ASC NULLS LAST, m_root.id ASC"),
+ "root selection must be deterministic under timestamp ties: {sql}"
+ );
+ assert!(
+ sql.contains("t.id::text"),
+ "threads without a usable global_id must fall back to their own id: {sql}"
+ );
+ // Own copy wins, then recency, then id.
+ assert!(
+ sql.contains("ORDER BY dedupe_key, is_own_link DESC, effective_ts DESC, id DESC"),
+ "wrong representative preference order: {sql}"
+ );
+}
+
+#[test]
+fn test_build_query_team_scoped_cursor_applies_after_dedupe() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);
+ let expr = Expr::Literal(EmailLiteral::Sender(Email::Domain("acme.com".to_string())));
+ let sql = super::query::debug_build_query_sql_team_scoped(&view, &expr);
+
+ // The cursor compares the representative's already-computed effective_ts
+ // outside the dedupe wrapper...
+ assert!(
+ sql.contains("(effective_ts, id) < ("),
+ "post-dedupe cursor missing: {sql}"
+ );
+ // ...and the per-candidate cursor CASE is gone — filtering before
+ // DISTINCT ON would let duplicates resurface on later pages.
+ assert!(
+ !sql.contains("END, t.id"),
+ "candidate-level cursor must not exist in team-scoped queries: {sql}"
+ );
+}
+
+#[test]
+fn test_build_query_team_scoped_dedupe_wraps_shared_union() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);
+ let expr = Expr::Literal(EmailLiteral::Shared(
+ item_filters::SharedEmailFilter::Include,
+ ));
+ let sql = super::query::debug_build_query_sql_team_scoped(&view, &expr);
+
+ // Both the Owned and Shared candidate branches must sit inside the
+ // dedupe wrapper, so a conversation entering via both still collapses.
+ // (Skip past the shared CTE — it has its own UNION ALLs.)
+ let distinct_pos = sql
+ .find("DISTINCT ON (dedupe_key)")
+ .expect("dedupe wrapper missing");
+ let union_pos = sql[distinct_pos..]
+ .find("UNION")
+ .map(|p| distinct_pos + p)
+ .expect("candidate UNION missing after dedupe wrapper");
+ let dedupe_close = sql
+ .find(") AS deduped_threads")
+ .expect("dedupe wrapper close missing");
+ assert!(
+ union_pos < dedupe_close,
+ "UNION must be inside the dedupe wrapper: {sql}"
+ );
+}
+
+#[test]
+fn test_build_query_non_team_has_no_dedupe_machinery() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);
+ let expr = Expr::Literal(EmailLiteral::Sender(Email::Domain("acme.com".to_string())));
+ let sql = super::query::debug_build_query_sql(&view, &expr);
+
+ 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"));
+}
+
const DEFAULT_SORT_TS: &str = "t.updated_at";
#[test]
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/crm_scope_dynamic_query.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/crm_scope_dynamic_query.rs
index 3ff47142ae..5552f08c7c 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/crm_scope_dynamic_query.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/crm_scope_dynamic_query.rs
@@ -755,3 +755,322 @@ async fn crm_scope_collapses_to_empty_when_killswitch_off(
);
Ok(())
}
+
+// =====================================================================
+// Dedupe of team-member conversation copies — fixture
+// `email_dynamic_query_crm_dedupe.sql`. Two members (Dave, Erin) and
+// four conversations keyed by root-message global_id:
+// X — both copies; dave's is newer (extra reply).
+// Y — erin only. Z — dave only.
+// W — both copies; ERIN's is newer (extra reply).
+// =====================================================================
+
+const TEAM_BETA_ID: &str = "e0000002-0000-0000-0000-000000000002";
+const DAVE_LINK_ID: &str = "d0000001-0000-0000-0000-000000000001";
+const ERIN_LINK_ID: &str = "d0000002-0000-0000-0000-000000000002";
+
+const TD1_DAVE_CONV_X: &str = "55550001-0000-0000-0000-000000000001";
+const TD2_DAVE_CONV_Z: &str = "55550001-0000-0000-0000-000000000002";
+const TD3_DAVE_CONV_W: &str = "55550001-0000-0000-0000-000000000003";
+const TE1_ERIN_CONV_X: &str = "55550002-0000-0000-0000-000000000001";
+const TE2_ERIN_CONV_Y: &str = "55550002-0000-0000-0000-000000000002";
+const TE3_ERIN_CONV_W: &str = "55550002-0000-0000-0000-000000000003";
+
+/// Run a team-scoped acme.com query for one caller and return the result
+/// thread ids in order.
+async fn run_dedupe_query(
+ pool: &Pool<Postgres>,
+ caller_link: &str,
+ caller_user: &str,
+) -> anyhow::Result<Vec<String>> {
+ let team_id = Uuid::parse_str(TEAM_BETA_ID)?;
+ let link_id = Uuid::parse_str(caller_link)?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);
+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Domain(
+ "acme.com".to_string(),
+ ))));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
+
+ let results = dynamic::dynamic_email_thread_cursor(
+ pool,
+ &[link_id],
+ 100,
+ &view,
+ query,
+ caller_user,
+ Some(team_id),
+ )
+ .await?;
+ Ok(results.into_iter().map(|r| r.id.to_string()).collect())
+}
+
+// =====================================================================
+// 17. One row per conversation; the caller's own copy wins even when the
+// teammate's copy is newer (W), and teammate-only conversations come
+// back via the teammate's copy (Y).
+// =====================================================================
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query_crm_dedupe")
+ )
+)]
+async fn crm_scope_dedupes_team_copies_own_copy_wins(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let ids = run_dedupe_query(&pool, DAVE_LINK_ID, "macro|[email protected]").await?;
+
+ // Ordered by the representative's recency: Z(11) > X(10) > Y(9) > W(7).
+ // X: dave's copy (own + newer). W: dave's copy despite erin's being
+ // newer — own-copy preference precedes recency. Y: erin's copy (dave
+ // has none).
+ assert_eq!(
+ ids,
+ vec![
+ TD2_DAVE_CONV_Z.to_string(),
+ TD1_DAVE_CONV_X.to_string(),
+ TE2_ERIN_CONV_Y.to_string(),
+ TD3_DAVE_CONV_W.to_string(),
+ ],
+ "expected one row per conversation with dave's copies preferred"
+ );
+
+ Ok(())
+}
+
+// =====================================================================
+// 18. Same fixture from Erin's perspective — symmetric preference. Erin
+// gets her own X copy even though Dave's is newer.
+// =====================================================================
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query_crm_dedupe")
+ )
+)]
+async fn crm_scope_dedupe_is_caller_relative(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let ids = run_dedupe_query(&pool, ERIN_LINK_ID, "macro|[email protected]").await?;
+
+ // W(12, erin's own) > Z(11, dave-only) > Y(9, own) > X(8, erin's own
+ // copy even though dave's is at 10:00).
+ assert_eq!(
+ ids,
+ vec![
+ TE3_ERIN_CONV_W.to_string(),
+ TD2_DAVE_CONV_Z.to_string(),
+ TE2_ERIN_CONV_Y.to_string(),
+ TE1_ERIN_CONV_X.to_string(),
+ ],
+ "expected one row per conversation with erin's copies preferred"
+ );
+
+ Ok(())
+}
+
+// =====================================================================
+// 19. Dedupe is stable across cursor pages. The representative is chosen
+// before the cursor applies, so a conversation whose non-preferred
+// copy falls into a later page window must NOT resurface. With the
+// cursor inside the dedupe (the naive shape), erin's X copy (08:00)
+// would leak onto the page after dave's X copy (10:00) was returned.
+// =====================================================================
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query_crm_dedupe")
+ )
+)]
+async fn crm_scope_dedupe_stable_across_cursor_pages(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let team_id = Uuid::parse_str(TEAM_BETA_ID)?;
+ let link_id = Uuid::parse_str(DAVE_LINK_ID)?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);
+ let limit = 1;
+ let make_filter = || {
+ Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Domain(
+ "acme.com".to_string(),
+ ))))
+ };
+
+ let mut pages: Vec<String> = Vec::new();
+ let mut cursor: Option<Cursor<Uuid, CursorVal<SimpleSortMethod>, Arc<Expr<EmailLiteral>>>> =
+ None;
+ loop {
+ let query = Query::new(cursor.take(), SimpleSortMethod::UpdatedAt, make_filter());
+ let page = dynamic::dynamic_email_thread_cursor(
+ &pool,
+ &[link_id],
+ limit,
+ &view,
+ query,
+ Some(team_id),
+ )
+ .await?;
+ let Some(last) = page.last() else {
+ break;
+ };
+ cursor = Some(Cursor {
+ id: last.id,
+ limit: limit as usize,
+ val: CursorVal {
+ sort_type: SimpleSortMethod::UpdatedAt,
+ last_val: last.sort_ts,
+ },
+ filter: make_filter(),
+ });
+ pages.extend(page.into_iter().map(|r| r.id.to_string()));
+ assert!(pages.len() <= 6, "runaway pagination: {:?}", pages);
+ }
+
+ // Every conversation exactly once, own copies preferred, and neither
+ // of erin's duplicate copies (te1, te3) ever surfaces on any page.
+ assert_eq!(
+ pages,
+ vec![
+ TD2_DAVE_CONV_Z.to_string(),
+ TD1_DAVE_CONV_X.to_string(),
+ TE2_ERIN_CONV_Y.to_string(),
+ TD3_DAVE_CONV_W.to_string(),
+ ],
+ "pages must cover each conversation exactly once with no duplicate copies"
+ );
+
+ Ok(())
+}
+
+// =====================================================================
+// 20. Root selection skips drafts. Dave's X copy contains a draft that
+// is the EARLIEST message in the thread and has a (mailbox-local)
+// global_id. If the root subquery didn't filter `is_draft = FALSE`,
+// dave's key would become the draft's Message-ID and X would stop
+// deduping (te1 would reappear). Covered implicitly by #17's exact
+// vector; this test names the intent.
+// =====================================================================
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query_crm_dedupe")
+ )
+)]
+async fn crm_scope_dedupe_root_skips_drafts(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let ids = run_dedupe_query(&pool, DAVE_LINK_ID, "macro|[email protected]").await?;
+
+ assert!(
+ ids.contains(&TD1_DAVE_CONV_X.to_string()),
+ "dave's X copy must be the representative"
+ );
+ assert!(
+ !ids.contains(&TE1_ERIN_CONV_X.to_string()),
+ "X must still dedupe — the gid-less draft must not become the root"
+ );
+
+ Ok(())
+}
+
+// =====================================================================
+// 21. A copy shared from OUTSIDE the team (entity_access) collapses with
+// the caller's own copy. Faye (non-member) has a copy of X — the
+// newest of all X copies — directly shared with Dave. Under
+// Shared::Include it enters via the Shared candidate branch and must
+// dedupe into td1; a failure would put tf1 at the top of the list.
+// =====================================================================
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts(
+ "email_dynamic_query_crm_dedupe",
+ "email_dynamic_query_crm_dedupe_shared"
+ )
+ )
+)]
+async fn crm_scope_dedupe_collapses_externally_shared_copy(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ const TF1_FAYE_CONV_X: &str = "55550003-0000-0000-0000-000000000001";
+
+ let team_id = Uuid::parse_str(TEAM_BETA_ID)?;
+ let link_id = Uuid::parse_str(DAVE_LINK_ID)?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);
+ let filter = Arc::new(Expr::and(
+ Expr::Literal(EmailLiteral::Sender(Email::Domain("acme.com".to_string()))),
+ Expr::Literal(EmailLiteral::Shared(
+ item_filters::SharedEmailFilter::Include,
+ )),
+ ));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
+
+ let results = dynamic::dynamic_email_thread_cursor(
+ &pool,
+ &[link_id],
+ 100,
+ &view,
+ query,
+ Some(team_id),
+ )
+ .await?;
+ let ids: Vec<String> = results.into_iter().map(|r| r.id.to_string()).collect();
+
+ // Same vector as #17 — faye's tf1 entered via the Shared branch but
+ // collapsed into dave's own X copy.
+ assert_eq!(
+ ids,
+ vec![
+ TD2_DAVE_CONV_Z.to_string(),
+ TD1_DAVE_CONV_X.to_string(),
+ TE2_ERIN_CONV_Y.to_string(),
+ TD3_DAVE_CONV_W.to_string(),
+ ],
+ "externally shared copy must dedupe into the caller's own copy"
+ );
+ assert!(!ids.contains(&TF1_FAYE_CONV_X.to_string()));
+
+ Ok(())
+}
+
+// =====================================================================
+// 22. Documented degradation: a member added MID-THREAD has a copy
+// without the root message, so root-by-date keys diverge and both
+// copies are returned. If the dedupe key strategy ever changes,
+// update this test alongside it.
+// =====================================================================
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts(
+ "email_dynamic_query_crm_dedupe",
+ "email_dynamic_query_crm_dedupe_divergent"
+ )
+ )
+)]
+async fn crm_scope_dedupe_mid_thread_join_copies_stay_separate(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ const TDV_DAVE_CONV_V: &str = "55550001-0000-0000-0000-000000000004";
+ const TEV_ERIN_CONV_V: &str = "55550002-0000-0000-0000-000000000004";
+
+ let ids = run_dedupe_query(&pool, DAVE_LINK_ID, "macro|[email protected]").await?;
+
+ // Dave's V copy lacks the root '<v-1@...>' message — its key is
+ // '<v-2@...>' while erin's is '<v-1@...>', so both rows survive.
+ assert!(ids.contains(&TDV_DAVE_CONV_V.to_string()));
+ assert!(ids.contains(&TEV_ERIN_CONV_V.to_string()));
+ assert_eq!(
+ ids.len(),
+ 6,
+ "X/Y/Z/W dedupe as usual plus both divergent V copies, got: {:?}",
+ ids
+ );
+
+ Ok(())
+}