Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(email): close backfill dedup race with a partial unique index (#4097)

gbirman69b86a8f7bcb
diff --git a/rust/cloud-storage/.sqlx/query-ea7622c671b053d5519e2fb2a996372002b31d070e2cbfe2d58ae763bc04b7c6.json b/rust/cloud-storage/.sqlx/query-87097a992a2d5274660147d12a865b5717e0acaff30e5361c0d00018eeedece6.json
similarity index 76%
rename from rust/cloud-storage/.sqlx/query-ea7622c671b053d5519e2fb2a996372002b31d070e2cbfe2d58ae763bc04b7c6.json
rename to rust/cloud-storage/.sqlx/query-87097a992a2d5274660147d12a865b5717e0acaff30e5361c0d00018eeedece6.json
index 071f6b7b3a..437242aaa6 100644
--- a/rust/cloud-storage/.sqlx/query-ea7622c671b053d5519e2fb2a996372002b31d070e2cbfe2d58ae763bc04b7c6.json
+++ b/rust/cloud-storage/.sqlx/query-87097a992a2d5274660147d12a865b5717e0acaff30e5361c0d00018eeedece6.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO email_backfill_jobs (id, link_id, fusionauth_user_id, threads_requested_limit, status)\n VALUES ($1, $2, $3, $4, 'Init')\n RETURNING \n id, \n link_id, \n fusionauth_user_id,\n threads_requested_limit,\n total_threads,\n threads_retrieved_count,\n status as \"status: db::backfill::BackfillJobStatus\",\n created_at, \n updated_at\n ",
+ "query": "\n INSERT INTO email_backfill_jobs (id, link_id, fusionauth_user_id, threads_requested_limit, status)\n VALUES ($1, $2, $3, $4, 'Init')\n ON CONFLICT (link_id) WHERE status IN ('Init', 'InProgress') DO NOTHING\n RETURNING\n id,\n link_id,\n fusionauth_user_id,\n threads_requested_limit,\n total_threads,\n threads_retrieved_count,\n status as \"status: db::backfill::BackfillJobStatus\",\n created_at,\n updated_at\n ",
"describe": {
"columns": [
{
@@ -82,5 +82,5 @@
false
]
},
- "hash": "ea7622c671b053d5519e2fb2a996372002b31d070e2cbfe2d58ae763bc04b7c6"
+ "hash": "87097a992a2d5274660147d12a865b5717e0acaff30e5361c0d00018eeedece6"
}
diff --git a/rust/cloud-storage/email_db_client/src/backfill/job/insert.rs b/rust/cloud-storage/email_db_client/src/backfill/job/insert.rs
index f2d56bf0f8..aa5f9e1c9a 100644
--- a/rust/cloud-storage/email_db_client/src/backfill/job/insert.rs
+++ b/rust/cloud-storage/email_db_client/src/backfill/job/insert.rs
@@ -3,13 +3,16 @@ use models_email::email::service;
use sqlx::PgPool;
use sqlx::types::Uuid;
+/// Creates an `Init` backfill job for a link. Returns `None` when an active
+/// (`Init`/`InProgress`) job already exists for the link — the `uq_active_backfill_job_per_link`
+/// partial unique index makes this atomic, so concurrent callers don't create duplicates.
#[tracing::instrument(skip(pool), err)]
pub async fn create_backfill_job(
pool: &PgPool,
link_id: Uuid,
fusionauth_user_id: &str,
num_threads: Option<i32>,
-) -> anyhow::Result<service::backfill::BackfillJob> {
+) -> anyhow::Result<Option<service::backfill::BackfillJob>> {
let id = macro_uuid::generate_uuid_v7();
let record = sqlx::query_as!(
@@ -17,15 +20,16 @@ pub async fn create_backfill_job(
r#"
INSERT INTO email_backfill_jobs (id, link_id, fusionauth_user_id, threads_requested_limit, status)
VALUES ($1, $2, $3, $4, 'Init')
- RETURNING
- id,
- link_id,
+ ON CONFLICT (link_id) WHERE status IN ('Init', 'InProgress') DO NOTHING
+ RETURNING
+ id,
+ link_id,
fusionauth_user_id,
threads_requested_limit,
total_threads,
threads_retrieved_count,
status as "status: db::backfill::BackfillJobStatus",
- created_at,
+ created_at,
updated_at
"#,
id,
@@ -33,8 +37,11 @@ pub async fn create_backfill_job(
fusionauth_user_id,
num_threads
)
- .fetch_one(pool)
+ .fetch_optional(pool)
.await?;
- Ok(record.into())
+ Ok(record.map(Into::into))
}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/email_db_client/src/backfill/job/insert/test.rs b/rust/cloud-storage/email_db_client/src/backfill/job/insert/test.rs
new file mode 100644
index 0000000000..1a89ff420b
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/src/backfill/job/insert/test.rs
@@ -0,0 +1,40 @@
+use super::create_backfill_job;
+use crate::backfill::job::get::get_active_backfill_job;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::types::Uuid;
+use sqlx::{Pool, Postgres};
+
+async fn insert_link(pool: &Pool<Postgres>, link_id: Uuid) {
+ sqlx::query!(
+ r#"INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider)
+ VALUES ($1, $2, $2, $3, 'GMAIL')"#,
+ link_id,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_backfill_job_dedupes_active_job(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::new_v4();
+ insert_link(&pool, link_id).await;
+
+ let first = create_backfill_job(&pool, link_id, "fusion-x", None).await?;
+ assert!(first.is_some(), "first create should insert a job");
+
+ // A second create while one is active no-ops (partial unique index) and returns None.
+ let second = create_backfill_job(&pool, link_id, "fusion-x", None).await?;
+ assert!(
+ second.is_none(),
+ "second create should no-op while a job is active"
+ );
+
+ // Exactly one active job exists, and it is the first one.
+ let active = get_active_backfill_job(&pool, link_id).await?;
+ assert_eq!(active.map(|j| j.id), first.map(|j| j.id));
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_service/src/api/email/init.rs b/rust/cloud-storage/email_service/src/api/email/init.rs
index 636c05f32a..1a18d3e600 100644
--- a/rust/cloud-storage/email_service/src/api/email/init.rs
+++ b/rust/cloud-storage/email_service/src/api/email/init.rs
@@ -537,8 +537,10 @@ pub async fn handler(
};
// Concurrent /email/init calls for the same inbox upsert the same link (ON CONFLICT)
- // and would each enqueue a backfill. If one is already in flight for this link, reuse
- // it instead of starting (and history-logging) a duplicate.
+ // and would each enqueue a backfill. Reuse an in-flight backfill if one already exists
+ // for this link rather than starting a duplicate. This cheap pre-check covers the common
+ // sequential case; the partial unique index behind create_backfill_job closes the
+ // check-then-create race for truly concurrent callers.
if let Some(existing) =
email_db_client::backfill::job::get::get_active_backfill_job(&ctx.db, link.id)
.await
@@ -554,7 +556,33 @@ pub async fn handler(
.into_response());
}
- // Record link creation in history table for tracking (best-effort)
+ let Some(backfill_job) = email_db_client::backfill::job::insert::create_backfill_job(
+ &ctx.db,
+ link.id,
+ link.fusionauth_user_id.as_str(),
+ None,
+ )
+ .await
+ .context("Failed to create backfill job")?
+ else {
+ // Lost the create race: a concurrent init already started this link's backfill.
+ // Reuse it without writing a duplicate history row or enqueueing a second backfill.
+ let existing =
+ email_db_client::backfill::job::get::get_active_backfill_job(&ctx.db, link.id)
+ .await
+ .context("Failed to fetch in-flight backfill job after insert conflict")?
+ .context("backfill insert conflicted but no active job found")?;
+ return Ok((
+ StatusCode::OK,
+ Json(InitResponse {
+ link_id: link.id,
+ backfill_job_id: Some(existing.id),
+ }),
+ )
+ .into_response());
+ };
+
+ // Genuinely new job — record link creation in history (best-effort) only now.
email_db_client::links_history::insert::insert_email_link_history(
&ctx.db,
link.id,
@@ -568,15 +596,6 @@ pub async fn handler(
})
.ok();
- let backfill_job = email_db_client::backfill::job::insert::create_backfill_job(
- &ctx.db,
- link.id,
- link.fusionauth_user_id.as_str(),
- None,
- )
- .await
- .context("Failed to create backfill job")?;
-
let ps_message = BackfillPubsubMessage {
backfill_operation: BackfillOperation::Init(JobScopedPayload {
link_id: link.id,
diff --git a/rust/cloud-storage/email_service/src/api/email/links/resync.rs b/rust/cloud-storage/email_service/src/api/email/links/resync.rs
index 26250ce059..29e20643aa 100644
--- a/rust/cloud-storage/email_service/src/api/email/links/resync.rs
+++ b/rust/cloud-storage/email_service/src/api/email/links/resync.rs
@@ -62,14 +62,26 @@ pub async fn resync_link_handler(
.into_response());
}
- let backfill_job = email_db_client::backfill::job::insert::create_backfill_job(
+ let Some(backfill_job) = email_db_client::backfill::job::insert::create_backfill_job(
&ctx.db,
link.id,
link.fusionauth_user_id.as_str(),
None,
)
.await
- .context("failed to create backfill job")?;
+ .context("failed to create backfill job")?
+ else {
+ // A concurrent request started the backfill between the check above and here.
+ let active = email_db_client::backfill::job::get::get_active_backfill_job(&ctx.db, link.id)
+ .await
+ .context("failed to fetch active backfill job after insert conflict")?
+ .context("backfill insert conflicted but no active job found")?;
+ return Ok(Json(ResyncResponse {
+ backfill_job_id: active.id,
+ already_in_progress: true,
+ })
+ .into_response());
+ };
let ps_message = BackfillPubsubMessage {
backfill_operation: BackfillOperation::Init(JobScopedPayload {
diff --git a/rust/cloud-storage/email_service/src/api/internal/gmail/create.rs b/rust/cloud-storage/email_service/src/api/internal/gmail/create.rs
index 895ef63207..47b5aecded 100644
--- a/rust/cloud-storage/email_service/src/api/internal/gmail/create.rs
+++ b/rust/cloud-storage/email_service/src/api/internal/gmail/create.rs
@@ -88,6 +88,45 @@ pub async fn handler(
.into_response()
})?;
+ let Some(backfill_job) = backfill_job else {
+ // An active backfill already exists for this link; reuse it and skip re-enqueue.
+ let existing =
+ email_db_client::backfill::job::get::get_active_backfill_job(&ctx.db, link.id)
+ .await
+ .map_err(|e| {
+ tracing::warn!(error=?e, "error fetching active backfill_job");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: format!(
+ "error fetching active backfill job for link {}",
+ link_id
+ )
+ .into(),
+ }),
+ )
+ .into_response()
+ })?
+ .ok_or_else(|| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: format!(
+ "backfill conflict but no active job for link {}",
+ link_id
+ )
+ .into(),
+ }),
+ )
+ .into_response()
+ })?;
+ link_job_pairs.push(LinkJobPair {
+ link_id,
+ job_id: existing.id,
+ });
+ continue;
+ };
+
link_job_pairs.push(LinkJobPair {
link_id,
job_id: backfill_job.id,
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260615224322_add_active_backfill_job_unique_index.sql b/rust/cloud-storage/macro_db_client/migrations/20260615224322_add_active_backfill_job_unique_index.sql
new file mode 100644
index 0000000000..6197a74840
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260615224322_add_active_backfill_job_unique_index.sql
@@ -0,0 +1,6 @@
+-- At most one active (Init/InProgress) backfill job per link, so concurrent connects can
+-- rely on ON CONFLICT instead of a racy check-then-insert. A one-off cleanup that resolves
+-- any pre-existing duplicate active jobs is deployed ahead of this migration.
+CREATE UNIQUE INDEX uq_active_backfill_job_per_link
+ ON email_backfill_jobs (link_id)
+ WHERE status IN ('Init', 'InProgress');