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(email): materialize address-pushdown CTE for soup pagination (#3152)
Evan Hutnik6c569b0259cd
diff --git a/rust/cloud-storage/.sqlx/query-6852fb9f96ae7ed17fd27c08412598b0383b0da562e63ecae81472b14ba21640.json b/rust/cloud-storage/.sqlx/query-6852fb9f96ae7ed17fd27c08412598b0383b0da562e63ecae81472b14ba21640.jsonnew file mode 100644index 0000000000..1360bf281b--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-6852fb9f96ae7ed17fd27c08412598b0383b0da562e63ecae81472b14ba21640.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id\n FROM email_labels\n WHERE link_id = $1 AND name = 'TRASH'\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "6852fb9f96ae7ed17fd27c08412598b0383b0da562e63ecae81472b14ba21640"+}diff --git a/rust/cloud-storage/.sqlx/query-eb3f310b68951e5fccde74c2390e6d53b23291547a16b19036161d5120d87a0d.json b/rust/cloud-storage/.sqlx/query-eb3f310b68951e5fccde74c2390e6d53b23291547a16b19036161d5120d87a0d.jsonnew file mode 100644index 0000000000..1351d065a4--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-eb3f310b68951e5fccde74c2390e6d53b23291547a16b19036161d5120d87a0d.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, LOWER(email_address) AS \"email_lower!\"\n FROM email_contacts\n WHERE link_id = $1 AND LOWER(email_address) = ANY($2)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "email_lower!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": [+ false,+ null+ ]+ },+ "hash": "eb3f310b68951e5fccde74c2390e6d53b23291547a16b19036161d5120d87a0d"+}diff --git a/rust/cloud-storage/email/fixtures/email_dynamic_query_address_edge_cases.sql b/rust/cloud-storage/email/fixtures/email_dynamic_query_address_edge_cases.sqlnew file mode 100644index 0000000000..e6173c0383--- /dev/null+++ b/rust/cloud-storage/email/fixtures/email_dynamic_query_address_edge_cases.sql@@ -0,0 +1,53 @@+-- Extra rows on top of `email_dynamic_query` for address-filter edge cases.+-- Loaded only by tests that need them; existing tests aren't affected.++-- Add [email protected] as BCC on message 4 so the BCC filter has data to+-- match against. Message 4 is on thread 4 (alice → john) in the base+-- fixture — the BCC test will assert that filtering by Bcc(bob) returns+-- thread 4.+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type)+VALUES+ ('30000004-0000-0000-0000-000000000004', '40000003-0000-0000-0000-000000000003', 'BCC');++-- Thread 12: a "split" thread that exercises single-message AND semantics.+-- msg12a: john → bob (john is sender; alice is NOT involved)+-- msg12b: bob → alice (alice is recipient; john is NOT the sender)+-- Filtering by `Sender(john) AND Recipient(alice)` must EXCLUDE this thread+-- because no single message in it satisfies both conjuncts. Filtering by+-- `Sender(john)` alone must INCLUDE it (proves the fixture is wired right).+--+-- inbox_visible=false so this thread doesn't show up in any of the existing+-- inbox/important tests that count threads exactly.+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+ ('20000012-0000-0000-0000-000000000012', 'thread12', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',+ false, false, NULL, NULL, '2024-01-04 00: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+ -- msg12a: from john (40000001) — no alice on it+ ('30000012-0000-0000-0000-000000000012', '20000012-0000-0000-0000-000000000012',+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg12a', '40000001-0000-0000-0000-000000000001',+ 'Split Thread Part 1', 'john writing to bob', '2024-01-04 00:00:00+00',+ false, false, false, false, NOW(), NOW()),+ -- msg12b: from bob (40000003) — no john on it+ ('30000013-0000-0000-0000-000000000013', '20000012-0000-0000-0000-000000000012',+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg12b', '40000003-0000-0000-0000-000000000003',+ 'Split Thread Part 2', 'bob writing to alice', '2024-01-04 00:01:00+00',+ false, false, false, false, NOW(), NOW());++INSERT INTO email_message_recipients (message_id, contact_id, recipient_type)+VALUES+ -- msg12a: TO bob+ ('30000012-0000-0000-0000-000000000012', '40000003-0000-0000-0000-000000000003', 'TO'),+ -- msg12b: TO alice+ ('30000013-0000-0000-0000-000000000013', '40000004-0000-0000-0000-000000000004', 'TO');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 29a097dbc9..22749755f5 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@@ -1,4 +1,5 @@use super::SqlFragment;+use super::resolve::ResolvedFilters;use crate::domain::models::{PreviewView, PreviewViewStandardLabel};use filter_ast::Expr;use item_filters::ast::email::{Email, EmailLiteral};@@ -30,28 +31,86 @@ pub(super) fn has_message_literals(ast: &Expr<EmailLiteral>) -> bool {})}-/// Builds a parameterized email address match fragment.-/// `preamble` is the raw SQL before the email comparison (EXISTS subquery header).-fn build_email_match(preamble: &str, email: &Email) -> SqlFragment {- match email {- Email::Complete(e) => {- let mut f = SqlFragment::raw(format!(- "{preamble}\n AND LOWER(c.email_address) = LOWER("- ));- f.extend(SqlFragment::bind_string(e.0.as_ref().to_string()));- f.push_raw(")\n )");- f+#[derive(Clone, Copy)]+enum AddressKind {+ Sender,+ Cc,+ Bcc,+ Recipient,+}++impl AddressKind {+ fn recipient_type_sql(self) -> Option<&'static str> {+ match self {+ AddressKind::Sender => None,+ AddressKind::Cc => Some("CC"),+ AddressKind::Bcc => Some("BCC"),+ AddressKind::Recipient => Some("TO"),}- Email::Partial(s) => {- let mut f = SqlFragment::raw(format!(- "{preamble}\n AND c.email_address ILIKE "- ));- f.extend(SqlFragment::bind_string(format!(- "%{}%",- escape_like_pattern(s)- )));- f.push_raw("\n )");- f+ }+}++/// Builds a per-message predicate for one address literal, picking the fast+/// path (`m.from_contact_id = $id` / `mr.contact_id = $id`) when the email+/// resolved to a contact id, the LOWER/ILIKE fallback when it's Partial, and+/// `FALSE` when a Complete email has no contact in this link (so any branch+/// referencing it can never match).+fn build_address_predicate_on_m(+ kind: AddressKind,+ email: &Email,+ resolved: &ResolvedFilters,+) -> SqlFragment {+ match (resolved.contact_id_for(email), email) {+ (Some(contact_id), _) => match kind {+ AddressKind::Sender => {+ let mut f = SqlFragment::raw("m.from_contact_id = ");+ f.extend(SqlFragment::bind_uuid(contact_id));+ f+ }+ _ => {+ let recipient_type = kind.recipient_type_sql().expect("non-sender kind");+ let mut f = SqlFragment::raw(format!(+ r#"EXISTS (+ SELECT 1 FROM email_message_recipients mr+ WHERE mr.message_id = m.id+ AND mr.recipient_type = '{recipient_type}'+ AND mr.contact_id = "#,+ ));+ f.extend(SqlFragment::bind_uuid(contact_id));+ f.push_raw("\n )");+ f+ }+ },+ (None, Email::Complete(_)) => SqlFragment::raw("FALSE"),+ (None, Email::Partial(s)) => {+ let pattern = format!("%{}%", escape_like_pattern(s));+ match kind {+ AddressKind::Sender => {+ let mut f = SqlFragment::raw(+ r#"EXISTS (+ SELECT 1 FROM email_contacts c+ WHERE c.id = m.from_contact_id+ AND c.email_address ILIKE "#,+ );+ f.extend(SqlFragment::bind_string(pattern));+ f.push_raw("\n )");+ f+ }+ _ => {+ let recipient_type = kind.recipient_type_sql().expect("non-sender kind");+ let mut f = SqlFragment::raw(format!(+ r#"EXISTS (+ SELECT 1 FROM email_message_recipients mr+ JOIN email_contacts c ON mr.contact_id = c.id+ WHERE mr.message_id = m.id+ AND mr.recipient_type = '{recipient_type}'+ AND c.email_address ILIKE "#,+ ));+ f.extend(SqlFragment::bind_string(pattern));+ f.push_raw("\n )");+ f+ }+ }}}}@@ -94,7 +153,10 @@ fn build_sender_importance_override_filter(is_important: bool) -> SqlFragment {))}-pub(super) fn build_message_email_filter(ast: &Expr<EmailLiteral>) -> SqlFragment {+pub(super) fn build_message_email_filter(+ ast: &Expr<EmailLiteral>,+ resolved: &ResolvedFilters,+) -> SqlFragment {let fragment = ast.collapse_frames(|frame| match frame {filter_ast::ExprFrame::And(a, b) => SqlFragment::and(a, b),filter_ast::ExprFrame::Or(a, b) => SqlFragment::or(a, b),@@ -104,39 +166,21 @@ pub(super) fn build_message_email_filter(ast: &Expr<EmailLiteral>) -> SqlFragmenEmailLiteral::ThreadId(_) | EmailLiteral::ProjectId(_),) => SqlFragment::raw("TRUE"),- filter_ast::ExprFrame::Literal(EmailLiteral::Sender(email)) => build_email_match(- r#"EXISTS (- SELECT 1 FROM email_contacts c- WHERE c.id = m.from_contact_id"#,- &email,- ),+ filter_ast::ExprFrame::Literal(EmailLiteral::Sender(email)) => {+ build_address_predicate_on_m(AddressKind::Sender, &email, resolved)+ }- filter_ast::ExprFrame::Literal(EmailLiteral::Recipient(email)) => build_email_match(- r#"EXISTS (- SELECT 1 FROM email_message_recipients mr- JOIN email_contacts c ON mr.contact_id = c.id- WHERE mr.message_id = m.id- AND mr.recipient_type = 'TO'"#,- &email,- ),+ filter_ast::ExprFrame::Literal(EmailLiteral::Recipient(email)) => {+ build_address_predicate_on_m(AddressKind::Recipient, &email, resolved)+ }- filter_ast::ExprFrame::Literal(EmailLiteral::Cc(email)) => build_email_match(- r#"EXISTS (- SELECT 1 FROM email_message_recipients mr- JOIN email_contacts c ON mr.contact_id = c.id- WHERE mr.message_id = m.id- AND mr.recipient_type = 'CC'"#,- &email,- ),+ filter_ast::ExprFrame::Literal(EmailLiteral::Cc(email)) => {+ build_address_predicate_on_m(AddressKind::Cc, &email, resolved)+ }- filter_ast::ExprFrame::Literal(EmailLiteral::Bcc(email)) => build_email_match(- r#"EXISTS (- SELECT 1 FROM email_message_recipients mr- JOIN email_contacts c ON mr.contact_id = c.id- WHERE mr.message_id = m.id- AND mr.recipient_type = 'BCC'"#,- &email,- ),+ filter_ast::ExprFrame::Literal(EmailLiteral::Bcc(email)) => {+ build_address_predicate_on_m(AddressKind::Bcc, &email, resolved)+ }filter_ast::ExprFrame::Literal(EmailLiteral::Importance(true)) => {let mut f = SqlFragment::raw(@@ -224,6 +268,306 @@ pub(super) fn build_message_email_filter(ast: &Expr<EmailLiteral>) -> SqlFragmenfragment.with_and_prefix()}+/// True if the AST contains any address-typed literal (Sender/Cc/Bcc/Recipient).+pub(super) fn has_address_literals(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::Sender(_)+ | EmailLiteral::Cc(_)+ | EmailLiteral::Bcc(_)+ | EmailLiteral::Recipient(_),+ ) => true,+ filter_ast::ExprFrame::Literal(_) => false,+ })+}++/// True if the subtree contains only address literals (Sender/Cc/Bcc/Recipient)+/// composed via And/Or/Not. Used to decide whether a top-level conjunct can be+/// safely pushed into the candidate-thread pre-filter without risking false+/// negatives (e.g., `Sender(X) OR Importance(true)` cannot be reduced to just+/// `Sender(X)` at the candidate stage).+fn is_pure_address_subtree(expr: &Expr<EmailLiteral>) -> bool {+ expr.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::Sender(_)+ | EmailLiteral::Cc(_)+ | EmailLiteral::Bcc(_)+ | EmailLiteral::Recipient(_),+ ) => true,+ filter_ast::ExprFrame::Literal(_) => false,+ })+}++/// Walks the top-level AND-chain and returns subtrees that are pure-address.+/// Non-pure subtrees (e.g. `Or(Sender, Importance)`) are skipped because pushing+/// them into the candidate-thread filter would change semantics.+fn extract_address_only_conjuncts(expr: &Expr<EmailLiteral>) -> Vec<&Expr<EmailLiteral>> {+ fn walk<'a>(e: &'a Expr<EmailLiteral>, out: &mut Vec<&'a Expr<EmailLiteral>>) {+ match e {+ Expr::And(a, b) => {+ walk(a, out);+ walk(b, out);+ }+ other => {+ if is_pure_address_subtree(other) {+ out.push(other);+ }+ }+ }+ }+ let mut out = Vec::new();+ walk(expr, &mut out);+ out+}++/// Builds the per-message address predicate over the same `m` aliases the+/// LATERAL uses, with resolved contact ids substituted in. Caller guarantees+/// the input is a pure-address subtree.+fn build_address_message_predicate(+ expr: &Expr<EmailLiteral>,+ resolved: &ResolvedFilters,+) -> SqlFragment {+ expr.collapse_frames(|frame| match frame {+ filter_ast::ExprFrame::And(a, b) => SqlFragment::and(a, b),+ filter_ast::ExprFrame::Or(a, b) => SqlFragment::or(a, b),+ filter_ast::ExprFrame::Not(a) => SqlFragment::not(a),++ filter_ast::ExprFrame::Literal(EmailLiteral::Sender(email)) => {+ build_address_predicate_on_m(AddressKind::Sender, &email, resolved)+ }+ filter_ast::ExprFrame::Literal(EmailLiteral::Recipient(email)) => {+ build_address_predicate_on_m(AddressKind::Recipient, &email, resolved)+ }+ filter_ast::ExprFrame::Literal(EmailLiteral::Cc(email)) => {+ build_address_predicate_on_m(AddressKind::Cc, &email, resolved)+ }+ filter_ast::ExprFrame::Literal(EmailLiteral::Bcc(email)) => {+ build_address_predicate_on_m(AddressKind::Bcc, &email, resolved)+ }++ filter_ast::ExprFrame::Literal(_) => SqlFragment::raw("TRUE"),+ })+}++/// Builds the `NOT EXISTS (… TRASH …)` fragment used inside the candidate+/// subquery. Uses a direct `ml.label_id = $trash_label_id` probe (full PK+/// match on `email_message_labels`) when the trash label is resolved.+/// Returns `TRUE` (no exclusion) when the link has no TRASH label —+/// callers must always pre-resolve via `resolve_filters`, and a missing+/// TRASH label means no message can be trashed in the first place.+fn build_trash_check(resolved: &ResolvedFilters) -> SqlFragment {+ match resolved.trash_label_id() {+ Some(id) => {+ let mut f = SqlFragment::raw(+ r#"NOT EXISTS (+ SELECT 1 FROM email_message_labels ml+ WHERE ml.message_id = m.id AND ml.label_id = "#,+ );+ f.extend(SqlFragment::bind_uuid(id));+ f.push_raw(+ r#"+ )"#,+ );+ f+ }+ None => SqlFragment::raw("TRUE"),+ }+}++/// True when the AST contains at least one pure-address top-level+/// AND-conjunct, i.e. the candidate WHERE will reference `matching_threads`.+/// Callers use this to decide whether to emit the CTE definition.+pub(super) fn wants_address_pushdown(ast: &Expr<EmailLiteral>) -> bool {+ !extract_address_only_conjuncts(ast).is_empty()+}++/// Emits the `AND t.id IN (SELECT thread_id FROM matching_threads)` fragment+/// pushed into the candidate-thread WHERE. The CTE itself is built by+/// `build_matching_threads_cte_body` and pasted into the top-level `WITH …`+/// chain. Returns empty when there are no pure-address conjuncts to push.+pub(super) fn build_thread_address_filter(ast: &Expr<EmailLiteral>) -> SqlFragment {+ if !wants_address_pushdown(ast) {+ return SqlFragment::empty();+ }+ SqlFragment::raw(" AND t.id IN (SELECT thread_id FROM matching_threads)")+}++/// 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-branches+/// is only correct for OR-trees: each branch contributes thread_ids+/// independently and the union of branches matches the OR semantics.+fn flatten_or_tree_of_address_literals(+ expr: &Expr<EmailLiteral>,+) -> Option<Vec<(AddressKind, &Email)>> {+ fn walk<'a>(e: &'a Expr<EmailLiteral>, out: &mut Vec<(AddressKind, &'a Email)>) -> bool {+ match e {+ Expr::Or(a, b) => walk(a, out) && walk(b, out),+ Expr::Literal(EmailLiteral::Sender(email)) => {+ out.push((AddressKind::Sender, email));+ true+ }+ Expr::Literal(EmailLiteral::Cc(email)) => {+ out.push((AddressKind::Cc, email));+ true+ }+ Expr::Literal(EmailLiteral::Bcc(email)) => {+ out.push((AddressKind::Bcc, email));+ true+ }+ Expr::Literal(EmailLiteral::Recipient(email)) => {+ out.push((AddressKind::Recipient, email));+ true+ }+ _ => false,+ }+ }+ let mut out = Vec::new();+ if walk(expr, &mut out) {+ Some(out)+ } else {+ None+ }+}++/// Builds one `SELECT m.thread_id FROM …` UNION branch for a single+/// positive address literal. Returns `None` for unresolved Complete emails+/// — the branch can't match anything, so we drop it from the UNION rather+/// than emitting a `WHERE FALSE` branch.+fn build_union_branch(+ kind: AddressKind,+ email: &Email,+ resolved: &ResolvedFilters,+) -> Option<SqlFragment> {+ let trash = build_trash_check(resolved);+ match (resolved.contact_id_for(email), email) {+ (Some(contact_id), _) => {+ let mut f = match kind {+ AddressKind::Sender => {+ let mut f = SqlFragment::raw(+ "SELECT m.thread_id FROM email_messages m WHERE m.from_contact_id = ",+ );+ f.extend(SqlFragment::bind_uuid(contact_id));+ f+ }+ _ => {+ let recipient_type = kind.recipient_type_sql().expect("non-sender kind");+ let mut f = SqlFragment::raw(+ "SELECT m.thread_id FROM email_message_recipients mr \+ JOIN email_messages m ON m.id = mr.message_id \+ WHERE mr.contact_id = ",+ );+ f.extend(SqlFragment::bind_uuid(contact_id));+ f.push_raw(format!(" AND mr.recipient_type = '{recipient_type}'"));+ f+ }+ };+ f.push_raw(" AND ");+ f.extend(trash);+ Some(f)+ }+ (None, Email::Complete(_)) => None,+ (None, Email::Partial(s)) => {+ let pattern = format!("%{}%", escape_like_pattern(s));+ let mut f = match kind {+ AddressKind::Sender => {+ let mut f = SqlFragment::raw(+ "SELECT m.thread_id FROM email_contacts c \+ JOIN email_messages m ON m.from_contact_id = c.id \+ WHERE c.email_address ILIKE ",+ );+ f.extend(SqlFragment::bind_string(pattern));+ f+ }+ _ => {+ let recipient_type = kind.recipient_type_sql().expect("non-sender kind");+ let mut f = SqlFragment::raw(+ "SELECT m.thread_id FROM email_contacts c \+ JOIN email_message_recipients mr ON mr.contact_id = c.id \+ JOIN email_messages m ON m.id = mr.message_id \+ WHERE c.email_address ILIKE ",+ );+ f.extend(SqlFragment::bind_string(pattern));+ f.push_raw(format!(" AND mr.recipient_type = '{recipient_type}'"));+ f+ }+ };+ f.push_raw(" AND ");+ f.extend(trash);+ Some(f)+ }+ }+}++/// Builds the body of the `matching_threads` CTE — i.e., everything+/// between `MATERIALIZED (` and `)`. Two shapes:+///+/// 1. **UNION-of-branches** (preferred): when the candidate filter is a+/// single conjunct that's a flat OR-tree of positive single-address+/// literals (e.g. `Sender(X) OR Cc(X) OR Bcc(X) OR Recipient(X)`), each+/// literal becomes its own UNION branch. Each branch is index-driven+/// via `idx_email_messages_from_contact_id` /+/// `idx_email_message_recipients_contact_id`, so total work is+/// proportional to the contact's actual mention count rather than+/// mailbox size.+/// 2. **Combined predicate**: for everything else (multiple AND conjuncts,+/// NOT inside a conjunct, mixed nested operators) we emit a single+/// `SELECT DISTINCT m.thread_id FROM email_messages m WHERE …` whose+/// WHERE is the AND of all per-conjunct predicates. Single-message+/// semantics is preserved (a thread matches iff ∃ one message satisfying+/// every conjunct).+///+/// Returns `None` when there are no pure-address conjuncts to push down.+pub(super) fn build_matching_threads_cte_body(+ ast: &Expr<EmailLiteral>,+ resolved: &ResolvedFilters,+) -> Option<SqlFragment> {+ let conjuncts = extract_address_only_conjuncts(ast);+ if conjuncts.is_empty() {+ return None;+ }++ if conjuncts.len() == 1+ && let Some(literals) = flatten_or_tree_of_address_literals(conjuncts[0])+ {+ let branches: Vec<SqlFragment> = literals+ .into_iter()+ .filter_map(|(k, e)| build_union_branch(k, e, resolved))+ .collect();+ if !branches.is_empty() {+ let mut iter = branches.into_iter();+ let mut f = iter.next().expect("non-empty checked above");+ for branch in iter {+ f.push_raw("\n UNION\n ");+ f.extend(branch);+ }+ return Some(f);+ }+ // All branches were unresolved Complete emails — emit a no-rows+ // form so the JOIN against matching_threads is empty.+ return Some(SqlFragment::raw(+ "SELECT NULL::uuid AS thread_id WHERE FALSE",+ ));+ }++ // Combined-predicate fallback: AND all conjuncts and emit one subquery.+ let predicate = conjuncts+ .into_iter()+ .map(|c| build_address_message_predicate(c, resolved))+ .reduce(SqlFragment::and)+ .expect("non-empty checked above");++ let mut f = SqlFragment::raw("SELECT DISTINCT m.thread_id FROM email_messages m WHERE ");+ f.extend(build_trash_check(resolved));+ f.push_raw(" AND ");+ f.extend(predicate);+ Some(f)+}+/// Builds thread-level SQL WHERE conditions. Message-level literals map to TRUE.pub(super) fn build_thread_email_filter(ast: &Expr<EmailLiteral>) -> SqlFragment {let fragment = ast.collapse_frames(|frame| match frame {@@ -369,3 +713,27 @@ pub(super) fn get_sort_timestamp_field(view: &PreviewView) -> &'static str {_ => "COALESCE(t.latest_non_spam_message_ts, t.updated_at)",}}++/// Builds the LATERAL's TRASH-exclusion fragment using the resolved label id+/// when available. Returns `TRUE` (no exclusion) when the link has no TRASH+/// label — same rationale as `build_trash_check`: a missing TRASH label+/// means no message can be trashed. Anchored on `m.id` inside the LATERAL,+/// so callers shouldn't add their own AND prefix.+pub(super) fn build_lateral_trash_exclusion(resolved: &ResolvedFilters) -> SqlFragment {+ match resolved.trash_label_id() {+ Some(id) => {+ let mut f = SqlFragment::raw(+ r#"NOT EXISTS (+ SELECT 1 FROM email_message_labels ml+ WHERE ml.message_id = m.id AND ml.label_id = "#,+ );+ f.extend(SqlFragment::bind_uuid(id));+ f.push_raw(+ r#"+ )"#,+ );+ f+ }+ None => SqlFragment::raw("TRUE"),+ }+}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/mod.rsindex 95b688be8e..fb69f5eb31 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/mod.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/mod.rs@@ -3,6 +3,7 @@mod filters;mod query;+mod resolve;#[cfg(test)]mod tests;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 2f631e1b7b..7e81ebc91d 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@@ -1,4 +1,5 @@use super::filters::*;+use super::resolve::{ResolvedFilters, can_short_circuit, resolve_filters};use crate::domain::models::{PreviewView, PreviewViewStandardLabel};use crate::outbound::email_pg_repo::db_types::*;use chrono::{DateTime, Utc};@@ -20,6 +21,7 @@ struct QueryParams {is_important: bool,shared: SharedEmailFilter,user_id: String,+ resolved: ResolvedFilters,}enum ThreadCandidateSource {@@ -27,6 +29,42 @@ enum ThreadCandidateSource {Shared,}+/// 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+/// commas between sibling CTEs.+fn push_shared_cte(builder: &mut QueryBuilder<'static, Postgres>, params: &QueryParams) {+ builder.push(+ r#"user_source_ids AS (+ SELECT cp.channel_id::text as source_id FROM comms_channel_participants cp+ WHERE cp.user_id = "#,+ );+ builder.push_bind(params.user_id.clone());+ builder.push(+ r#" AND cp.left_at IS NULL+ UNION ALL+ SELECT t.team_id::text FROM team_user t+ WHERE t.user_id = "#,+ );+ builder.push_bind(params.user_id.clone());+ builder.push(+ r#"+ UNION ALL+ SELECT "#,+ );+ builder.push_bind(params.user_id.clone());+ builder.push(+ r#"+ ),+ SharedEmailThreads AS (+ SELECT entity_id AS thread_id+ FROM entity_access+ WHERE source_id = ANY(SELECT source_id FROM user_source_ids)+ AND entity_type = 'thread'+ )"#,+ );+}+fn push_thread_candidate_select(builder: &mut QueryBuilder<'static, Postgres>,view: &PreviewView,@@ -90,6 +128,15 @@ fn push_thread_candidate_select(build_thread_email_filter(email_filter).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) {+ build_thread_address_filter(email_filter).push_into(builder);+ }+builder.push(r#"-- Cursor logic@@ -132,43 +179,26 @@ fn build_query(let view_message_filter = build_view_message_filter(view);let needs_shared_cte = !matches!(params.shared, SharedEmailFilter::Exclude);-- let mut builder = if needs_shared_cte {- let mut b = sqlx::QueryBuilder::new(- r#"- WITH user_source_ids AS (- SELECT cp.channel_id::text as source_id FROM comms_channel_participants cp- WHERE cp.user_id = "#,- );- b.push_bind(params.user_id.clone());- b.push(- r#" AND cp.left_at IS NULL- UNION ALL- SELECT t.team_id::text FROM team_user t- WHERE t.user_id = "#,- );- b.push_bind(params.user_id.clone());- b.push(- r#"- UNION ALL- SELECT "#,- );- b.push_bind(params.user_id.clone());- b.push(- r#"- ),- SharedEmailThreads AS (- SELECT entity_id AS thread_id- FROM entity_access- WHERE source_id = ANY(SELECT source_id FROM user_source_ids)- AND entity_type = 'thread'- )- "#,- );- b- } else {- sqlx::QueryBuilder::new("")- };+ let matching_threads_body = build_matching_threads_cte_body(email_filter, ¶ms.resolved);++ let mut builder = sqlx::QueryBuilder::new("");+ if needs_shared_cte || matching_threads_body.is_some() {+ builder.push("\n WITH ");+ let mut needs_comma = false;+ if needs_shared_cte {+ push_shared_cte(&mut builder, ¶ms);+ needs_comma = true;+ }+ if let Some(body) = matching_threads_body {+ if needs_comma {+ builder.push(",\n ");+ }+ builder.push("matching_threads AS MATERIALIZED (\n ");+ body.push_into(&mut builder);+ builder.push("\n )");+ }+ builder.push("\n ");+ }builder.push(r#"@@ -279,12 +309,9 @@ fn build_query(m.is_draftFROM email_messages mWHERE m.thread_id = t.id- AND NOT EXISTS (- SELECT 1 FROM email_message_labels ml JOIN email_labels l ON ml.label_id = l.id- WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id- )- "#,+ AND "#,);+ build_lateral_trash_exclusion(¶ms.resolved).push_into(&mut builder);// Add view-specific message filtersif !view_message_filter.is_empty() {@@ -292,7 +319,7 @@ fn build_query(}if has_message_literals(email_filter) {- build_message_email_filter(email_filter).push_into(&mut builder);+ build_message_email_filter(email_filter, ¶ms.resolved).push_into(&mut builder);}builder.push(@@ -315,6 +342,15 @@ fn build_query(pub(super) fn debug_build_query_sql(view: &PreviewView,email_filter: &Expr<EmailLiteral>,+) -> String {+ debug_build_query_sql_with_resolved(view, email_filter, ResolvedFilters::empty())+}++#[cfg(test)]+pub(super) fn debug_build_query_sql_with_resolved(+ view: &PreviewView,+ email_filter: &Expr<EmailLiteral>,+ resolved: ResolvedFilters,) -> String {use sqlx::Execute;@@ -336,6 +372,7 @@ pub(super) fn debug_build_query_sql(is_important,shared,user_id: "test-user".to_string(),+ resolved,},).build()@@ -405,6 +442,14 @@ pub(crate) async fn dynamic_email_thread_cursor(PreviewView::StandardLabel(PreviewViewStandardLabel::Important));+ // Resolve Complete email addresses to contact ids and look up the TRASH+ // label id once, so the candidate WHERE can use direct id equality+ // instead of joining email_contacts/email_labels per message row.+ let resolved = resolve_filters(pool, *link_id, email_filter).await?;+ if can_short_circuit(email_filter, &resolved) {+ return Ok(Vec::new());+ }+let mut qb = build_query(view,email_filter,@@ -417,8 +462,10 @@ pub(crate) async fn dynamic_email_thread_cursor(is_important,shared,user_id: user_id.to_string(),+ resolved,},);+qb.build().try_map(|row| {Ok(ThreadPreviewCursorDbRow {diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/resolve.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/resolve.rsnew file mode 100644index 0000000000..9c51f4f602--- /dev/null+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/resolve.rs@@ -0,0 +1,185 @@+use filter_ast::Expr;+use item_filters::ast::email::{Email, EmailLiteral};+use sqlx::PgPool;+use std::collections::HashMap;+use uuid::Uuid;++/// Caches lookups that are repeated thousands of times inside the address+/// filter — `email_contacts.id` for each Complete email referenced by the+/// AST, plus the `email_labels.id` for the per-link TRASH label. Resolving+/// once up front lets the candidate WHERE use direct id equality instead of+/// joining `email_contacts` / `email_labels` per message row.+pub(super) struct ResolvedFilters {+ /// Lowercased email address → contact id, for every Complete address in+ /// the AST that has a row in `email_contacts` for this link.+ contact_ids: HashMap<String, Uuid>,+ /// The TRASH label id for this link, if one exists.+ trash_label_id: Option<Uuid>,+}++impl ResolvedFilters {+ /// Returns the resolved contact id for a Complete email, or `None` for+ /// unresolved Completes and Partial emails. Unresolved Completes will+ /// be emitted as `FALSE` by the SQL builder.+ pub(super) fn contact_id_for(&self, email: &Email) -> Option<Uuid> {+ match email {+ Email::Complete(e) => {+ let lowered = e.0.as_ref().to_lowercase();+ self.contact_ids.get(&lowered).copied()+ }+ Email::Partial(_) => None,+ }+ }++ pub(super) fn trash_label_id(&self) -> Option<Uuid> {+ self.trash_label_id+ }++ #[cfg(test)]+ pub(super) fn empty() -> Self {+ Self {+ contact_ids: HashMap::new(),+ trash_label_id: None,+ }+ }++ #[cfg(test)]+ pub(super) fn with_contact(mut self, lowered_email: impl Into<String>, id: Uuid) -> Self {+ self.contact_ids.insert(lowered_email.into(), id);+ self+ }++ #[cfg(test)]+ pub(super) fn with_trash(mut self, id: Uuid) -> Self {+ self.trash_label_id = Some(id);+ self+ }+}++/// Walks the AST collecting every Complete email address (lowercased,+/// deduplicated) so they can be resolved in one DB round trip.+pub(super) fn collect_complete_emails(ast: &Expr<EmailLiteral>) -> Vec<String> {+ fn walk(e: &Expr<EmailLiteral>, out: &mut Vec<String>) {+ match e {+ Expr::And(a, b) | Expr::Or(a, b) => {+ walk(a, out);+ walk(b, out);+ }+ Expr::Not(a) => walk(a, out),+ Expr::Literal(lit) => match lit {+ EmailLiteral::Sender(Email::Complete(e))+ | EmailLiteral::Cc(Email::Complete(e))+ | EmailLiteral::Bcc(Email::Complete(e))+ | EmailLiteral::Recipient(Email::Complete(e)) => {+ out.push(e.0.as_ref().to_lowercase());+ }+ _ => {}+ },+ }+ }+ let mut out = Vec::new();+ walk(ast, &mut out);+ out.sort();+ out.dedup();+ out+}++/// Constant-folds the AST treating unresolved Complete emails as `FALSE`.+/// Returns `Some(b)` when the whole AST collapses to a constant under that+/// substitution, `None` otherwise. A `Some(false)` result means no thread+/// can match — the caller can short-circuit to an empty page without+/// running the main query.+pub(super) fn fold_unresolved(+ ast: &Expr<EmailLiteral>,+ resolved: &ResolvedFilters,+) -> Option<bool> {+ fn lit_value(literal: &EmailLiteral, resolved: &ResolvedFilters) -> Option<bool> {+ let email = match literal {+ EmailLiteral::Sender(e)+ | EmailLiteral::Cc(e)+ | EmailLiteral::Bcc(e)+ | EmailLiteral::Recipient(e) => e,+ _ => return None,+ };+ match email {+ Email::Complete(e) => {+ let lowered = e.0.as_ref().to_lowercase();+ if resolved.contact_ids.contains_key(&lowered) {+ None+ } else {+ Some(false)+ }+ }+ Email::Partial(_) => None,+ }+ }++ match ast {+ Expr::And(a, b) => match (fold_unresolved(a, resolved), fold_unresolved(b, resolved)) {+ (Some(false), _) | (_, Some(false)) => Some(false),+ (Some(true), x) | (x, Some(true)) => x,+ (None, None) => None,+ },+ Expr::Or(a, b) => match (fold_unresolved(a, resolved), fold_unresolved(b, resolved)) {+ (Some(true), _) | (_, Some(true)) => Some(true),+ (Some(false), x) | (x, Some(false)) => x,+ (None, None) => None,+ },+ Expr::Not(a) => fold_unresolved(a, resolved).map(|b| !b),+ Expr::Literal(lit) => lit_value(lit, resolved),+ }+}++/// True when the AST cannot match any thread because at least one+/// positive-polarity Complete email has no contact in this link. Caller+/// should return an empty result without running the main query.+pub(super) fn can_short_circuit(ast: &Expr<EmailLiteral>, resolved: &ResolvedFilters) -> bool {+ matches!(fold_unresolved(ast, resolved), Some(false))+}++/// Resolves all Complete emails in the AST to `contact_id`s and looks up+/// the TRASH label id for the link in one (or two) DB round trip(s).+#[tracing::instrument(skip(pool, ast), err)]+pub(super) async fn resolve_filters(+ pool: &PgPool,+ link_id: Uuid,+ ast: &Expr<EmailLiteral>,+) -> Result<ResolvedFilters, sqlx::Error> {+ let trash_label_id: Option<Uuid> = sqlx::query_scalar!(+ r#"+ SELECT id+ FROM email_labels+ WHERE link_id = $1 AND name = 'TRASH'+ LIMIT 1+ "#,+ link_id,+ )+ .fetch_optional(pool)+ .await?;++ let emails = collect_complete_emails(ast);+ let contact_ids = if emails.is_empty() {+ HashMap::new()+ } else {+ let rows = sqlx::query!(+ r#"+ SELECT id, LOWER(email_address) AS "email_lower!"+ FROM email_contacts+ WHERE link_id = $1 AND LOWER(email_address) = ANY($2)+ "#,+ link_id,+ &emails,+ )+ .fetch_all(pool)+ .await?;++ rows.into_iter()+ .map(|r| (r.email_lower, r.id))+ .collect::<HashMap<_, _>>()+ };++ Ok(ResolvedFilters {+ contact_ids,+ trash_label_id,+ })+}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 06765ece1a..d29566c71a 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@@ -1,3 +1,6 @@+use super::resolve::{+ ResolvedFilters, can_short_circuit, collect_complete_emails, fold_unresolved,+};use super::*;use crate::domain::models::{PreviewView, PreviewViewStandardLabel};use filter_ast::Expr;@@ -6,28 +9,125 @@ use macro_user_id::cowlike::CowLike;use macro_user_id::email::EmailStr;use uuid::Uuid;+fn complete(s: &str) -> Email {+ Email::Complete(EmailStr::parse_from_str(s).unwrap().into_owned())+}++/// A `ResolvedFilters` that has resolved every Complete email referenced+/// here. Lets tests exercise the fast (`m.from_contact_id = $uuid`) path+/// without spinning up a DB.+fn resolved_with(emails: &[(&str, Uuid)]) -> ResolvedFilters {+ let mut r = ResolvedFilters::empty().with_trash(Uuid::new_v4());+ for (e, id) in emails {+ r = r.with_contact(e.to_lowercase(), *id);+ }+ r+}++/// `ResolvedFilters` populated only with the listed emails (no trash+/// label). Used by the `resolve::*` constant-folding tests where we only+/// care which Complete emails resolve.+fn resolved_with_random_ids(emails: &[&str]) -> ResolvedFilters {+ let mut r = ResolvedFilters::empty();+ for e in emails {+ r = r.with_contact(e.to_lowercase(), Uuid::new_v4());+ }+ r+}++#[test]+fn unresolved_sender_short_circuits() {+ let expr = Expr::Literal(EmailLiteral::Sender(complete("[email protected]")));+ let r = resolved_with_random_ids(&[]);+ assert!(can_short_circuit(&expr, &r));+}+#[test]-fn test_build_message_email_filter_sender_complete() {- let email = Email::Complete(- EmailStr::parse_from_str("[email protected]")- .unwrap()- .into_owned(),+fn resolved_sender_does_not_short_circuit() {+ let expr = Expr::Literal(EmailLiteral::Sender(complete("[email protected]")));+ let r = resolved_with_random_ids(&["[email protected]"]);+ assert!(!can_short_circuit(&expr, &r));+}++#[test]+fn unresolved_under_not_does_not_short_circuit() {+ let expr = Expr::is_not(Expr::Literal(EmailLiteral::Sender(complete(+ "[email protected]",+ ))));+ let r = resolved_with_random_ids(&[]);+ assert!(!can_short_circuit(&expr, &r));+}++#[test]+fn or_with_one_unresolved_does_not_short_circuit() {+ let expr = Expr::or(+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),);- let expr = Expr::Literal(EmailLiteral::Sender(email));- let result = build_message_email_filter(&expr);+ let r = resolved_with_random_ids(&["[email protected]"]);+ assert!(!can_short_circuit(&expr, &r));+}++#[test]+fn and_with_one_unresolved_short_circuits() {+ let expr = Expr::and(+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),+ );+ let r = resolved_with_random_ids(&["[email protected]"]);+ assert!(can_short_circuit(&expr, &r));+}++#[test]+fn collect_dedups_case_insensitively() {+ let expr = Expr::or(+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),+ Expr::Literal(EmailLiteral::Recipient(complete("[email protected]"))),+ );+ let collected = collect_complete_emails(&expr);+ assert_eq!(collected, vec!["[email protected]"]);+}++#[test]+fn partial_emails_are_never_constant() {+ let expr = Expr::Literal(EmailLiteral::Sender(Email::Partial("foo".to_string())));+ let r = ResolvedFilters::empty();+ assert!(!can_short_circuit(&expr, &r));+ assert_eq!(fold_unresolved(&expr, &r), None);+}++#[test]+fn test_build_message_email_filter_sender_complete_resolved_emits_contact_id() {+ let id = Uuid::new_v4();+ let expr = Expr::Literal(EmailLiteral::Sender(complete("[email protected]")));+ let resolved = resolved_with(&[("[email protected]", id)]);+ let result = build_message_email_filter(&expr, &resolved);let debug = result.to_debug_sql();- assert!(debug.contains("m.from_contact_id"));- assert!(debug.contains("LOWER(c.email_address) = LOWER("));- assert!(result.has_bind_string("[email protected]"));+ assert!(debug.contains("m.from_contact_id = "));+ // No LOWER/email_contacts join when we have a resolved contact id.+ assert!(!debug.contains("LOWER(c.email_address)"));+ assert!(!debug.contains("FROM email_contacts"));+ assert!(result.has_bind_uuid(&id));+ // The email address itself never appears in the SQL — only the uuid.assert!(result.has_no_raw_containing("[email protected]"));}+#[test]+fn test_build_message_email_filter_sender_complete_unresolved_emits_false() {+ let expr = Expr::Literal(EmailLiteral::Sender(complete("[email protected]")));+ let result = build_message_email_filter(&expr, &ResolvedFilters::empty());+ let debug = result.to_debug_sql();++ assert!(debug.contains("FALSE"));+ assert!(result.has_no_raw_containing("[email protected]"));+}+#[test]fn test_build_message_email_filter_sender_partial() {let email = Email::Partial("example".to_string());let expr = Expr::Literal(EmailLiteral::Sender(email));- let result = build_message_email_filter(&expr);+ let result = build_message_email_filter(&expr, &ResolvedFilters::empty());let debug = result.to_debug_sql();assert!(debug.contains("m.from_contact_id"));@@ -39,7 +139,7 @@ fn test_build_message_email_filter_sender_partial() {#[test]fn test_build_message_email_filter_importance_true_includes_drafts() {let expr = Expr::Literal(EmailLiteral::Importance(true));- let result = build_message_email_filter(&expr);+ let result = build_message_email_filter(&expr, &ResolvedFilters::empty());let debug = result.to_debug_sql();assert!(debug.contains("m.is_draft = TRUE"));@@ -48,7 +148,7 @@ fn test_build_message_email_filter_importance_true_includes_drafts() {#[test]fn test_build_message_email_filter_importance_true_excludes_trash() {let expr = Expr::Literal(EmailLiteral::Importance(true));- let result = build_message_email_filter(&expr);+ let result = build_message_email_filter(&expr, &ResolvedFilters::empty());let debug = result.to_debug_sql();assert!(debug.contains("l.name = 'TRASH'"));@@ -58,7 +158,7 @@ fn test_build_message_email_filter_importance_true_excludes_trash() {#[test]fn test_build_message_email_filter_importance_true_includes_email_filters() {let expr = Expr::Literal(EmailLiteral::Importance(true));- let result = build_message_email_filter(&expr);+ let result = build_message_email_filter(&expr, &ResolvedFilters::empty());let debug = result.to_debug_sql();assert!(debug.contains("FROM email_filters ef"));@@ -73,7 +173,7 @@ fn test_build_message_email_filter_importance_true_includes_email_filters() {#[test]fn test_build_message_email_filter_importance_false_includes_email_filters() {let expr = Expr::Literal(EmailLiteral::Importance(false));- let result = build_message_email_filter(&expr);+ let result = build_message_email_filter(&expr, &ResolvedFilters::empty());let debug = result.to_debug_sql();assert!(debug.contains("FROM email_filters ef"));@@ -83,119 +183,100 @@ fn test_build_message_email_filter_importance_false_includes_email_filters() {}#[test]-fn test_build_message_email_filter_recipient() {- let email = Email::Complete(- EmailStr::parse_from_str("[email protected]")- .unwrap()- .into_owned(),- );- let expr = Expr::Literal(EmailLiteral::Recipient(email));- let result = build_message_email_filter(&expr);+fn test_build_message_email_filter_recipient_resolved() {+ let id = Uuid::new_v4();+ let expr = Expr::Literal(EmailLiteral::Recipient(complete("[email protected]")));+ let resolved = resolved_with(&[("[email protected]", id)]);+ let result = build_message_email_filter(&expr, &resolved);let debug = result.to_debug_sql();assert!(debug.contains("email_message_recipients"));assert!(debug.contains("recipient_type = 'TO'"));- assert!(result.has_bind_string("[email protected]"));+ assert!(debug.contains("mr.contact_id = "));+ // No email_contacts join: we already resolved the contact id.+ assert!(!debug.contains("JOIN email_contacts"));+ assert!(result.has_bind_uuid(&id));assert!(result.has_no_raw_containing("[email protected]"));}#[test]-fn test_build_message_email_filter_cc() {- let email = Email::Complete(- EmailStr::parse_from_str("[email protected]")- .unwrap()- .into_owned(),- );- let expr = Expr::Literal(EmailLiteral::Cc(email));- let result = build_message_email_filter(&expr);+fn test_build_message_email_filter_cc_resolved() {+ let id = Uuid::new_v4();+ let expr = Expr::Literal(EmailLiteral::Cc(complete("[email protected]")));+ let resolved = resolved_with(&[("[email protected]", id)]);+ let result = build_message_email_filter(&expr, &resolved);let debug = result.to_debug_sql();assert!(debug.contains("recipient_type = 'CC'"));- assert!(result.has_bind_string("[email protected]"));+ assert!(debug.contains("mr.contact_id = "));+ assert!(result.has_bind_uuid(&id));assert!(result.has_no_raw_containing("[email protected]"));}#[test]-fn test_build_message_email_filter_bcc() {- let email = Email::Complete(- EmailStr::parse_from_str("[email protected]")- .unwrap()- .into_owned(),- );- let expr = Expr::Literal(EmailLiteral::Bcc(email));- let result = build_message_email_filter(&expr);+fn test_build_message_email_filter_bcc_resolved() {+ let id = Uuid::new_v4();+ let expr = Expr::Literal(EmailLiteral::Bcc(complete("[email protected]")));+ let resolved = resolved_with(&[("[email protected]", id)]);+ let result = build_message_email_filter(&expr, &resolved);let debug = result.to_debug_sql();assert!(debug.contains("recipient_type = 'BCC'"));- assert!(result.has_bind_string("[email protected]"));+ assert!(debug.contains("mr.contact_id = "));+ assert!(result.has_bind_uuid(&id));assert!(result.has_no_raw_containing("[email protected]"));}#[test]fn test_build_message_email_filter_and() {- let email1 = Email::Complete(- EmailStr::parse_from_str("[email protected]")- .unwrap()- .into_owned(),- );- let email2 = Email::Complete(- EmailStr::parse_from_str("[email protected]")- .unwrap()- .into_owned(),- );+ let id1 = Uuid::new_v4();+ let id2 = Uuid::new_v4();let expr = Expr::and(- Expr::Literal(EmailLiteral::Sender(email1)),- Expr::Literal(EmailLiteral::Recipient(email2)),+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),+ Expr::Literal(EmailLiteral::Recipient(complete("[email protected]"))),);- let result = build_message_email_filter(&expr);+ let resolved = resolved_with(&[("[email protected]", id1), ("[email protected]", id2)]);+ let result = build_message_email_filter(&expr, &resolved);let debug = result.to_debug_sql();assert!(debug.contains("AND"));- assert!(result.has_bind_string("[email protected]"));- assert!(result.has_bind_string("[email protected]"));+ assert!(result.has_bind_uuid(&id1));+ assert!(result.has_bind_uuid(&id2));assert!(result.has_no_raw_containing("[email protected]"));assert!(result.has_no_raw_containing("[email protected]"));}#[test]fn test_build_message_email_filter_or() {- let email1 = Email::Complete(- EmailStr::parse_from_str("[email protected]")- .unwrap()- .into_owned(),- );- let email2 = Email::Complete(- EmailStr::parse_from_str("[email protected]")- .unwrap()- .into_owned(),- );+ let id1 = Uuid::new_v4();+ let id2 = Uuid::new_v4();let expr = Expr::or(- Expr::Literal(EmailLiteral::Sender(email1)),- Expr::Literal(EmailLiteral::Sender(email2)),+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),);- let result = build_message_email_filter(&expr);+ let resolved = resolved_with(&[("[email protected]", id1), ("[email protected]", id2)]);+ let result = build_message_email_filter(&expr, &resolved);let debug = result.to_debug_sql();assert!(debug.contains("OR"));- assert!(result.has_bind_string("[email protected]"));- assert!(result.has_bind_string("[email protected]"));+ assert!(result.has_bind_uuid(&id1));+ assert!(result.has_bind_uuid(&id2));assert!(result.has_no_raw_containing("[email protected]"));assert!(result.has_no_raw_containing("[email protected]"));}#[test]fn test_build_message_email_filter_not() {- let email = Email::Complete(- EmailStr::parse_from_str("[email protected]")- .unwrap()- .into_owned(),- );- let expr = Expr::is_not(Expr::Literal(EmailLiteral::Sender(email)));- let result = build_message_email_filter(&expr);+ let id = Uuid::new_v4();+ let expr = Expr::is_not(Expr::Literal(EmailLiteral::Sender(complete(+ "[email protected]",+ ))));+ let resolved = resolved_with(&[("[email protected]", id)]);+ let result = build_message_email_filter(&expr, &resolved);let debug = result.to_debug_sql();assert!(debug.contains("NOT"));- assert!(result.has_bind_string("[email protected]"));+ assert!(result.has_bind_uuid(&id));assert!(result.has_no_raw_containing("[email protected]"));}@@ -357,12 +438,7 @@ fn test_build_thread_email_filter_multiple_thread_ids() {#[test]fn test_build_thread_email_filter_maps_sender_to_true() {- let email = Email::Complete(- EmailStr::parse_from_str("[email protected]")- .unwrap()- .into_owned(),- );- let expr = Expr::Literal(EmailLiteral::Sender(email));+ let expr = Expr::Literal(EmailLiteral::Sender(complete("[email protected]")));let result = build_thread_email_filter(&expr);let debug = result.to_debug_sql();@@ -374,7 +450,7 @@ fn test_build_thread_email_filter_maps_sender_to_true() {fn test_build_message_email_filter_maps_thread_id_to_true() {let id = Uuid::new_v4();let expr = Expr::Literal(EmailLiteral::ThreadId(id));- let result = build_message_email_filter(&expr);+ let result = build_message_email_filter(&expr, &ResolvedFilters::empty());let debug = result.to_debug_sql();assert!(debug.contains("TRUE"));@@ -384,14 +460,10 @@ fn test_build_message_email_filter_maps_thread_id_to_true() {#[test]fn test_combined_thread_id_and_sender_splits_correctly() {let id = Uuid::new_v4();- let email = Email::Complete(- EmailStr::parse_from_str("[email protected]")- .unwrap()- .into_owned(),- );+ let contact_id = Uuid::new_v4();let expr = Expr::and(Expr::Literal(EmailLiteral::ThreadId(id)),- Expr::Literal(EmailLiteral::Sender(email)),+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),);let thread_result = build_thread_email_filter(&expr);@@ -399,11 +471,11 @@ fn test_combined_thread_id_and_sender_splits_correctly() {assert!(thread_result.has_bind_uuid(&id));assert!(!thread_debug.contains("from_contact_id"));- let message_result = build_message_email_filter(&expr);+ let resolved = resolved_with(&[("[email protected]", contact_id)]);+ let message_result = build_message_email_filter(&expr, &resolved);let message_debug = message_result.to_debug_sql();assert!(message_debug.contains("from_contact_id"));- assert!(message_result.has_bind_string("[email protected]"));- assert!(!message_result.has_bind_uuid(&id));+ assert!(message_result.has_bind_uuid(&contact_id));}#[test]@@ -415,23 +487,13 @@ fn test_has_thread_literals_true_when_thread_id_present() {#[test]fn test_has_thread_literals_false_when_only_message_literals() {- let email = Email::Complete(- EmailStr::parse_from_str("[email protected]")- .unwrap()- .into_owned(),- );- let expr = Expr::Literal(EmailLiteral::Sender(email));+ let expr = Expr::Literal(EmailLiteral::Sender(complete("[email protected]")));assert!(!has_thread_literals(&expr));}#[test]fn test_has_message_literals_true_when_sender_present() {- let email = Email::Complete(- EmailStr::parse_from_str("[email protected]")- .unwrap()- .into_owned(),- );- let expr = Expr::Literal(EmailLiteral::Sender(email));+ let expr = Expr::Literal(EmailLiteral::Sender(complete("[email protected]")));assert!(has_message_literals(&expr));}@@ -445,14 +507,9 @@ fn test_has_message_literals_false_when_only_thread_id() {#[test]fn test_has_both_literals_in_combined_ast() {let id = Uuid::new_v4();- let email = Email::Complete(- EmailStr::parse_from_str("[email protected]")- .unwrap()- .into_owned(),- );let expr = Expr::and(Expr::Literal(EmailLiteral::ThreadId(id)),- Expr::Literal(EmailLiteral::Sender(email)),+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),);assert!(has_thread_literals(&expr));assert!(has_message_literals(&expr));@@ -488,7 +545,7 @@ fn test_build_thread_email_filter_multiple_project_ids() {#[test]fn test_build_message_email_filter_maps_project_id_to_true() {let expr = Expr::Literal(EmailLiteral::ProjectId("project-123".to_string()));- let result = build_message_email_filter(&expr);+ let result = build_message_email_filter(&expr, &ResolvedFilters::empty());let debug = result.to_debug_sql();assert!(debug.contains("TRUE"));@@ -509,14 +566,10 @@ fn test_has_message_literals_false_when_only_project_id() {#[test]fn test_combined_project_id_and_sender_splits_correctly() {- let email = Email::Complete(- EmailStr::parse_from_str("[email protected]")- .unwrap()- .into_owned(),- );+ let contact_id = Uuid::new_v4();let expr = Expr::and(Expr::Literal(EmailLiteral::ProjectId("project-123".to_string())),- Expr::Literal(EmailLiteral::Sender(email)),+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),);let thread_result = build_thread_email_filter(&expr);@@ -525,10 +578,11 @@ fn test_combined_project_id_and_sender_splits_correctly() {assert!(thread_result.has_bind_string("project-123"));assert!(!thread_debug.contains("from_contact_id"));- let message_result = build_message_email_filter(&expr);+ let resolved = resolved_with(&[("[email protected]", contact_id)]);+ let message_result = build_message_email_filter(&expr, &resolved);let message_debug = message_result.to_debug_sql();assert!(message_debug.contains("from_contact_id"));- assert!(message_result.has_bind_string("[email protected]"));+ assert!(message_result.has_bind_uuid(&contact_id));assert!(!message_result.has_bind_string("project-123"));}@@ -544,11 +598,15 @@ fn test_sql_injection_project_id_not_in_raw_sql() {#[test]fn test_sql_injection_email_not_in_raw_sql() {- let malicious = Email::Complete(EmailStr::parse_from_str("[email protected]").unwrap().into_owned());- let expr = Expr::Literal(EmailLiteral::Sender(malicious));- let result = build_message_email_filter(&expr);+ // Resolved Complete emails: the address is replaced by a uuid bind, so+ // the raw SQL never contains the email at all. Verify the email string+ // is absent from raw SQL — that's the property we care about.+ let id = Uuid::new_v4();+ let expr = Expr::Literal(EmailLiteral::Sender(complete("[email protected]")));+ let resolved = resolved_with(&[("[email protected]", id)]);+ let result = build_message_email_filter(&expr, &resolved);- assert!(result.has_bind_string("[email protected]"));+ assert!(result.has_bind_uuid(&id));assert!(result.has_no_raw_containing("[email protected]"));}@@ -557,7 +615,7 @@ fn test_sql_injection_partial_email_not_in_raw_sql() {let expr = Expr::Literal(EmailLiteral::Sender(Email::Partial("'; DROP TABLE--".to_string(),)));- let result = build_message_email_filter(&expr);+ let result = build_message_email_filter(&expr, &ResolvedFilters::empty());assert!(result.has_no_raw_containing("DROP"));assert!(result.has_no_raw_containing("';"));@@ -583,6 +641,204 @@ fn test_sql_injection_thread_id_not_in_raw_sql() {assert!(result.has_no_raw_containing(&id.to_string()));}+#[test]+fn test_build_thread_address_filter_emits_in_cte_reference() {+ // The candidate WHERE just references the materialized CTE by name —+ // the actual matching set is built once in `matching_threads AS+ // MATERIALIZED (...)` at the top of the query.+ let expr = Expr::Literal(EmailLiteral::Sender(complete("[email protected]")));+ let result = build_thread_address_filter(&expr);+ let debug = result.to_debug_sql();++ assert!(debug.contains("t.id IN (SELECT thread_id FROM matching_threads)"));+ // No address-resolution details leak into the candidate WHERE itself.+ assert!(!debug.contains("from_contact_id"));+ assert!(!debug.contains("email_messages"));+}++#[test]+fn test_build_thread_address_filter_empty_when_no_address_literals() {+ let id = Uuid::new_v4();+ let expr = Expr::Literal(EmailLiteral::ThreadId(id));+ let result = build_thread_address_filter(&expr);+ assert!(result.is_empty());+}++#[test]+fn test_build_thread_address_filter_skips_mixed_or_to_avoid_false_negatives() {+ // `Sender(X) OR Importance(true)` cannot be safely reduced to `Sender(X)`+ // at the candidate stage — a thread matching only Importance would be+ // wrongly excluded. Expect no pushdown.+ let expr = Expr::or(+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),+ Expr::Literal(EmailLiteral::Importance(true)),+ );+ let result = build_thread_address_filter(&expr);+ assert!(result.is_empty());+}++#[test]+fn test_matching_threads_cte_body_single_sender_uses_union_form() {+ let id = Uuid::new_v4();+ let expr = Expr::Literal(EmailLiteral::Sender(complete("[email protected]")));+ let resolved = resolved_with(&[("[email protected]", id)]);+ let body = build_matching_threads_cte_body(&expr, &resolved).expect("body present");+ let debug = body.to_debug_sql();++ // Single sender: one UNION branch (no UNION keyword needed), index probe+ // on idx_email_messages_from_contact_id.+ assert!(debug.contains("SELECT m.thread_id FROM email_messages m"));+ assert!(debug.contains("m.from_contact_id = "));+ assert!(!debug.contains("UNION"));+ assert!(!debug.contains("LOWER(c.email_address)"));+ assert!(body.has_bind_uuid(&id));+}++#[test]+fn test_matching_threads_cte_body_or_of_kinds_emits_one_union_branch_per_literal() {+ // Sender OR Cc OR Bcc OR Recipient over the same email — the common+ // "filter by this address in any role" case. Each leaf becomes its own+ // index-driven UNION branch instead of a single OR-laden subquery.+ let id = Uuid::new_v4();+ let expr = Expr::or(+ Expr::or(+ Expr::or(+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),+ Expr::Literal(EmailLiteral::Cc(complete("[email protected]"))),+ ),+ Expr::Literal(EmailLiteral::Bcc(complete("[email protected]"))),+ ),+ Expr::Literal(EmailLiteral::Recipient(complete("[email protected]"))),+ );+ let resolved = resolved_with(&[("[email protected]", id)]);+ let body = build_matching_threads_cte_body(&expr, &resolved).expect("body present");+ let debug = body.to_debug_sql();++ // Three UNIONs join the four branches.+ assert_eq!(debug.matches("UNION").count(), 3);+ assert!(debug.contains("recipient_type = 'TO'"));+ assert!(debug.contains("recipient_type = 'CC'"));+ assert!(debug.contains("recipient_type = 'BCC'"));+ assert!(debug.contains("m.from_contact_id = "));+ assert!(body.has_bind_uuid(&id));+ // No correlated `m.thread_id = t.id` — uncorrelated branches.+ assert!(!debug.contains("m.thread_id = t.id"));+}++#[test]+fn test_matching_threads_cte_body_skips_unresolved_complete_branches() {+ // Sender(known) OR Sender(missing) — drops the missing branch from the+ // UNION rather than emitting a `WHERE FALSE` branch.+ let id = Uuid::new_v4();+ let expr = Expr::or(+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),+ );+ let resolved = resolved_with(&[("[email protected]", id)]);+ let body = build_matching_threads_cte_body(&expr, &resolved).expect("body present");+ let debug = body.to_debug_sql();++ // Only one branch left → no UNION keyword.+ assert!(!debug.contains("UNION"));+ assert!(debug.contains("m.from_contact_id = "));+ assert!(body.has_bind_uuid(&id));+}++#[test]+fn test_matching_threads_cte_body_partial_emits_ilike_branch_with_email_contacts_join() {+ let expr = Expr::Literal(EmailLiteral::Sender(Email::Partial("acme".into())));+ let body =+ build_matching_threads_cte_body(&expr, &ResolvedFilters::empty()).expect("body present");+ let debug = body.to_debug_sql();++ assert!(debug.contains("FROM email_contacts c"));+ assert!(debug.contains("ILIKE"));+ assert!(body.has_bind_string("%acme%"));+}++#[test]+fn test_matching_threads_cte_body_and_of_conjuncts_uses_combined_predicate_form() {+ // `Sender(X) AND Recipient(Y)` requires single-message semantics —+ // can't UNION the two (would change AND to OR). Expect a single+ // SELECT DISTINCT subquery whose WHERE ANDs both predicates.+ let sender_id = Uuid::new_v4();+ let recipient_id = Uuid::new_v4();+ let expr = Expr::and(+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),+ Expr::Literal(EmailLiteral::Recipient(complete("[email protected]"))),+ );+ let resolved = resolved_with(&[("[email protected]", sender_id), ("[email protected]", recipient_id)]);+ let body = build_matching_threads_cte_body(&expr, &resolved).expect("body present");+ let debug = body.to_debug_sql();++ assert!(debug.contains("SELECT DISTINCT m.thread_id"));+ assert!(!debug.contains("UNION"));+ // Both literals appear inside the combined predicate.+ assert!(body.has_bind_uuid(&sender_id));+ assert!(body.has_bind_uuid(&recipient_id));+ // Importance / NOT/AND patterns aren't extracted into this body.+ assert!(!debug.contains("ef.is_important"));+}++#[test]+fn test_matching_threads_cte_body_uses_resolved_trash_label_id() {+ // With a resolved trash label, the per-branch TRASH check is a direct+ // ml.label_id probe rather than a name+link_id join.+ let contact_id = Uuid::new_v4();+ let trash_id = Uuid::new_v4();+ let expr = Expr::Literal(EmailLiteral::Sender(complete("[email protected]")));+ let resolved = ResolvedFilters::empty()+ .with_contact("[email protected]", contact_id)+ .with_trash(trash_id);+ let body = build_matching_threads_cte_body(&expr, &resolved).expect("body present");+ let debug = body.to_debug_sql();++ assert!(debug.contains("ml.label_id = "));+ assert!(!debug.contains("l.name = 'TRASH'"));+ assert!(!debug.contains("JOIN email_labels"));+ assert!(body.has_bind_uuid(&trash_id));+}++#[test]+fn test_matching_threads_cte_body_none_when_no_address_literals() {+ let id = Uuid::new_v4();+ let expr = Expr::Literal(EmailLiteral::ThreadId(id));+ let body = build_matching_threads_cte_body(&expr, &ResolvedFilters::empty());+ assert!(body.is_none());+}++#[test]+fn test_full_query_emits_matching_threads_cte_and_in_reference() {+ // End-to-end: the full SQL contains both the materialized CTE+ // definition and the candidate WHERE reference to it. The candidate+ // WHERE no longer contains an inline matching subquery.+ let contact_id = Uuid::new_v4();+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);+ let expr = Expr::Literal(EmailLiteral::Sender(complete("[email protected]")));+ let resolved = ResolvedFilters::empty()+ .with_contact("[email protected]", contact_id)+ .with_trash(Uuid::new_v4());+ let sql = super::query::debug_build_query_sql_with_resolved(&view, &expr, resolved);++ assert!(+ sql.contains("matching_threads AS MATERIALIZED ("),+ "MATERIALIZED CTE missing: {sql}"+ );+ assert!(+ sql.contains("t.id IN (SELECT thread_id FROM matching_threads)"),+ "candidate WHERE doesn't reference the CTE: {sql}"+ );+ // No inline EXISTS or correlated subquery remains in the candidate WHERE.+ let candidate_end = sql+ .find("ORDER BY effective_ts DESC, id DESC")+ .expect("candidate ORDER BY missing");+ let candidate_section = &sql[..candidate_end];+ assert!(+ !candidate_section.contains("m.thread_id = t.id"),+ "stale correlated subquery still present in candidate: {sql}",+ );+}+#[test]fn test_build_thread_email_filter_calendar_only_true_emits_ics_exists() {let expr = Expr::Literal(EmailLiteral::CalendarOnly(true));@@ -610,7 +866,7 @@ fn test_build_thread_email_filter_calendar_only_false_maps_to_true() {#[test]fn test_build_message_email_filter_maps_calendar_only_to_true() {let expr = Expr::Literal(EmailLiteral::CalendarOnly(true));- let result = build_message_email_filter(&expr);+ let result = build_message_email_filter(&expr, &ResolvedFilters::empty());let debug = result.to_debug_sql();assert!(debug.contains("TRUE"));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 89ba74ca81..38f6871c91 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@@ -1652,3 +1652,161 @@ async fn test_shared_only_returns_correct_owner_id(pool: Pool<Postgres>) -> anyhOk(())}++// Filtering by a Complete email that has no contact in `email_contacts`+// for this link must short-circuit to an empty result set without+// running the main query. This is what `resolve_filters` ++// `can_short_circuit` are for: the AST `Sender(Complete(missing))`+// folds to FALSE and the entry point returns `Vec::new()`.+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))+)]+async fn test_dynamic_query_short_circuits_on_unresolved_complete_email(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);+ let limit = 50;++ // No contact with this email exists in the fixture.+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Complete(+ EmailStr::parse_from_str("[email protected]")?.into_owned(),+ ))));+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);++ let results =+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;++ assert!(+ results.is_empty(),+ "filtering by an unresolved Complete email must short-circuit to no results, got {} threads",+ results.len()+ );++ Ok(())+}++// Filtering by `Bcc(bob)` must return thread 4: the edge-cases fixture+// adds bob as a BCC recipient on message 4. Exercises the BCC arm of+// `build_address_predicate_on_m` and the Bcc UNION branch in+// `build_matching_threads_cte_body`. Without this test, no SQL-level+// path covers BCC.+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query", "email_dynamic_query_address_edge_cases")+ )+)]+async fn test_dynamic_query_with_bcc_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);+ let limit = 50;++ let email_filter = Arc::new(Expr::Literal(EmailLiteral::Bcc(Email::Complete(+ EmailStr::parse_from_str("[email protected]")?.into_owned(),+ ))));+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);++ let results =+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;++ let result_ids: std::collections::HashSet<String> =+ results.iter().map(|r| r.id.to_string()).collect();++ assert!(+ result_ids.contains("20000004-0000-0000-0000-000000000004"),+ "Bcc(bob) should match thread 4 (bob is BCC on message 4); got {:?}",+ result_ids+ );+ // Thread 7 has bob as CC, not BCC — it must NOT match a Bcc filter.+ assert!(+ !result_ids.contains("20000007-0000-0000-0000-000000000007"),+ "Bcc(bob) must not match thread 7 (bob is CC there, not BCC); got {:?}",+ result_ids+ );++ Ok(())+}++// `Sender(john) AND Recipient(alice)` must match using *single-message*+// semantics: the thread is included iff some single message satisfies+// both conjuncts. Thread 12 (split between msg12a john→bob and msg12b+// bob→alice) has john-as-sender on one message AND alice-as-recipient on+// a *different* message — neither message individually satisfies both,+// so the thread must be excluded. The same filter must still match+// thread 1 (msg1: john→alice) where a single message does satisfy both.+//+// Sanity check: filtering by `Sender(john)` alone must include thread 12,+// proving the fixture is wired correctly and the exclusion above is+// driven by single-message semantics rather than a missing fixture row.+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query", "email_dynamic_query_address_edge_cases")+ )+)]+async fn test_dynamic_query_and_filter_uses_single_message_semantics(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);+ let limit = 50;++ // Sanity: Sender(john) alone matches the split thread (msg12a is from+ // john) — so the fixture is wired up and john has at least one+ // message on thread 12.+ {+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Complete(+ EmailStr::parse_from_str("[email protected]")?.into_owned(),+ ))));+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);+ let results =+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ let ids: std::collections::HashSet<String> =+ results.iter().map(|r| r.id.to_string()).collect();+ assert!(+ ids.contains("20000012-0000-0000-0000-000000000012"),+ "fixture sanity: Sender(john) should include thread 12 (msg12a is from john); got {:?}",+ ids+ );+ }++ // The actual assertion: AND-of-conjuncts is single-message-scoped.+ let filter = Arc::new(Expr::and(+ Expr::Literal(EmailLiteral::Sender(Email::Complete(+ EmailStr::parse_from_str("[email protected]")?.into_owned(),+ ))),+ Expr::Literal(EmailLiteral::Recipient(Email::Complete(+ EmailStr::parse_from_str("[email protected]")?.into_owned(),+ ))),+ ));+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);+ let results =+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ let ids: std::collections::HashSet<String> = results.iter().map(|r| r.id.to_string()).collect();++ assert!(+ !ids.contains("20000012-0000-0000-0000-000000000012"),+ "Sender(john) AND Recipient(alice) must NOT match thread 12: john's message and \+ alice's message are different messages on that thread, so no single message satisfies \+ both conjuncts. got: {:?}",+ ids+ );++ // And it should still match thread 1, where msg1 is john → alice on+ // a single message (the positive case, already covered by+ // `test_dynamic_query_with_and_filter` but re-asserted here so a+ // regression that drops thread 1 wouldn't be hidden by the negative+ // assertion above succeeding for the wrong reason).+ assert!(+ ids.contains("20000001-0000-0000-0000-000000000001"),+ "Sender(john) AND Recipient(alice) should still match thread 1 (msg1: john → alice); \+ got: {:?}",+ ids+ );++ Ok(())+}