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.

Seanaye/feat/push notif for signal email (#3040)

Sean Aye82618095b9de
diff --git a/js/app/packages/notifications/notification-platform.ts b/js/app/packages/notifications/notification-platform.ts
index d51366b7c2..fb081832f0 100644
--- a/js/app/packages/notifications/notification-platform.ts
+++ b/js/app/packages/notifications/notification-platform.ts
@@ -81,10 +81,7 @@ export async function maybeHandlePlatformNotification(
splitLayoutManager: SplitManager
) {
// Ignore notification types that should not show as browser notifications
- if (
- notification.notification_metadata.tag === 'document_mention' ||
- notification.notification_metadata.tag === 'new_email'
- ) {
+ if (notification.notification_metadata.tag === 'document_mention') {
return;
}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 45809c3ce0..6b7e6df36f 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3656,6 +3656,7 @@ dependencies = [
"chrono",
"doppleganger",
"either",
+ "email_importance",
"email_utils",
"entity_access",
"filter_ast",
@@ -3727,6 +3728,18 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "email_importance"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "macro_db_migrator",
+ "sqlx",
+ "tokio",
+ "tracing",
+ "uuid",
+]
+
[[package]]
name = "email_refresh_handler"
version = "0.1.0"
@@ -3794,6 +3807,7 @@ dependencies = [
"ego-tree",
"email",
"email_db_client",
+ "email_importance",
"email_utils",
"entity_access",
"frecency",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 3ca37d8ce1..ac1f4ca556 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -39,6 +39,7 @@ members = [
"docx_unzip_handler",
"dynamodb_client",
"email_db_client",
+ "email_importance",
"email_refresh_handler",
"email_scheduled_handler",
"email_service",
diff --git a/rust/cloud-storage/email/Cargo.toml b/rust/cloud-storage/email/Cargo.toml
index 2f57d2f12c..f8440ca3e1 100644
--- a/rust/cloud-storage/email/Cargo.toml
+++ b/rust/cloud-storage/email/Cargo.toml
@@ -51,6 +51,7 @@ axum-extra = { workspace = true, optional = true }
chrono = { workspace = true, features = ["serde"] }
doppleganger = { workspace = true, features = ["chrono", "uuid"] }
either = { workspace = true }
+email_importance = { path = "../email_importance" }
email_utils = { path = "../email_utils" }
filter_ast = { path = "../filter_ast" }
frecency = { path = "../frecency" }
@@ -79,6 +80,7 @@ utoipa = { workspace = true, optional = true }
uuid = { workspace = true }
[dev-dependencies]
+email_importance = { path = "../email_importance" }
frecency = { path = "../frecency", features = ["outbound", "postgres"] }
macro_db_migrator = { path = "../macro_db_migrator" }
serde_json = { workspace = true }
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.rs
index 29a097dbc9..57640f0744 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,5 +1,6 @@
use super::SqlFragment;
use crate::domain::models::{PreviewView, PreviewViewStandardLabel};
+use email_importance::build_importance_condition;
use filter_ast::Expr;
use item_filters::ast::email::{Email, EmailLiteral};
use recursion::CollapsibleExt;
@@ -56,44 +57,6 @@ fn build_email_match(preamble: &str, email: &Email) -> SqlFragment {
}
}
-fn build_sender_importance_override_filter(is_important: bool) -> SqlFragment {
- let importance_literal = if is_important { "TRUE" } else { "FALSE" };
- let opposite_importance_literal = if is_important { "FALSE" } else { "TRUE" };
-
- SqlFragment::raw(format!(
- r#"(
- EXISTS (
- SELECT 1
- FROM email_contacts sender_c
- JOIN email_filters ef
- ON ef.link_id = m.link_id
- AND ef.email_address IS NOT NULL
- AND LOWER(ef.email_address) = LOWER(sender_c.email_address)
- WHERE sender_c.id = m.from_contact_id
- AND ef.is_important = {importance_literal}
- )
- OR EXISTS (
- SELECT 1
- FROM email_contacts sender_c
- JOIN email_filters ef
- ON ef.link_id = m.link_id
- AND ef.email_domain IS NOT NULL
- AND LOWER(ef.email_domain) = LOWER(split_part(sender_c.email_address, '@', 2))
- WHERE sender_c.id = m.from_contact_id
- AND ef.is_important = {importance_literal}
- AND NOT EXISTS (
- SELECT 1
- FROM email_filters ef_addr
- WHERE ef_addr.link_id = m.link_id
- AND ef_addr.email_address IS NOT NULL
- AND LOWER(ef_addr.email_address) = LOWER(sender_c.email_address)
- AND ef_addr.is_important = {opposite_importance_literal}
- )
- )
- )"#,
- ))
-}
-
pub(super) fn build_message_email_filter(ast: &Expr<EmailLiteral>) -> SqlFragment {
let fragment = ast.collapse_frames(|frame| match frame {
filter_ast::ExprFrame::And(a, b) => SqlFragment::and(a, b),
@@ -139,77 +102,17 @@ pub(super) fn build_message_email_filter(ast: &Expr<EmailLiteral>) -> SqlFragmen
),
filter_ast::ExprFrame::Literal(EmailLiteral::Importance(true)) => {
- let mut f = SqlFragment::raw(
- r#"(
- 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 (
- "#,
- );
- f.extend(build_sender_importance_override_filter(true));
- f.push_raw(
- r#"
- OR (
- NOT "#,
- );
- f.extend(build_sender_importance_override_filter(false));
- f.push_raw(
- r#"
- AND (
- m.is_draft = TRUE
- OR 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 IN ('CATEGORY_PERSONAL', 'SENT', 'DRAFT')
- )
- OR 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 IN ('CATEGORY_UPDATES', 'CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')
- )
- )
- )
- )
- )"#,
+ let mut builder = sqlx::QueryBuilder::new(
+ "(\n NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id\n AND l.name = 'TRASH'\n )\n AND ",
);
- f
+ build_importance_condition(true, &mut builder);
+ builder.push(")");
+ SqlFragment::raw(builder.sql())
}
filter_ast::ExprFrame::Literal(EmailLiteral::Importance(false)) => {
- let mut f = SqlFragment::raw(
- r#"(
- "#,
- );
- f.extend(build_sender_importance_override_filter(false));
- f.push_raw(
- r#"
- OR (
- NOT "#,
- );
- f.extend(build_sender_importance_override_filter(true));
- f.push_raw(
- r#"
- 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 IN ('CATEGORY_PERSONAL', 'SENT', 'DRAFT')
- )
- AND 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 IN ('CATEGORY_UPDATES', 'CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')
- )
- )
- )"#,
- );
- f
+ let mut builder = sqlx::QueryBuilder::new("");
+ build_importance_condition(false, &mut builder);
+ SqlFragment::raw(builder.sql())
}
filter_ast::ExprFrame::Literal(EmailLiteral::NotificationDone(_)) => {
SqlFragment::raw("TRUE")
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 06765ece1a..d38e5aa76c 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,9 +1,11 @@
use super::*;
use crate::domain::models::{PreviewView, PreviewViewStandardLabel};
+use email_importance::build_importance_condition;
use filter_ast::Expr;
use item_filters::ast::email::{Email, EmailLiteral};
use macro_user_id::cowlike::CowLike;
use macro_user_id::email::EmailStr;
+use sqlx::{Execute, Postgres};
use uuid::Uuid;
#[test]
@@ -66,6 +68,7 @@ fn test_build_message_email_filter_importance_true_includes_email_filters() {
debug
.contains("LOWER(ef.email_domain) = LOWER(split_part(sender_c.email_address, '@', 2))")
);
+ // Boolean values are inlined as TRUE/FALSE into the raw SQL.
assert!(debug.contains("ef.is_important = TRUE"));
assert!(debug.contains("ef_addr.is_important = FALSE"));
}
@@ -628,3 +631,41 @@ fn test_has_message_literals_false_when_only_calendar_only() {
let expr = Expr::Literal(EmailLiteral::CalendarOnly(true));
assert!(!has_message_literals(&expr));
}
+
+/// Verifies that `build_message_email_filter` for `Importance(true)` embeds the exact SQL
+/// produced by `build_importance_condition(true)`. If the filter arm ever diverges from the
+/// shared condition (e.g. by inlining different SQL), this test fails.
+#[test]
+fn importance_true_filter_contains_shared_condition() {
+ let mut builder = sqlx::QueryBuilder::<Postgres>::new("");
+ build_importance_condition(true, &mut builder);
+ let condition_sql = builder.build().sql().to_owned();
+
+ let filter_sql =
+ build_message_email_filter(&Expr::Literal(EmailLiteral::Importance(true))).to_debug_sql();
+ assert!(
+ filter_sql.contains(&condition_sql),
+ "Importance(true) filter SQL does not contain build_importance_condition(true) output.\n\
+ filter: {filter_sql}\n\
+ condition: {condition_sql}"
+ );
+}
+
+/// Verifies that `build_message_email_filter` for `Importance(false)` embeds the exact SQL
+/// produced by `build_importance_condition(false)`. If the filter arm ever diverges from the
+/// shared condition, this test fails.
+#[test]
+fn importance_false_filter_contains_shared_condition() {
+ let mut builder = sqlx::QueryBuilder::<Postgres>::new("");
+ build_importance_condition(false, &mut builder);
+ let condition_sql = builder.build().sql().to_owned();
+
+ let filter_sql =
+ build_message_email_filter(&Expr::Literal(EmailLiteral::Importance(false))).to_debug_sql();
+ assert!(
+ filter_sql.contains(&condition_sql),
+ "Importance(false) filter SQL does not contain build_importance_condition(false) output.\n\
+ filter: {filter_sql}\n\
+ condition: {condition_sql}"
+ );
+}
diff --git a/rust/cloud-storage/email_importance/Cargo.toml b/rust/cloud-storage/email_importance/Cargo.toml
new file mode 100644
index 0000000000..e23e8e4a23
--- /dev/null
+++ b/rust/cloud-storage/email_importance/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+edition = "2024"
+name = "email_importance"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+anyhow = { workspace = true }
+sqlx = { workspace = true }
+tokio = { workspace = true }
+tracing = { workspace = true }
+uuid = { workspace = true }
+
+[dev-dependencies]
+macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/rust/cloud-storage/email_importance/fixtures/domain_case_insensitive.sql b/rust/cloud-storage/email_importance/fixtures/domain_case_insensitive.sql
new file mode 100644
index 0000000000..101657ed5a
--- /dev/null
+++ b/rust/cloud-storage/email_importance/fixtures/domain_case_insensitive.sql
@@ -0,0 +1,16 @@
+-- Domain matching is case-insensitive.
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NOW(), NOW());
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false, false, NOW(), NOW());
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts, has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'provider-dddddddd-dddd-dddd-dddd-dddddddddddd', false, 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NOW(), false, false, false, false, NOW(), NOW());
+
+INSERT INTO email_filters (link_id, email_address, email_domain, is_important)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', NULL, 'EXAMPLE.COM', true);
diff --git a/rust/cloud-storage/email_importance/fixtures/domain_important_false.sql b/rust/cloud-storage/email_importance/fixtures/domain_important_false.sql
new file mode 100644
index 0000000000..a8b4c29eb8
--- /dev/null
+++ b/rust/cloud-storage/email_importance/fixtures/domain_important_false.sql
@@ -0,0 +1,16 @@
+-- Domain-level override is_important=false → fragment(false) matches.
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NOW(), NOW());
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false, false, NOW(), NOW());
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts, has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'provider-dddddddd-dddd-dddd-dddd-dddddddddddd', false, 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NOW(), false, false, false, false, NOW(), NOW());
+
+INSERT INTO email_filters (link_id, email_address, email_domain, is_important)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', NULL, 'noise.com', false);
diff --git a/rust/cloud-storage/email_importance/fixtures/domain_important_true.sql b/rust/cloud-storage/email_importance/fixtures/domain_important_true.sql
new file mode 100644
index 0000000000..f2a0dbf823
--- /dev/null
+++ b/rust/cloud-storage/email_importance/fixtures/domain_important_true.sql
@@ -0,0 +1,16 @@
+-- Domain-level override is_important=true → fragment(true) matches.
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NOW(), NOW());
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false, false, NOW(), NOW());
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts, has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'provider-dddddddd-dddd-dddd-dddd-dddddddddddd', false, 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NOW(), false, false, false, false, NOW(), NOW());
+
+INSERT INTO email_filters (link_id, email_address, email_domain, is_important)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', NULL, 'important.com', true);
diff --git a/rust/cloud-storage/email_importance/fixtures/domain_suppression_scoped.sql b/rust/cloud-storage/email_importance/fixtures/domain_suppression_scoped.sql
new file mode 100644
index 0000000000..bd55a11735
--- /dev/null
+++ b/rust/cloud-storage/email_importance/fixtures/domain_suppression_scoped.sql
@@ -0,0 +1,19 @@
+-- Domain suppression is per-address: bob's email-level false does not suppress alice's domain-level true.
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NOW(), NOW());
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false, false, NOW(), NOW());
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts, has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'provider-dddddddd-dddd-dddd-dddd-dddddddddddd', false, 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NOW(), false, false, false, false, NOW(), NOW());
+
+INSERT INTO email_filters (link_id, email_address, email_domain, is_important)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', NULL, 'company.com', true);
+
+INSERT INTO email_filters (link_id, email_address, email_domain, is_important)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NULL, false);
diff --git a/rust/cloud-storage/email_importance/fixtures/email_case_insensitive.sql b/rust/cloud-storage/email_importance/fixtures/email_case_insensitive.sql
new file mode 100644
index 0000000000..6f89c5c246
--- /dev/null
+++ b/rust/cloud-storage/email_importance/fixtures/email_case_insensitive.sql
@@ -0,0 +1,16 @@
+-- Email address matching is case-insensitive.
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NOW(), NOW());
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false, false, NOW(), NOW());
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts, has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'provider-dddddddd-dddd-dddd-dddd-dddddddddddd', false, 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NOW(), false, false, false, false, NOW(), NOW());
+
+INSERT INTO email_filters (link_id, email_address, email_domain, is_important)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NULL, true);
diff --git a/rust/cloud-storage/email_importance/fixtures/email_false_overrides_domain_true.sql b/rust/cloud-storage/email_importance/fixtures/email_false_overrides_domain_true.sql
new file mode 100644
index 0000000000..c809ff36f9
--- /dev/null
+++ b/rust/cloud-storage/email_importance/fixtures/email_false_overrides_domain_true.sql
@@ -0,0 +1,19 @@
+-- Email-level false takes precedence over domain-level true, suppressing the domain match.
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NOW(), NOW());
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false, false, NOW(), NOW());
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts, has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'provider-dddddddd-dddd-dddd-dddd-dddddddddddd', false, 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NOW(), false, false, false, false, NOW(), NOW());
+
+INSERT INTO email_filters (link_id, email_address, email_domain, is_important)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NULL, false);
+
+INSERT INTO email_filters (link_id, email_address, email_domain, is_important)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', NULL, 'mixed.com', true);
diff --git a/rust/cloud-storage/email_importance/fixtures/email_important_false.sql b/rust/cloud-storage/email_importance/fixtures/email_important_false.sql
new file mode 100644
index 0000000000..3bc79a9925
--- /dev/null
+++ b/rust/cloud-storage/email_importance/fixtures/email_important_false.sql
@@ -0,0 +1,16 @@
+-- Email-level override is_important=false → fragment(false) matches.
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NOW(), NOW());
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false, false, NOW(), NOW());
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts, has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'provider-dddddddd-dddd-dddd-dddd-dddddddddddd', false, 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NOW(), false, false, false, false, NOW(), NOW());
+
+INSERT INTO email_filters (link_id, email_address, email_domain, is_important)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NULL, false);
diff --git a/rust/cloud-storage/email_importance/fixtures/email_important_true.sql b/rust/cloud-storage/email_importance/fixtures/email_important_true.sql
new file mode 100644
index 0000000000..433b8e38bc
--- /dev/null
+++ b/rust/cloud-storage/email_importance/fixtures/email_important_true.sql
@@ -0,0 +1,16 @@
+-- Email-level override is_important=true → fragment(true) matches.
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NOW(), NOW());
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false, false, NOW(), NOW());
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts, has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'provider-dddddddd-dddd-dddd-dddd-dddddddddddd', false, 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NOW(), false, false, false, false, NOW(), NOW());
+
+INSERT INTO email_filters (link_id, email_address, email_domain, is_important)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NULL, true);
diff --git a/rust/cloud-storage/email_importance/fixtures/email_true_overrides_domain_false.sql b/rust/cloud-storage/email_importance/fixtures/email_true_overrides_domain_false.sql
new file mode 100644
index 0000000000..bf73795e15
--- /dev/null
+++ b/rust/cloud-storage/email_importance/fixtures/email_true_overrides_domain_false.sql
@@ -0,0 +1,19 @@
+-- Email-level true takes precedence over domain-level false.
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NOW(), NOW());
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false, false, NOW(), NOW());
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts, has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'provider-dddddddd-dddd-dddd-dddd-dddddddddddd', false, 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NOW(), false, false, false, false, NOW(), NOW());
+
+INSERT INTO email_filters (link_id, email_address, email_domain, is_important)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NULL, true);
+
+INSERT INTO email_filters (link_id, email_address, email_domain, is_important)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', NULL, 'mixed.com', false);
diff --git a/rust/cloud-storage/email_importance/fixtures/no_filter.sql b/rust/cloud-storage/email_importance/fixtures/no_filter.sql
new file mode 100644
index 0000000000..25938b7243
--- /dev/null
+++ b/rust/cloud-storage/email_importance/fixtures/no_filter.sql
@@ -0,0 +1,13 @@
+-- No email_filters entries → neither fragment matches.
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NOW(), NOW());
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false, false, NOW(), NOW());
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts, has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'provider-dddddddd-dddd-dddd-dddd-dddddddddddd', false, 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NOW(), false, false, false, false, NOW(), NOW());
diff --git a/rust/cloud-storage/email_importance/fixtures/other_link_ignored.sql b/rust/cloud-storage/email_importance/fixtures/other_link_ignored.sql
new file mode 100644
index 0000000000..3d41476c46
--- /dev/null
+++ b/rust/cloud-storage/email_importance/fixtures/other_link_ignored.sql
@@ -0,0 +1,19 @@
+-- A filter belonging to a different link_id has no effect.
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'macro|[email protected]', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NOW(), NOW());
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false, false, NOW(), NOW());
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts, has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'provider-dddddddd-dddd-dddd-dddd-dddddddddddd', false, 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NOW(), false, false, false, false, NOW(), NOW());
+
+INSERT INTO email_filters (link_id, email_address, email_domain, is_important)
+VALUES ('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '[email protected]', NULL, true);
diff --git a/rust/cloud-storage/email_importance/fixtures/subdomain_not_matched.sql b/rust/cloud-storage/email_importance/fixtures/subdomain_not_matched.sql
new file mode 100644
index 0000000000..42c07d6a0b
--- /dev/null
+++ b/rust/cloud-storage/email_importance/fixtures/subdomain_not_matched.sql
@@ -0,0 +1,16 @@
+-- Domain matching is exact: filter for example.com must not match subdomain mail.example.com.
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NOW(), NOW());
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false, false, NOW(), NOW());
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts, has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'provider-dddddddd-dddd-dddd-dddd-dddddddddddd', false, 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NOW(), false, false, false, false, NOW(), NOW());
+
+INSERT INTO email_filters (link_id, email_address, email_domain, is_important)
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', NULL, 'example.com', true);
diff --git a/rust/cloud-storage/email_importance/src/lib.rs b/rust/cloud-storage/email_importance/src/lib.rs
new file mode 100644
index 0000000000..6920ecfaac
--- /dev/null
+++ b/rust/cloud-storage/email_importance/src/lib.rs
@@ -0,0 +1,156 @@
+#![deny(missing_docs)]
+//! Sender-importance SQL logic shared between the `email` and `email_service` crates.
+//!
+//! Business rules: email-level overrides take precedence over domain-level; a domain-level
+//! match is suppressed by an email-level override of the opposite importance.
+
+#[cfg(test)]
+mod test;
+
+use anyhow::Result;
+use sqlx::types::Uuid;
+use sqlx::{PgPool, Postgres, QueryBuilder};
+
+/// Pushes a correlated SQL subquery into `builder` that matches senders where `email_filters`
+/// has an override with the given `is_important` value for the message's `link_id`.
+///
+/// Email-level matches take precedence; domain-level matches are suppressed when an
+/// email-level override of the opposite importance exists for the same address.
+/// All table aliases (`m`, `sender_c`, `ef`, `ef_addr`) must be defined in the outer query.
+pub fn build_sender_importance_override_filter(
+ is_important: bool,
+ builder: &mut QueryBuilder<'_, Postgres>,
+) {
+ let tf = if is_important { "TRUE" } else { "FALSE" };
+ let opp = if is_important { "FALSE" } else { "TRUE" };
+ builder.push(
+ r#"(
+ EXISTS (
+ SELECT 1
+ FROM email_contacts sender_c
+ JOIN email_filters ef
+ ON ef.link_id = m.link_id
+ AND ef.email_address IS NOT NULL
+ AND LOWER(ef.email_address) = LOWER(sender_c.email_address)
+ WHERE sender_c.id = m.from_contact_id
+ AND ef.is_important = "#,
+ );
+ builder.push(tf);
+ builder.push(
+ r#"
+ )
+ OR EXISTS (
+ SELECT 1
+ FROM email_contacts sender_c
+ JOIN email_filters ef
+ ON ef.link_id = m.link_id
+ AND ef.email_domain IS NOT NULL
+ AND LOWER(ef.email_domain) = LOWER(split_part(sender_c.email_address, '@', 2))
+ WHERE sender_c.id = m.from_contact_id
+ AND ef.is_important = "#,
+ );
+ builder.push(tf);
+ builder.push(
+ r#"
+ AND NOT EXISTS (
+ SELECT 1
+ FROM email_filters ef_addr
+ WHERE ef_addr.link_id = m.link_id
+ AND ef_addr.email_address IS NOT NULL
+ AND LOWER(ef_addr.email_address) = LOWER(sender_c.email_address)
+ AND ef_addr.is_important = "#,
+ );
+ builder.push(opp);
+ builder.push(
+ r#"
+ )
+ )
+ )"#,
+ );
+}
+
+/// Pushes the inner SQL condition for an importance filter into `builder`.
+///
+/// When `is_important = true`: sender explicitly marked important, or no noise override and
+/// the message is not deprioritised by labels.
+///
+/// When `is_important = false`: sender explicitly marked as noise, or no importance override
+/// and the message carries noise-category labels but not personal/sent/draft labels.
+///
+/// All table aliases (`m`, `sender_c`, `ef`, `ef_addr`) must be in scope in the outer query.
+pub fn build_importance_condition(is_important: bool, builder: &mut QueryBuilder<'_, Postgres>) {
+ builder.push("(");
+ build_sender_importance_override_filter(is_important, builder);
+ if is_important {
+ builder.push(
+ r#" OR (
+ NOT "#,
+ );
+ build_sender_importance_override_filter(false, builder);
+ builder.push(
+ r#"
+ AND (
+ m.is_draft = TRUE
+ OR 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 IN ('CATEGORY_PERSONAL', 'SENT', 'DRAFT')
+ )
+ OR 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 IN ('CATEGORY_UPDATES', 'CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')
+ )
+ )
+ ))"#,
+ );
+ } else {
+ builder.push(
+ r#"
+ OR (
+ NOT "#,
+ );
+ build_sender_importance_override_filter(true, builder);
+ builder.push(
+ r#"
+ 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 IN ('CATEGORY_PERSONAL', 'SENT', 'DRAFT')
+ )
+ AND 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 IN ('CATEGORY_UPDATES', 'CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')
+ )
+ )
+ )"#,
+ );
+ }
+}
+
+/// Returns `true` if the message would match the `Importance(true)` filter: the sender is
+/// explicitly marked important, or the sender has no noise override and the message is not
+/// deprioritised by labels.
+///
+/// SPAM and TRASH messages are always excluded, regardless of sender overrides.
+///
+/// Uses [`build_importance_condition`] to mirror the `EmailLiteral::Importance(true)`
+/// match arm exactly.
+#[tracing::instrument(err, skip(db))]
+pub async fn is_message_important(db: &PgPool, message_id: Uuid) -> Result<bool> {
+ let mut builder: QueryBuilder<'_, Postgres> =
+ QueryBuilder::new("SELECT EXISTS(SELECT 1 FROM email_messages m WHERE m.id = ");
+ builder.push_bind(message_id);
+ builder.push(
+ " 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 IN ('SPAM', 'TRASH')) AND ",
+ );
+ build_importance_condition(true, &mut builder);
+ builder.push(")");
+ let result: bool = builder.build_query_scalar().fetch_one(db).await?;
+ Ok(result)
+}
diff --git a/rust/cloud-storage/email_importance/src/test.rs b/rust/cloud-storage/email_importance/src/test.rs
new file mode 100644
index 0000000000..0c4c302c96
--- /dev/null
+++ b/rust/cloud-storage/email_importance/src/test.rs
@@ -0,0 +1,201 @@
+use crate::{build_importance_condition, build_sender_importance_override_filter};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::types::Uuid;
+use sqlx::{Pool, Postgres, QueryBuilder};
+
+// ---------------------------------------------------------------------------
+// Shared UUIDs — match the values used in the fixture SQL scripts.
+// ---------------------------------------------------------------------------
+
+const MESSAGE_ID: Uuid = Uuid::from_bytes([
+ 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD,
+]);
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+/// Embeds `build_sender_importance_override_filter` in a real query and returns
+/// whether it matches for the given `email_messages` row.
+async fn fragment_matches(pool: &Pool<Postgres>, message_id: Uuid, is_important: bool) -> bool {
+ let mut builder =
+ QueryBuilder::new("SELECT EXISTS(SELECT 1 FROM email_messages m WHERE m.id = ");
+ builder.push_bind(message_id);
+ builder.push(" AND ");
+ build_sender_importance_override_filter(is_important, &mut builder);
+ builder.push(")");
+ builder
+ .build_query_scalar::<bool>()
+ .fetch_one(pool)
+ .await
+ .unwrap()
+}
+
+/// Asserts that `build_sender_importance_override_filter` produces the expected result.
+async fn assert_fragment_result(pool: &Pool<Postgres>, message_id: Uuid, expected: Option<bool>) {
+ let frag_true = fragment_matches(pool, message_id, true).await;
+ let frag_false = fragment_matches(pool, message_id, false).await;
+
+ match expected {
+ Some(true) => {
+ assert!(frag_true, "fragment(true) should match");
+ assert!(!frag_false, "fragment(false) should not match");
+ }
+ Some(false) => {
+ assert!(!frag_true, "fragment(true) should not match");
+ assert!(frag_false, "fragment(false) should match");
+ }
+ None => {
+ assert!(!frag_true, "fragment(true) should not match with no filter");
+ assert!(
+ !frag_false,
+ "fragment(false) should not match with no filter"
+ );
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+/// Pins the contract that `build_importance_condition` emits no bind placeholders.
+/// Callers in `filters.rs` round-trip its output through `SqlFragment::raw(qb.sql())`,
+/// which would silently drop bound values — so any future `.push_bind()` here would
+/// produce SQL with unbound `$N` at runtime.
+#[test]
+fn build_importance_condition_emits_no_binds() {
+ for is_important in [true, false] {
+ let mut qb = QueryBuilder::<Postgres>::new("");
+ build_importance_condition(is_important, &mut qb);
+ assert!(
+ !qb.sql().contains('$'),
+ "build_importance_condition({is_important}) emitted a $N placeholder; \
+ callers rely on bind-free output. SQL: {}",
+ qb.sql()
+ );
+ }
+}
+
+/// No email_filters entries → no override → both fragments are false.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../fixtures", scripts("no_filter"))
+)]
+async fn no_filter_returns_none(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ assert_fragment_result(&pool, MESSAGE_ID, None).await;
+ Ok(())
+}
+
+/// Email-level override is_important=true → fragment(true) matches.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../fixtures", scripts("email_important_true"))
+)]
+async fn email_level_important_true(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ assert_fragment_result(&pool, MESSAGE_ID, Some(true)).await;
+ Ok(())
+}
+
+/// Email-level override is_important=false → fragment(false) matches.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../fixtures", scripts("email_important_false"))
+)]
+async fn email_level_important_false(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ assert_fragment_result(&pool, MESSAGE_ID, Some(false)).await;
+ Ok(())
+}
+
+/// Domain-level override is_important=true (no email-level) → fragment(true) matches.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../fixtures", scripts("domain_important_true"))
+)]
+async fn domain_level_important_true(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ assert_fragment_result(&pool, MESSAGE_ID, Some(true)).await;
+ Ok(())
+}
+
+/// Domain-level override is_important=false (no email-level) → fragment(false) matches.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../fixtures", scripts("domain_important_false"))
+)]
+async fn domain_level_important_false(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ assert_fragment_result(&pool, MESSAGE_ID, Some(false)).await;
+ Ok(())
+}
+
+/// Email-level true takes precedence over domain-level false.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../fixtures", scripts("email_true_overrides_domain_false"))
+)]
+async fn email_true_overrides_domain_false(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ assert_fragment_result(&pool, MESSAGE_ID, Some(true)).await;
+ Ok(())
+}
+
+/// Email-level false takes precedence over domain-level true, and suppresses the domain match.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../fixtures", scripts("email_false_overrides_domain_true"))
+)]
+async fn email_false_overrides_domain_true(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ assert_fragment_result(&pool, MESSAGE_ID, Some(false)).await;
+ Ok(())
+}
+
+/// Email address matching is case-insensitive: filter stored in uppercase still matches
+/// a lowercase contact address.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../fixtures", scripts("email_case_insensitive"))
+)]
+async fn email_level_case_insensitive(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ assert_fragment_result(&pool, MESSAGE_ID, Some(true)).await;
+ Ok(())
+}
+
+/// Domain matching is case-insensitive: filter stored with uppercase domain still matches.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../fixtures", scripts("domain_case_insensitive"))
+)]
+async fn domain_level_case_insensitive(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ assert_fragment_result(&pool, MESSAGE_ID, Some(true)).await;
+ Ok(())
+}
+
+/// A filter belonging to a different link_id has no effect on the result.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../fixtures", scripts("other_link_ignored"))
+)]
+async fn filter_for_other_link_is_ignored(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ assert_fragment_result(&pool, MESSAGE_ID, None).await;
+ Ok(())
+}
+
+/// Domain suppression is per-address: a different sender at the same domain having an
+/// email-level override of the opposite importance must NOT suppress our sender's domain match.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../fixtures", scripts("domain_suppression_scoped"))
+)]
+async fn domain_suppression_scoped_to_sender_address(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ assert_fragment_result(&pool, MESSAGE_ID, Some(true)).await;
+ Ok(())
+}
+
+/// Domain matching is exact, not suffix-based: a filter for `example.com` must not match
+/// a sender whose domain is `mail.example.com`.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../fixtures", scripts("subdomain_not_matched"))
+)]
+async fn subdomain_does_not_match_parent_domain_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ assert_fragment_result(&pool, MESSAGE_ID, None).await;
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index e27ccaa113..2453ede025 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -85,6 +85,7 @@ ego-tree = { workspace = true }
email = { path = "../email", features = ["axum", "gmail_token", "inbound", "outbound"] }
entity_access = { path = "../entity_access", default-features = false, features = ["outbound"] }
email_db_client = { path = "../email_db_client" }
+email_importance = { path = "../email_importance" }
email_utils = { path = "../email_utils" }
frecency = { path = "../frecency", features = ["postgres"] }
futures = { workspace = true }
diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs
index f00ba06c12..a310fba86b 100644
--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs
@@ -1,5 +1,3 @@
-use contacts::domain::ports::ContactsIngress;
-
use crate::convert::{map_message_resource_to_service, map_thread_resources_to_service};
use crate::pubsub::context::PubSubContext;
use crate::pubsub::inbox_sync::operations::shared::notify_search;
@@ -8,13 +6,13 @@ use crate::pubsub::inbox_sync::process::check_gmail_rate_limit_inbox_sync;
use crate::pubsub::util::cg_refresh_email;
use crate::util::process_pre_insert::{process_message_pre_insert, process_threads_pre_insert};
use crate::util::upload_attachment::{UploadAttachmentContext, upload_attachment};
+use contacts::domain::ports::ContactsIngress;
use email_db_client::threads;
use email_utils::dedupe_emails;
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::EntityType;
use model_notifications::NewEmailMetadata;
use models_email::db::address::EmailRecipientType;
-use models_email::email::service;
use models_email::email::service::link;
use models_email::email::service::message::SimpleMessage;
use models_email::gmail::inbox_sync::{InboxSyncOperation, UpsertMessagePayload};
@@ -540,6 +538,7 @@ async fn send_notifications(
recipient_ids: HashSet::from([recipient]),
}
.into_request()
+ .with_apns()
.with_conn_gateway();
if let Err(e) = ctx
@@ -578,28 +577,20 @@ async fn filter_notifiable_message(
return Ok(None);
};
- // 1. filter out sent and draft messages
+ // 1. Sent and draft messages never generate notifications.
if new_message.is_sent || new_message.is_draft {
return Ok(None);
}
- // 2. filter out messages that don't make it to the user's inbox (spam, etc)
- let labels = email_db_client::labels::get::fetch_message_labels(&ctx.db, new_message.db_id)
+ // 2. Single query mirroring Importance(true): sender override or label-based signal.
+ let important = email_importance::is_message_important(&ctx.db, new_message.db_id)
.await
.map_err(|e| {
ProcessingError::Retryable(DetailedError {
reason: FailureReason::DatabaseQueryFailed,
- source: e.context("Failed to fetch message labels".to_string()),
+ source: e.context("Failed to evaluate message importance".to_string()),
})
})?;
- let is_inbox = labels
- .iter()
- .any(|label| label.name == service::label::system_labels::INBOX);
-
- if !is_inbox {
- return Ok(None);
- }
-
- Ok(Some(new_message))
+ Ok(important.then_some(new_message))
}
diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfile
index c9ab5aa114..7d50eb6dd7 100644
--- a/rust/cloud-storage/justfile
+++ b/rust/cloud-storage/justfile
@@ -96,6 +96,7 @@ setup_test_envs:
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./entity_access_management/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./mobile_welcome_email_db_client/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./entity_access_db_utils/.env
+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./email_importance/.env
setup_macrodb:
just macro_db_client/create_db
diff --git a/rust/cloud-storage/model_notifications/src/metadata.rs b/rust/cloud-storage/model_notifications/src/metadata.rs
index 5fc964fd42..a88c796c60 100644
--- a/rust/cloud-storage/model_notifications/src/metadata.rs
+++ b/rust/cloud-storage/model_notifications/src/metadata.rs
@@ -222,6 +222,23 @@ impl NotificationTitle for NewEmailMetadata {
}
}
+impl NotificationExtIos for NewEmailMetadata {
+ type NotifData = ::notification::domain::models::apple::PushNotificationData;
+
+ fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {
+ NotifCollapseKey::new(&self.thread_id)
+ }
+
+ fn as_apns<'a>(
+ &self,
+ sender_id: Option<MacroUserIdStr<'a>>,
+ _entity: &Entity<'_>,
+ notification_id: Uuid,
+ ) -> Option<APNSPushNotification<Self::NotifData>> {
+ alert_apns(self, sender_id, notification_id, None).ok()
+ }
+}
+
impl notification::domain::models::Notification for AiResponseMetadata {
const TYPE_NAME: &'static str = "ai_response";
}