Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(sps): background backfill so it doesn't time out at the ALB (#3096)
gbirman1b7265d966b7
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 6b7e6df36f..db1cde92f2 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -9782,6 +9782,7 @@ dependencies = ["strum","thiserror 2.0.17","tokio",+ "tokio-util","tower 0.5.2","tower-http","tracing",diff --git a/rust/cloud-storage/search_processing_service/Cargo.toml b/rust/cloud-storage/search_processing_service/Cargo.tomlindex 9822403735..1f7d8d8b3f 100644--- a/rust/cloud-storage/search_processing_service/Cargo.toml+++ b/rust/cloud-storage/search_processing_service/Cargo.toml@@ -60,7 +60,8 @@ sqs_client = { path = "../sqs_client", default-features = false, features = [sqs_worker = { path = "../sqs_worker" }strum = { workspace = true }thiserror = { workspace = true }-tokio = { workspace = true }+tokio = { workspace = true, features = ["signal"] }+tokio-util = { workspace = true }tower = { workspace = true }tower-http = { workspace = true }tracing = { workspace = true }diff --git a/rust/cloud-storage/search_processing_service/src/api/context.rs b/rust/cloud-storage/search_processing_service/src/api/context.rsindex dddfb12719..1209804c92 100644--- a/rust/cloud-storage/search_processing_service/src/api/context.rs+++ b/rust/cloud-storage/search_processing_service/src/api/context.rs@@ -5,6 +5,7 @@ use std::sync::Arc;use crate::BackfillServiceImpl;use crate::config::Config;+use crate::domain::jobs::BackfillJobs;#[derive(Clone, FromRef)]pub(crate) struct ApiContext {@@ -14,4 +15,5 @@ pub(crate) struct ApiContext {pub internal_auth_key: LocalOrRemoteSecret<InternalApiSecretKey>,pub config: Arc<Config>,pub backfill_service: Arc<BackfillServiceImpl>,+ pub backfill_jobs: BackfillJobs,}diff --git a/rust/cloud-storage/search_processing_service/src/api/internal/backfill.rs b/rust/cloud-storage/search_processing_service/src/api/internal/backfill.rsindex d61bd36abc..1bc04e9237 100644--- a/rust/cloud-storage/search_processing_service/src/api/internal/backfill.rs+++ b/rust/cloud-storage/search_processing_service/src/api/internal/backfill.rs@@ -1,26 +1,33 @@//! Internal HTTP surface for every search-event backfill.//!-//! Every handler is a thin adapter: decode the per-entity request body, call-//! the matching method on [`BackfillService`], serialise the receipt. All-//! shared concerns (pagination, DB access, queue publishing) live in the-//! domain + outbound adapters — this file stays dumb on purpose so adding a-//! new entity is one handler + one `.route(...)`.+//! Each POST handler kicks the orchestrator onto a background tokio task+//! and returns `202 Accepted` with a job id right away — prod-scale corpora+//! can take many minutes to drain, well past the ALB idle timeout.+//! Clients poll `GET /internal/backfill/{job_id}` for progress; the+//! orchestrator updates the shared progress counter as each page lands.+//! On shutdown the registry's cancellation tokens fire so drains stop+//! between pages instead of being killed mid-publish.+//!+//! Adding a new entity is one POST handler + one `.route(...)`; the status+//! handler is generic.use std::sync::Arc;use axum::{Router,- extract::{self, State},+ extract::{self, Path, State},http::StatusCode,response::{IntoResponse, Response},- routing::post,+ routing::{get, post},};+use serde::Serialize;use crate::BackfillServiceImpl;use crate::api::context::ApiContext;+use crate::domain::jobs::{BackfillJobs, JobId};use crate::domain::models::{- BackfillError, BackfillReceipt, CallBackfillRequest, ChannelBackfillRequest,- ChatBackfillRequest, DocumentBackfillRequest, EmailBackfillRequest,+ CallBackfillRequest, ChannelBackfillRequest, ChatBackfillRequest, DocumentBackfillRequest,+ EmailBackfillRequest,};use crate::domain::service::BackfillService;@@ -31,54 +38,137 @@ pub fn router() -> Router<ApiContext> {.route("/channels", post(channels)).route("/documents", post(documents)).route("/emails", post(emails))+ .route("/{job_id}", get(status))+}++#[derive(Debug, Serialize)]+struct AcceptedReceipt {+ job_id: JobId,}-#[tracing::instrument(skip(service, req))]+#[tracing::instrument(skip(service, jobs, req))]async fn calls(State(service): State<Arc<BackfillServiceImpl>>,+ State(jobs): State<BackfillJobs>,extract::Json(req): extract::Json<CallBackfillRequest>,) -> Response {- receipt(service.backfill_calls(req).await)+ spawn_backfill(+ service,+ jobs,+ "calls",+ move |svc, progress, cancel| async move { svc.backfill_calls(req, progress, cancel).await },+ )}-#[tracing::instrument(skip(service, req))]+#[tracing::instrument(skip(service, jobs, req))]async fn chats(State(service): State<Arc<BackfillServiceImpl>>,+ State(jobs): State<BackfillJobs>,extract::Json(req): extract::Json<ChatBackfillRequest>,) -> Response {- receipt(service.backfill_chats(req).await)+ spawn_backfill(+ service,+ jobs,+ "chats",+ move |svc, progress, cancel| async move { svc.backfill_chats(req, progress, cancel).await },+ )}-#[tracing::instrument(skip(service, req))]+#[tracing::instrument(skip(service, jobs, req))]async fn channels(State(service): State<Arc<BackfillServiceImpl>>,+ State(jobs): State<BackfillJobs>,extract::Json(req): extract::Json<ChannelBackfillRequest>,) -> Response {- receipt(service.backfill_channels(req).await)+ spawn_backfill(+ service,+ jobs,+ "channels",+ move |svc, progress, cancel| async move { svc.backfill_channels(req, progress, cancel).await },+ )}-#[tracing::instrument(skip(service, req))]+#[tracing::instrument(skip(service, jobs, req))]async fn documents(State(service): State<Arc<BackfillServiceImpl>>,+ State(jobs): State<BackfillJobs>,extract::Json(req): extract::Json<DocumentBackfillRequest>,) -> Response {- receipt(service.backfill_documents(req).await)+ spawn_backfill(+ service,+ jobs,+ "documents",+ move |svc, progress, cancel| async move { svc.backfill_documents(req, progress, cancel).await },+ )}-#[tracing::instrument(skip(service, req))]+#[tracing::instrument(skip(service, jobs, req))]async fn emails(State(service): State<Arc<BackfillServiceImpl>>,+ State(jobs): State<BackfillJobs>,extract::Json(req): extract::Json<EmailBackfillRequest>,) -> Response {- receipt(service.backfill_emails(req).await)+ spawn_backfill(+ service,+ jobs,+ "emails",+ move |svc, progress, cancel| async move { svc.backfill_emails(req, progress, cancel).await },+ )}-fn receipt(result: Result<BackfillReceipt, BackfillError>) -> Response {- match result {- Ok(r) => axum::Json(r).into_response(),- Err(e) => {- tracing::error!(error=?e, "backfill failed");- (StatusCode::INTERNAL_SERVER_ERROR, "backfill failed").into_response()- }+#[tracing::instrument(skip(jobs))]+async fn status(State(jobs): State<BackfillJobs>, Path(job_id): Path<String>) -> Response {+ match jobs.snapshot(&JobId::from(job_id)) {+ Some(snap) => axum::Json(snap).into_response(),+ None => (StatusCode::NOT_FOUND, "unknown job id").into_response(),}}++/// Allocate a job slot, hand the progress + cancel token to the worker+/// future the caller built, spawn it, and return `202 Accepted` with the+/// job id. The worker future captures the request body so the HTTP body+/// reference doesn't outlive the handler.+fn spawn_backfill<F, Fut>(+ service: Arc<BackfillServiceImpl>,+ jobs: BackfillJobs,+ entity: &'static str,+ run: F,+) -> Response+where+ F: FnOnce(+ Arc<BackfillServiceImpl>,+ Arc<crate::domain::jobs::JobProgress>,+ tokio_util::sync::CancellationToken,+ ) -> Fut+ + Send+ + 'static,+ Fut: std::future::Future<+ Output = Result<+ crate::domain::models::BackfillReceipt,+ crate::domain::models::BackfillError,+ >,+ > + Send,+{+ let handle = jobs.start();+ let id = handle.id.clone();+ let id_for_task = handle.id.clone();+ let jobs_for_task = jobs.clone();++ tracing::info!(job_id = %id, entity, "spawning backfill");++ tokio::spawn(async move {+ let result = run(service, handle.progress, handle.cancel).await;+ if let Err(e) = &result {+ tracing::error!(job_id = %id_for_task, entity, error = ?e, "backfill failed");+ } else {+ tracing::info!(job_id = %id_for_task, entity, "backfill completed");+ }+ jobs_for_task.finish(&id_for_task, result);+ });++ (+ StatusCode::ACCEPTED,+ axum::Json(AcceptedReceipt { job_id: id }),+ )+ .into_response()+}diff --git a/rust/cloud-storage/search_processing_service/src/api/mod.rs b/rust/cloud-storage/search_processing_service/src/api/mod.rsindex 4ad8e2911e..ec03b65923 100644--- a/rust/cloud-storage/search_processing_service/src/api/mod.rs+++ b/rust/cloud-storage/search_processing_service/src/api/mod.rs@@ -21,6 +21,7 @@ pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {let port = state.config.port;let env = state.config.environment;+ let backfill_jobs = state.backfill_jobs.clone();let app = api_router(state.internal_auth_key.clone()).with_state(state).layer(cors.clone())@@ -38,10 +39,46 @@ pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {port);axum::serve(listener, app.into_make_service())+ .with_graceful_shutdown(shutdown_signal(backfill_jobs)).await.context("error starting service")}+/// Block on a SIGINT/SIGTERM signal, then fire every tracked backfill's+/// cancellation token so drains stop between pages instead of being killed+/// mid-publish when the runtime exits.+async fn shutdown_signal(backfill_jobs: crate::domain::jobs::BackfillJobs) {+ let ctrl_c = async {+ if let Err(e) = tokio::signal::ctrl_c().await {+ tracing::error!(error=?e, "failed to install ctrl_c handler");+ }+ };++ #[cfg(unix)]+ let terminate = async {+ match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {+ Ok(mut sig) => {+ sig.recv().await;+ }+ Err(e) => {+ tracing::error!(error=?e, "failed to install SIGTERM handler");+ std::future::pending::<()>().await;+ }+ }+ };++ #[cfg(not(unix))]+ let terminate = std::future::pending::<()>();++ tokio::select! {+ _ = ctrl_c => {},+ _ = terminate => {},+ }++ tracing::info!("shutdown signal received; cancelling in-flight backfills");+ backfill_jobs.cancel_all();+}+fn api_router(internal_secret: LocalOrRemoteSecret<InternalApiSecretKey>) -> Router<ApiContext> {Router::new().nest("/internal",diff --git a/rust/cloud-storage/search_processing_service/src/domain/jobs.rs b/rust/cloud-storage/search_processing_service/src/domain/jobs.rsnew file mode 100644index 0000000000..2010131fa3--- /dev/null+++ b/rust/cloud-storage/search_processing_service/src/domain/jobs.rs@@ -0,0 +1,240 @@+//! In-memory registry of long-running backfill jobs.+//!+//! Backfills can take many minutes for prod-scale entities — well past the+//! ALB idle timeout — so the HTTP handler kicks the orchestrator onto a+//! background tokio task and returns a [`JobId`] right away. Clients poll+//! [`BackfillJobs::snapshot`] for progress; the orchestrator updates the+//! shared [`JobProgress`] as each page lands. On shutdown,+//! [`BackfillJobs::cancel_all`] fires every job's [`CancellationToken`] so+//! drains stop between pages instead of being killed mid-publish.++use std::collections::HashMap;+use std::sync::Arc;+use std::sync::Mutex;+use std::sync::atomic::{AtomicUsize, Ordering};++use chrono::{DateTime, Utc};+use serde::Serialize;+use tokio_util::sync::CancellationToken;+use uuid::Uuid;++use super::models::{BackfillError, BackfillReceipt};++/// Opaque identifier the API hands back when a backfill is queued.+#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize)]+#[serde(transparent)]+pub struct JobId(String);++impl JobId {+ pub fn new() -> Self {+ Self(Uuid::new_v4().to_string())+ }+}++impl From<String> for JobId {+ fn from(s: String) -> Self {+ Self(s)+ }+}++impl std::fmt::Display for JobId {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(&self.0)+ }+}++/// Live row counter the orchestrator increments per page so the status+/// endpoint can report progress while the backfill is still running.+#[derive(Debug, Default)]+pub struct JobProgress {+ enqueued: AtomicUsize,+}++impl JobProgress {+ pub fn add(&self, n: usize) {+ self.enqueued.fetch_add(n, Ordering::Relaxed);+ }++ pub fn enqueued(&self) -> usize {+ self.enqueued.load(Ordering::Relaxed)+ }+}++/// Terminal state of a tracked job. `Running` is the only non-terminal+/// variant; the others are written exactly once when the worker future+/// resolves or is cancelled.+#[derive(Debug, Clone, Serialize)]+#[serde(tag = "status", rename_all = "snake_case")]+pub enum JobStatus {+ Running,+ Completed,+ Failed { error: String },+ Cancelled,+}++#[derive(Debug, Serialize)]+pub struct JobSnapshot {+ pub job_id: JobId,+ #[serde(flatten)]+ pub status: JobStatus,+ pub enqueued: usize,+ pub started_at: DateTime<Utc>,+ pub finished_at: Option<DateTime<Utc>>,+}++/// Bag of state the spawning code needs after [`BackfillJobs::start`]: the+/// id to hand back over HTTP, the progress counter to thread into the+/// orchestrator, and the token to wire to a `select!` for shutdown.+pub struct JobHandle {+ pub id: JobId,+ pub progress: Arc<JobProgress>,+ pub cancel: CancellationToken,+}++struct JobRecord {+ progress: Arc<JobProgress>,+ cancel: CancellationToken,+ status: JobStatus,+ started_at: DateTime<Utc>,+ finished_at: Option<DateTime<Utc>>,+}++/// Async-shareable registry of in-flight and finished backfill jobs. Cheap+/// to clone — backed by an `Arc<Mutex<HashMap>>` whose lock is never held+/// across awaits.+#[derive(Clone, Default)]+pub struct BackfillJobs {+ inner: Arc<Mutex<HashMap<JobId, JobRecord>>>,+}++impl BackfillJobs {+ pub fn new() -> Self {+ Self::default()+ }++ /// Allocate a new job slot and return the handle the spawning code+ /// needs to drive and observe it.+ pub fn start(&self) -> JobHandle {+ let id = JobId::new();+ let progress = Arc::new(JobProgress::default());+ let cancel = CancellationToken::new();+ let record = JobRecord {+ progress: progress.clone(),+ cancel: cancel.clone(),+ status: JobStatus::Running,+ started_at: Utc::now(),+ finished_at: None,+ };+ self.inner.lock().unwrap().insert(id.clone(), record);+ JobHandle {+ id,+ progress,+ cancel,+ }+ }++ /// Record the orchestrator's terminal result. Treats an `Ok` after the+ /// token fired as `Cancelled` so a clean `select!` exit still surfaces+ /// to the status endpoint.+ pub fn finish(&self, id: &JobId, result: Result<BackfillReceipt, BackfillError>) {+ let mut guard = self.inner.lock().unwrap();+ let Some(record) = guard.get_mut(id) else {+ return;+ };+ record.finished_at = Some(Utc::now());+ record.status = match result {+ Ok(_) if record.cancel.is_cancelled() => JobStatus::Cancelled,+ Ok(_) => JobStatus::Completed,+ Err(e) => JobStatus::Failed {+ error: format!("{e}"),+ },+ };+ }++ pub fn snapshot(&self, id: &JobId) -> Option<JobSnapshot> {+ let guard = self.inner.lock().unwrap();+ let record = guard.get(id)?;+ Some(JobSnapshot {+ job_id: id.clone(),+ status: record.status.clone(),+ enqueued: record.progress.enqueued(),+ started_at: record.started_at,+ finished_at: record.finished_at,+ })+ }++ /// Fire every tracked job's cancellation token. Used on graceful+ /// shutdown so drains stop between pages instead of being killed+ /// mid-publish when the runtime exits.+ pub fn cancel_all(&self) {+ let guard = self.inner.lock().unwrap();+ for record in guard.values() {+ record.cancel.cancel();+ }+ }+}++#[cfg(test)]+mod test {+ use super::*;++ #[test]+ fn snapshot_reflects_progress_updates() {+ let jobs = BackfillJobs::new();+ let handle = jobs.start();+ handle.progress.add(7);+ handle.progress.add(3);++ let snap = jobs.snapshot(&handle.id).unwrap();+ assert_eq!(snap.enqueued, 10);+ assert!(matches!(snap.status, JobStatus::Running));+ }++ #[test]+ fn finish_ok_after_cancel_marks_cancelled() {+ let jobs = BackfillJobs::new();+ let handle = jobs.start();+ handle.cancel.cancel();+ jobs.finish(&handle.id, Ok(BackfillReceipt { enqueued: 0 }));++ let snap = jobs.snapshot(&handle.id).unwrap();+ assert!(matches!(snap.status, JobStatus::Cancelled));+ assert!(snap.finished_at.is_some());+ }++ #[test]+ fn finish_err_records_failure_message() {+ let jobs = BackfillJobs::new();+ let handle = jobs.start();+ jobs.finish(+ &handle.id,+ Err(BackfillError::Source(anyhow::anyhow!("boom"))),+ );++ let snap = jobs.snapshot(&handle.id).unwrap();+ match snap.status {+ JobStatus::Failed { error } => {+ assert!(error.contains("failed reading backfill source"))+ }+ other => panic!("expected Failed, got {other:?}"),+ }+ }++ #[test]+ fn cancel_all_fires_every_token() {+ let jobs = BackfillJobs::new();+ let a = jobs.start();+ let b = jobs.start();++ jobs.cancel_all();++ assert!(a.cancel.is_cancelled());+ assert!(b.cancel.is_cancelled());+ }++ #[test]+ fn snapshot_returns_none_for_unknown_id() {+ let jobs = BackfillJobs::new();+ assert!(jobs.snapshot(&JobId::new()).is_none());+ }+}diff --git a/rust/cloud-storage/search_processing_service/src/domain/mod.rs b/rust/cloud-storage/search_processing_service/src/domain/mod.rsindex 56308a5110..2761b811a6 100644--- a/rust/cloud-storage/search_processing_service/src/domain/mod.rs+++ b/rust/cloud-storage/search_processing_service/src/domain/mod.rs@@ -7,6 +7,7 @@//! own mapping to [`sqs_client::search::SearchQueueMessage`] — but the public//! surface (orchestration + HTTP routes) stays uniform.+pub mod jobs;pub mod models;pub mod ports;pub mod service;diff --git a/rust/cloud-storage/search_processing_service/src/domain/service.rs b/rust/cloud-storage/search_processing_service/src/domain/service.rsindex 7cdb93adc9..8ad73236c7 100644--- a/rust/cloud-storage/search_processing_service/src/domain/service.rs+++ b/rust/cloud-storage/search_processing_service/src/domain/service.rs@@ -8,34 +8,51 @@//! — adapters stay single-concern.use std::future::Future;+use std::sync::Arc;+use tokio_util::sync::CancellationToken;++use super::jobs::JobProgress;use super::models::{BackfillError, BackfillReceipt, CallBackfillRequest, ChannelBackfillRequest,ChatBackfillRequest, DocumentBackfillRequest, EmailBackfillRequest, SourcePage,};use super::ports::{BackfillSource, SearchEventPublisher};-/// Inbound contract for all backfill HTTP routes.+/// Inbound contract for all backfill HTTP routes. Each call drives a single+/// orchestration to completion (or to cancellation via `cancel`); the HTTP+/// layer is responsible for spawning these onto a background task and+/// reporting progress through `progress`.pub trait BackfillService: Send + Sync + 'static {fn backfill_calls(&self,req: CallBackfillRequest,+ progress: Arc<JobProgress>,+ cancel: CancellationToken,) -> impl Future<Output = Result<BackfillReceipt, BackfillError>> + Send;fn backfill_chats(&self,req: ChatBackfillRequest,+ progress: Arc<JobProgress>,+ cancel: CancellationToken,) -> impl Future<Output = Result<BackfillReceipt, BackfillError>> + Send;fn backfill_channels(&self,req: ChannelBackfillRequest,+ progress: Arc<JobProgress>,+ cancel: CancellationToken,) -> impl Future<Output = Result<BackfillReceipt, BackfillError>> + Send;fn backfill_documents(&self,req: DocumentBackfillRequest,+ progress: Arc<JobProgress>,+ cancel: CancellationToken,) -> impl Future<Output = Result<BackfillReceipt, BackfillError>> + Send;fn backfill_emails(&self,req: EmailBackfillRequest,+ progress: Arc<JobProgress>,+ cancel: CancellationToken,) -> impl Future<Output = Result<BackfillReceipt, BackfillError>> + Send;}@@ -59,8 +76,14 @@ where/// Offset advances by `rows_consumed`, *not* by message count — sources are/// free to fold many rows into a smaller batch of messages (see the email/// path) without confusing the loop into re-reading rows.+///+/// Checks `cancel` at the top of each iteration so a shutdown signal stops+/// the drain between pages instead of mid-publish; the receipt that comes+/// back reflects the rows actually enqueued before cancellation.async fn drain_source<Fut, P>(publisher: &P,+ progress: &JobProgress,+ cancel: &CancellationToken,fetch: impl Fn(usize) -> Fut,) -> Result<BackfillReceipt, BackfillError>where@@ -71,6 +94,10 @@ wherelet mut enqueued = 0usize;loop {+ if cancel.is_cancelled() {+ tracing::info!(enqueued, "backfill cancelled between pages");+ break;+ }let page = fetch(offset).await?;if page.rows_consumed == 0 {break;@@ -78,6 +105,7 @@ wherepublisher.publish(page.messages).await?;enqueued += page.rows_consumed;offset += page.rows_consumed;+ progress.add(page.rows_consumed);}Ok(BackfillReceipt { enqueued })@@ -91,8 +119,10 @@ whereasync fn backfill_calls(&self,req: CallBackfillRequest,+ progress: Arc<JobProgress>,+ cancel: CancellationToken,) -> Result<BackfillReceipt, BackfillError> {- drain_source(&self.publisher, |offset| {+ drain_source(&self.publisher, &progress, &cancel, |offset| {self.source.fetch_calls(&req, offset)}).await@@ -101,8 +131,10 @@ whereasync fn backfill_chats(&self,req: ChatBackfillRequest,+ progress: Arc<JobProgress>,+ cancel: CancellationToken,) -> Result<BackfillReceipt, BackfillError> {- drain_source(&self.publisher, |offset| {+ drain_source(&self.publisher, &progress, &cancel, |offset| {self.source.fetch_chats(&req, offset)}).await@@ -111,8 +143,10 @@ whereasync fn backfill_channels(&self,req: ChannelBackfillRequest,+ progress: Arc<JobProgress>,+ cancel: CancellationToken,) -> Result<BackfillReceipt, BackfillError> {- drain_source(&self.publisher, |offset| {+ drain_source(&self.publisher, &progress, &cancel, |offset| {self.source.fetch_channels(&req, offset)}).await@@ -121,8 +155,10 @@ whereasync fn backfill_documents(&self,req: DocumentBackfillRequest,+ progress: Arc<JobProgress>,+ cancel: CancellationToken,) -> Result<BackfillReceipt, BackfillError> {- drain_source(&self.publisher, |offset| {+ drain_source(&self.publisher, &progress, &cancel, |offset| {self.source.fetch_documents(&req, offset)}).await@@ -131,8 +167,10 @@ whereasync fn backfill_emails(&self,req: EmailBackfillRequest,+ progress: Arc<JobProgress>,+ cancel: CancellationToken,) -> Result<BackfillReceipt, BackfillError> {- drain_source(&self.publisher, |offset| {+ drain_source(&self.publisher, &progress, &cancel, |offset| {self.source.fetch_emails(&req, offset)}).awaitdiff --git a/rust/cloud-storage/search_processing_service/src/domain/service/test.rs b/rust/cloud-storage/search_processing_service/src/domain/service/test.rsindex fbeade8575..ba73ea6779 100644--- a/rust/cloud-storage/search_processing_service/src/domain/service/test.rs+++ b/rust/cloud-storage/search_processing_service/src/domain/service/test.rs@@ -1,8 +1,10 @@use std::sync::Mutex;use sqs_client::search::{SearchQueueMessage, call::CallRecordMessage};+use tokio_util::sync::CancellationToken;use super::*;+use crate::domain::jobs::JobProgress;use crate::domain::models::{CallBackfillRequest, SourcePage};use crate::domain::ports::SearchEventPublisher;@@ -109,6 +111,10 @@ fn page(messages: Vec<SearchQueueMessage>) -> SourcePage {}}+fn detached() -> (JobProgress, CancellationToken) {+ (JobProgress::default(), CancellationToken::new())+}+#[tokio::test]async fn drains_source_across_full_pages() {// Three full pages of 5; loop terminates on the empty fourth fetch.@@ -119,12 +125,16 @@ async fn drains_source_across_full_pages() {]);let publisher = RecordingPublisher::default();let req = CallBackfillRequest::default();+ let (progress, cancel) = detached();- let receipt = drain_source(&publisher, |offset| source.fetch_page(&req, offset))- .await- .unwrap();+ let receipt = drain_source(&publisher, &progress, &cancel, |offset| {+ source.fetch_page(&req, offset)+ })+ .await+ .unwrap();assert_eq!(receipt.enqueued, 15);+ assert_eq!(progress.enqueued(), 15);assert_eq!(publisher.batch_count(), 3);assert_eq!(publisher.total_messages(), 15);assert_eq!(publisher.batch_sizes(), vec![5, 5, 5]);@@ -143,10 +153,13 @@ async fn short_final_page_short_circuits() {]);let publisher = RecordingPublisher::default();let req = CallBackfillRequest::default();+ let (progress, cancel) = detached();- let receipt = drain_source(&publisher, |offset| source.fetch_page(&req, offset))- .await- .unwrap();+ let receipt = drain_source(&publisher, &progress, &cancel, |offset| {+ source.fetch_page(&req, offset)+ })+ .await+ .unwrap();assert_eq!(receipt.enqueued, 12);assert_eq!(publisher.batch_sizes(), vec![5, 5, 2]);@@ -175,10 +188,13 @@ async fn batched_source_advances_by_rows_not_messages() {]);let publisher = RecordingPublisher::default();let req = CallBackfillRequest::default();+ let (progress, cancel) = detached();- let receipt = drain_source(&publisher, |offset| source.fetch_page(&req, offset))- .await- .unwrap();+ let receipt = drain_source(&publisher, &progress, &cancel, |offset| {+ source.fetch_page(&req, offset)+ })+ .await+ .unwrap();// enqueued = sum of rows_consumed (the meaningful unit), not message count.assert_eq!(receipt.enqueued, 240);@@ -193,10 +209,13 @@ async fn empty_source_publishes_nothing() {let source = FakeSource::new(vec![]);let publisher = RecordingPublisher::default();let req = CallBackfillRequest::default();+ let (progress, cancel) = detached();- let receipt = drain_source(&publisher, |offset| source.fetch_page(&req, offset))- .await- .unwrap();+ let receipt = drain_source(&publisher, &progress, &cancel, |offset| {+ source.fetch_page(&req, offset)+ })+ .await+ .unwrap();assert_eq!(receipt.enqueued, 0);assert_eq!(publisher.batch_count(), 0);@@ -208,10 +227,13 @@ async fn source_error_propagates_without_partial_publish() {let source = ExplodingSource;let publisher = RecordingPublisher::default();let req = CallBackfillRequest::default();+ let (progress, cancel) = detached();- let err = drain_source(&publisher, |offset| source.fetch_page(&req, offset))- .await- .unwrap_err();+ let err = drain_source(&publisher, &progress, &cancel, |offset| {+ source.fetch_page(&req, offset)+ })+ .await+ .unwrap_err();assert!(matches!(err, BackfillError::Source(_)));assert_eq!(publisher.batch_count(), 0);@@ -222,12 +244,76 @@ async fn publish_error_propagates_after_first_fetch() {let source = FakeSource::new(vec![page(vec![msg("only")])]);let publisher = ExplodingPublisher;let req = CallBackfillRequest::default();+ let (progress, cancel) = detached();- let err = drain_source(&publisher, |offset| source.fetch_page(&req, offset))- .await- .unwrap_err();+ let err = drain_source(&publisher, &progress, &cancel, |offset| {+ source.fetch_page(&req, offset)+ })+ .await+ .unwrap_err();assert!(matches!(err, BackfillError::Publish(_)));// Source hit once with offset=0; publish failure stops the loop.assert_eq!(source.observed_offsets(), vec![0]);}++#[tokio::test]+async fn cancel_before_first_fetch_returns_empty_receipt() {+ let source = FakeSource::new(vec![page(vec![msg("never-read")])]);+ let publisher = RecordingPublisher::default();+ let req = CallBackfillRequest::default();+ let (progress, cancel) = detached();+ cancel.cancel();++ let receipt = drain_source(&publisher, &progress, &cancel, |offset| {+ source.fetch_page(&req, offset)+ })+ .await+ .unwrap();++ assert_eq!(receipt.enqueued, 0);+ assert_eq!(publisher.batch_count(), 0);+ // Loop bailed before the first fetch.+ assert!(source.observed_offsets().is_empty());+}++#[tokio::test]+async fn cancel_between_pages_stops_drain_after_current_page() {+ // Cancel the token from inside the publisher: the page that triggered+ // the cancel still publishes (we already paid for the fetch), but the+ // next iteration sees the flag and bails before the second fetch.+ struct CancellingPublisher {+ cancel: CancellationToken,+ seen: Mutex<Vec<usize>>,+ }+ impl SearchEventPublisher for CancellingPublisher {+ async fn publish(&self, messages: Vec<SearchQueueMessage>) -> Result<(), BackfillError> {+ self.seen.lock().unwrap().push(messages.len());+ self.cancel.cancel();+ Ok(())+ }+ }++ let source = FakeSource::new(vec![+ page((0..5).map(|i| msg(&format!("first-{i}"))).collect()),+ page((0..5).map(|i| msg(&format!("never-{i}"))).collect()),+ ]);+ let (progress, cancel) = detached();+ let publisher = CancellingPublisher {+ cancel: cancel.clone(),+ seen: Mutex::new(Vec::new()),+ };+ let req = CallBackfillRequest::default();++ let receipt = drain_source(&publisher, &progress, &cancel, |offset| {+ source.fetch_page(&req, offset)+ })+ .await+ .unwrap();++ assert_eq!(receipt.enqueued, 5);+ assert_eq!(progress.enqueued(), 5);+ // First page fetched + published; cancellation prevents the second fetch.+ assert_eq!(source.observed_offsets(), vec![0]);+ assert_eq!(*publisher.seen.lock().unwrap(), vec![5]);+}diff --git a/rust/cloud-storage/search_processing_service/src/main.rs b/rust/cloud-storage/search_processing_service/src/main.rsindex 78f28bae9c..d97eeea461 100644--- a/rust/cloud-storage/search_processing_service/src/main.rs+++ b/rust/cloud-storage/search_processing_service/src/main.rs@@ -3,7 +3,7 @@ use std::sync::Arc;use crate::{api::context::ApiContext,- domain::service::BackfillOrchestrator,+ domain::{jobs::BackfillJobs, service::BackfillOrchestrator},outbound::{publisher::SqsSearchEventPublisher, source::PgBackfillSource},process::{context::SearchProcessingContext, worker::run_search_processing_workers},};@@ -196,6 +196,8 @@ async fn main() -> anyhow::Result<()> {run_search_processing_workers(ctx, config.worker_count);}+ let backfill_jobs = BackfillJobs::new();+api::setup_and_serve(ApiContext {db,sqs_client,@@ -203,6 +205,7 @@ async fn main() -> anyhow::Result<()> {internal_auth_key,config: Arc::new(config),backfill_service,+ backfill_jobs,}).await?;Ok(())