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): back the backfill job registry with dynamodb (#3102)
gbirman9cc552f0f90b
diff --git a/infra/packages/resources/src/resources/dynamodb.ts b/infra/packages/resources/src/resources/dynamodb.tsindex d0426de6f0..cb0a4ddbee 100644--- a/infra/packages/resources/src/resources/dynamodb.ts+++ b/infra/packages/resources/src/resources/dynamodb.ts@@ -13,6 +13,7 @@ type DynamoDBTableArgs = {billingMode?: 'PROVISIONED' | 'PAY_PER_REQUEST';tags?: { [key: string]: string };pointInTimeRecoveryEnabled?: boolean;+ ttl?: { attributeName: string; enabled?: boolean };};export class DynamoDBTable extends pulumi.ComponentResource {@@ -36,6 +37,7 @@ export class DynamoDBTable extends pulumi.ComponentResource {billingMode = 'PAY_PER_REQUEST',tags,pointInTimeRecoveryEnabled = stack === 'prod',+ ttl,} = args;this.table = new aws.dynamodb.Table(@@ -51,6 +53,9 @@ export class DynamoDBTable extends pulumi.ComponentResource {pointInTimeRecovery: {enabled: pointInTimeRecoveryEnabled,},+ ttl: ttl+ ? { attributeName: ttl.attributeName, enabled: ttl.enabled ?? true }+ : undefined,},{ parent: this });diff --git a/infra/stacks/search-processing-service/index.ts b/infra/stacks/search-processing-service/index.tsindex ad49221f5b..73cbb7980e 100644--- a/infra/stacks/search-processing-service/index.ts+++ b/infra/stacks/search-processing-service/index.ts@@ -1,5 +1,6 @@import * as aws from '@pulumi/aws';import * as pulumi from '@pulumi/pulumi';+import { DynamoDBTable } from '../../packages/resources';import {config,getSearchEventQueue,@@ -44,6 +45,14 @@ const opensearchStack = new pulumi.StackReference('opensearch-stack', {name: `macro-inc/opensearch/${stack}`,});+const backfillJobsTable = new DynamoDBTable('search-processing-backfill-jobs', {+ baseName: 'search-processing-backfill-jobs',+ attributes: [{ name: 'id', type: 'S' }],+ hashKey: 'id',+ ttl: { attributeName: 'expires_at' },+ tags,+});+const OPENSEARCH_URL: pulumi.Output<string> = opensearchStack.getOutput('domainEndpoint').apply((domainEndpoint) => `https://${domainEndpoint}`);@@ -82,6 +91,7 @@ const searchProcessingService = new SearchProcessingService(databaseUrlReadonlyArn,opensearchPasswordArn,],+ extraManagedPolicyArns: [backfillJobsTable.policy.arn],searchEventQueueArn,ecsClusterArn: cloudStorageClusterArn,documentStorageBucketArn,@@ -147,6 +157,10 @@ const searchProcessingService = new SearchProcessingService(name: ServiceUrl.LEXICAL_SERVICE_URL,value: getServiceUrl(ServiceUrl.LEXICAL_SERVICE_URL),},+ {+ name: 'BACKFILL_JOBS_TABLE',+ value: backfillJobsTable.table.name,+ },// OpenTelemetry / Datadog tracing configuration{name: 'DD_SERVICE',diff --git a/infra/stacks/search-processing-service/service.ts b/infra/stacks/search-processing-service/service.tsindex e0da89e765..9ccf2bb3d1 100644--- a/infra/stacks/search-processing-service/service.ts+++ b/infra/stacks/search-processing-service/service.ts@@ -37,6 +37,9 @@ type Args = {containerEnvVars?: { name: string; value: pulumi.Output<string> | string }[];healthCheckPath: string;searchEventQueueArn: pulumi.Output<string> | string;+ /// Extra managed policy ARNs to attach to the task role (e.g. DynamoDB+ /// access for the backfill job registry).+ extraManagedPolicyArns?: pulumi.Output<string>[];tags: { [key: string]: string };};@@ -68,6 +71,7 @@ export class SearchProcessingService extends pulumi.ComponentResource {tags,secretKeyArns,searchEventQueueArn,+ extraManagedPolicyArns = [],}: Args,opts?: pulumi.ComponentResourceOptions) {@@ -156,6 +160,7 @@ export class SearchProcessingService extends pulumi.ComponentResource {docStorageBucketPolicy.arn,secretsPolicy.arn,sqsPolicy.arn,+ ...extraManagedPolicyArns,],},{ parent: this }diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex db1cde92f2..b74aa42bb3 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -9742,6 +9742,7 @@ name = "search_processing_service"version = "0.1.0"dependencies = ["anyhow",+ "aws-sdk-dynamodb","aws-sdk-s3","aws-sdk-secretsmanager","aws-sdk-sqs",@@ -9750,6 +9751,7 @@ dependencies = ["comms_db_client","document_sub_type","email_db_client",+ "ensure_exists","futures","http-body-util","lexical_client",diff --git a/rust/cloud-storage/search_processing_service/Cargo.toml b/rust/cloud-storage/search_processing_service/Cargo.tomlindex 1f7d8d8b3f..38421a31cb 100644--- a/rust/cloud-storage/search_processing_service/Cargo.toml+++ b/rust/cloud-storage/search_processing_service/Cargo.toml@@ -17,6 +17,7 @@ required-features = ["processing", "service"][dependencies]anyhow = { workspace = true }+aws-sdk-dynamodb = { workspace = true }aws-sdk-s3 = { workspace = true }aws-sdk-secretsmanager = { workspace = true }aws-sdk-sqs = { workspace = true }@@ -47,6 +48,7 @@ models_opensearch = { path = "../models_opensearch" }models_search = { path = "../models_search" }nom = { workspace = true }opensearch_client = { path = "../opensearch_client" }+ensure_exists = { path = "../ensure_exists", features = ["dynamodb"] }pdfium-render = { workspace = true }rust-embed = "8.6.0"s3_client = { path = "../s3_client" }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 1bc04e9237..a76e7968a7 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@@ -2,11 +2,12 @@//!//! 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.+//! 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 in DynamoDB as each page lands. Any+//! SPS instance can answer the GET because state lives in DynamoDB, not+//! in process memory. On shutdown the registry's local 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.@@ -58,6 +59,7 @@ async fn calls("calls",move |svc, progress, cancel| async move { svc.backfill_calls(req, progress, cancel).await },)+ .await}#[tracing::instrument(skip(service, jobs, req))]@@ -72,6 +74,7 @@ async fn chats("chats",move |svc, progress, cancel| async move { svc.backfill_chats(req, progress, cancel).await },)+ .await}#[tracing::instrument(skip(service, jobs, req))]@@ -84,8 +87,11 @@ async fn channels(service,jobs,"channels",- move |svc, progress, cancel| async move { svc.backfill_channels(req, progress, cancel).await },+ move |svc, progress, cancel| async move {+ svc.backfill_channels(req, progress, cancel).await+ },)+ .await}#[tracing::instrument(skip(service, jobs, req))]@@ -98,8 +104,11 @@ async fn documents(service,jobs,"documents",- move |svc, progress, cancel| async move { svc.backfill_documents(req, progress, cancel).await },+ move |svc, progress, cancel| async move {+ svc.backfill_documents(req, progress, cancel).await+ },)+ .await}#[tracing::instrument(skip(service, jobs, req))]@@ -112,23 +121,30 @@ async fn emails(service,jobs,"emails",- move |svc, progress, cancel| async move { svc.backfill_emails(req, progress, cancel).await },+ move |svc, progress, cancel| async move {+ svc.backfill_emails(req, progress, cancel).await+ },)+ .await}#[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(),+ match jobs.snapshot(&JobId::from(job_id)).await {+ Ok(Some(snap)) => axum::Json(snap).into_response(),+ Ok(None) => (StatusCode::NOT_FOUND, "unknown job id").into_response(),+ Err(e) => {+ tracing::error!(error=?e, "failed to read backfill job snapshot");+ (StatusCode::INTERNAL_SERVER_ERROR, "registry unavailable").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>(+/// Allocate a job slot in the registry, 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.+async fn spawn_backfill<F, Fut>(service: Arc<BackfillServiceImpl>,jobs: BackfillJobs,entity: &'static str,@@ -149,7 +165,13 @@ where>,> + Send,{- let handle = jobs.start();+ let handle = match jobs.start(entity).await {+ Ok(h) => h,+ Err(e) => {+ tracing::error!(error=?e, entity, "failed to allocate backfill job in registry");+ return (StatusCode::INTERNAL_SERVER_ERROR, "registry unavailable").into_response();+ }+ };let id = handle.id.clone();let id_for_task = handle.id.clone();let jobs_for_task = jobs.clone();@@ -163,7 +185,9 @@ where} else {tracing::info!(job_id = %id_for_task, entity, "backfill completed");}- jobs_for_task.finish(&id_for_task, result);+ if let Err(e) = jobs_for_task.finish(&id_for_task, result).await {+ tracing::error!(job_id = %id_for_task, error=?e, "failed to record backfill terminal status in registry");+ }});(diff --git a/rust/cloud-storage/search_processing_service/src/api/mod.rs b/rust/cloud-storage/search_processing_service/src/api/mod.rsindex ec03b65923..7a89e50062 100644--- a/rust/cloud-storage/search_processing_service/src/api/mod.rs+++ b/rust/cloud-storage/search_processing_service/src/api/mod.rs@@ -44,9 +44,11 @@ pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {.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.+/// Block on a SIGINT/SIGTERM signal, then fire every locally tracked+/// backfill's cancellation token so drains stop between pages instead of+/// being killed mid-publish when the runtime exits. Only jobs running on+/// this pod are cancelled — the registry is shared via DynamoDB but+/// cancellation tokens are per-instance.async fn shutdown_signal(backfill_jobs: crate::domain::jobs::BackfillJobs) {let ctrl_c = async {if let Err(e) = tokio::signal::ctrl_c().await {@@ -75,8 +77,8 @@ async fn shutdown_signal(backfill_jobs: crate::domain::jobs::BackfillJobs) {_ = terminate => {},}- tracing::info!("shutdown signal received; cancelling in-flight backfills");- backfill_jobs.cancel_all();+ tracing::info!("shutdown signal received; cancelling in-flight backfills on this pod");+ backfill_jobs.cancel_all_local();}fn api_router(internal_secret: LocalOrRemoteSecret<InternalApiSecretKey>) -> Router<ApiContext> {diff --git a/rust/cloud-storage/search_processing_service/src/config.rs b/rust/cloud-storage/search_processing_service/src/config.rsindex 7b7bd6e2c6..2867b091ac 100644--- a/rust/cloud-storage/search_processing_service/src/config.rs+++ b/rust/cloud-storage/search_processing_service/src/config.rs@@ -62,6 +62,15 @@ pub struct Config {/// Per-entity DB page sizes for backfill adapters.pub backfill_page_sizes: BackfillPageSizes,++ /// DynamoDB table name backing the backfill job registry. Items carry an+ /// `expires_at` epoch attribute that DynamoDB's TTL sweeps in the+ /// background, so completed jobs vanish on their own.+ pub backfill_jobs_table: String,++ /// TTL applied to the `expires_at` attribute on each job record. Acts as+ /// the GC mechanism — DynamoDB removes items shortly after this elapses.+ pub backfill_job_ttl_seconds: u64,}fn parse_page_size(name: &str, default: usize) -> anyhow::Result<usize> {@@ -132,6 +141,13 @@ impl Config {emails: parse_page_size("BACKFILL_EMAILS_PAGE_SIZE", DEFAULT_EMAILS_PAGE)?,};+ let backfill_jobs_table =+ std::env::var("BACKFILL_JOBS_TABLE").context("BACKFILL_JOBS_TABLE must be provided")?;+ let backfill_job_ttl_seconds: u64 = std::env::var("BACKFILL_JOB_TTL_SECONDS")+ .unwrap_or_else(|_| (24 * 60 * 60).to_string())+ .parse()+ .context("BACKFILL_JOB_TTL_SECONDS must be a positive integer")?;+Ok(Config {database_url,database_url_readonly,@@ -147,6 +163,8 @@ impl Config {worker_count,lexical_service_url,backfill_page_sizes,+ backfill_jobs_table,+ backfill_job_ttl_seconds,})}}diff --git a/rust/cloud-storage/search_processing_service/src/domain/jobs.rs b/rust/cloud-storage/search_processing_service/src/domain/jobs.rsindex 2010131fa3..e19f2756e5 100644--- a/rust/cloud-storage/search_processing_service/src/domain/jobs.rs+++ b/rust/cloud-storage/search_processing_service/src/domain/jobs.rs@@ -1,19 +1,37 @@-//! In-memory registry of long-running backfill jobs.+//! DynamoDB-backed 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.+//! shared [`JobProgress`] (`UpdateItem ADD enqueued`) as each page lands.+//!+//! Why DynamoDB: SPS scales between 1 and 10 ECS tasks with no ALB+//! stickiness, so a status poll can land on a different instance from the+//! one that handled the POST. An in-memory registry would 404 in that+//! case. DynamoDB gives us a shared store with native TTL for cleanup and+//! pay-per-request pricing — no infra to provision.+//!+//! Each job is one item keyed on `id`. Items carry an `expires_at` epoch+//! attribute that DynamoDB's background TTL process sweeps. The+//! `Cancelled` status is a best-effort signal: cancellation tokens are+//! per-instance (kept in a local `HashMap`) since they don't replicate+//! across pods, so SIGTERM only stops jobs running on that pod. Since+//! workers re-index idempotently, a cancelled-but-not-recorded backfill+//! is recoverable by re-kicking it.use std::collections::HashMap;use std::sync::Arc;use std::sync::Mutex;+#[cfg(test)]use std::sync::atomic::{AtomicUsize, Ordering};+use std::time::Duration;+use aws_sdk_dynamodb::Client;+use aws_sdk_dynamodb::types::AttributeValue;use chrono::{DateTime, Utc};+use ensure_exists::EnsureExists;+use ensure_exists::dynamodb::{CreateTableErr, DefineTable, DynamoClientWrapper};use serde::Serialize;use tokio_util::sync::CancellationToken;use uuid::Uuid;@@ -43,47 +61,165 @@ impl std::fmt::Display for JobId {}}-/// Live row counter the orchestrator increments per page so the status-/// endpoint can report progress while the backfill is still running.-#[derive(Debug, Default)]+/// Newtype around the table name so `DefineTable` knows what to create.+/// Used by [`BackfillJobs::ensure_table`] for local-dev table bootstrap;+/// in deployed environments Pulumi creates the table.+#[derive(Debug, Clone)]+pub struct BackfillJobsTable(Arc<str>);++impl AsRef<str> for BackfillJobsTable {+ fn as_ref(&self) -> &str {+ &self.0+ }+}++impl DefineTable for BackfillJobsTable {+ async fn create_table(&self, client: &aws_sdk_dynamodb::Client) -> Result<(), CreateTableErr> {+ client+ .create_table()+ .table_name(self.as_ref())+ .key_schema(+ aws_sdk_dynamodb::types::KeySchemaElement::builder()+ .attribute_name("id")+ .key_type(aws_sdk_dynamodb::types::KeyType::Hash)+ .build()+ .map_err(aws_sdk_dynamodb::Error::from)?,+ )+ .attribute_definitions(+ aws_sdk_dynamodb::types::AttributeDefinition::builder()+ .attribute_name("id")+ .attribute_type(aws_sdk_dynamodb::types::ScalarAttributeType::S)+ .build()+ .map_err(aws_sdk_dynamodb::Error::from)?,+ )+ .billing_mode(aws_sdk_dynamodb::types::BillingMode::PayPerRequest)+ .send()+ .await+ .map_err(aws_sdk_dynamodb::Error::from)?;+ Ok(())+ }+}++/// Per-page progress hook handed to the orchestrator.+///+/// Two backends so `drain_source` doesn't need to know whether it's running+/// against a real DynamoDB or a unit-test fake:+///+/// - `Detached` — bumps an in-process atomic. Used by tests.+/// - `Dynamo` — fires `UpdateItem ADD enqueued :n` per page. Page bounds+/// are the same point the cancellation token is checked, so the round+/// trip cost is amortised over the page work.pub struct JobProgress {- enqueued: AtomicUsize,+ backend: ProgressBackend,+}++enum ProgressBackend {+ #[cfg(test)]+ Detached(AtomicUsize),+ Dynamo {+ client: Client,+ table: Arc<str>,+ id: JobId,+ },}impl JobProgress {- pub fn add(&self, n: usize) {- self.enqueued.fetch_add(n, Ordering::Relaxed);+ /// In-memory progress for tests. Production always uses the DynamoDB+ /// backend so other instances can read the live counter.+ #[cfg(test)]+ pub fn detached() -> Self {+ Self {+ backend: ProgressBackend::Detached(AtomicUsize::new(0)),+ }+ }++ fn dynamo(client: Client, table: Arc<str>, id: JobId) -> Self {+ Self {+ backend: ProgressBackend::Dynamo { client, table, id },+ }+ }++ /// Add `n` to the running enqueued count. Best effort against+ /// DynamoDB: a failed write logs and continues so a transient blip+ /// doesn't kill the whole drain (the next page's `ADD` reconciles).+ pub async fn add(&self, n: usize) {+ match &self.backend {+ #[cfg(test)]+ ProgressBackend::Detached(a) => {+ a.fetch_add(n, Ordering::Relaxed);+ }+ ProgressBackend::Dynamo { client, table, id } => {+ let result = client+ .update_item()+ .table_name(table.as_ref())+ .key("id", AttributeValue::S(id.0.clone()))+ .update_expression("ADD enqueued :n")+ .expression_attribute_values(":n", AttributeValue::N(n.to_string()))+ .send()+ .await;+ if let Err(e) = result {+ tracing::warn!(error=?e, id=%id, "failed to update backfill progress in dynamodb");+ }+ }+ }}- pub fn enqueued(&self) -> usize {- self.enqueued.load(Ordering::Relaxed)+ #[cfg(test)]+ pub fn local_count(&self) -> usize {+ match &self.backend {+ ProgressBackend::Detached(a) => a.load(Ordering::Relaxed),+ ProgressBackend::Dynamo { .. } => 0,+ }}}/// 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")]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]pub enum JobStatus {Running,Completed,- Failed { error: String },+ Failed,Cancelled,}+impl JobStatus {+ fn as_str(self) -> &'static str {+ match self {+ JobStatus::Running => "running",+ JobStatus::Completed => "completed",+ JobStatus::Failed => "failed",+ JobStatus::Cancelled => "cancelled",+ }+ }++ fn from_str(s: &str) -> Option<Self> {+ match s {+ "running" => Some(JobStatus::Running),+ "completed" => Some(JobStatus::Completed),+ "failed" => Some(JobStatus::Failed),+ "cancelled" => Some(JobStatus::Cancelled),+ _ => None,+ }+ }+}+#[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>>,+ /// Populated when `status == Failed`.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error: Option<String>,}/// Bag of state the spawning code needs after [`BackfillJobs::start`]: the-/// id to hand back over HTTP, the progress counter to thread into the+/// id to hand back over HTTP, the progress hook to thread into the/// orchestrator, and the token to wire to a `select!` for shutdown.pub struct JobHandle {pub id: JobId,@@ -91,150 +227,192 @@ pub struct JobHandle {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)]+/// Async-shareable registry of backfill jobs, backed by DynamoDB. Cheap to+/// clone — the SDK `Client` is internally `Arc`-y and the local cancel+/// map sits behind one `Arc<Mutex<…>>`.+#[derive(Clone)]pub struct BackfillJobs {- inner: Arc<Mutex<HashMap<JobId, JobRecord>>>,+ client: Client,+ table: Arc<str>,+ /// Per-instance cancellation tokens. Cancellation does not replicate+ /// across pods (we have no cancel endpoint, and the token is the only+ /// mechanism `drain_source` checks). Entries are removed on `finish`.+ local_cancels: Arc<Mutex<HashMap<JobId, CancellationToken>>>,+ ttl: Duration,}impl BackfillJobs {- pub fn new() -> Self {- Self::default()+ pub fn new(client: Client, table: impl Into<Arc<str>>, ttl: Duration) -> Self {+ Self {+ client,+ table: table.into(),+ local_cancels: Arc::new(Mutex::new(HashMap::new())),+ ttl,+ }+ }++ /// Create the DynamoDB table if it doesn't exist. Used in local+ /// development against the dynamodb-local container; in deployed+ /// environments Pulumi owns the table and this is a no-op (DescribeTable+ /// finds it and returns).+ pub async fn ensure_table(&self) -> anyhow::Result<()> {+ let table = BackfillJobsTable(self.table.clone());+ let wrapper = DynamoClientWrapper {+ client: &self.client,+ table_name: table,+ };+ wrapper.ensure_exists().await?;+ Ok(())}/// Allocate a new job slot and return the handle the spawning code- /// needs to drive and observe it.- pub fn start(&self) -> JobHandle {+ /// needs to drive and observe it. Writes the initial item with TTL+ /// before returning so a subsequent status poll can find it.+ pub async fn start(&self, entity: &str) -> anyhow::Result<JobHandle> {let id = JobId::new();- let progress = Arc::new(JobProgress::default());+ let started_at = Utc::now();+ let expires_at = started_at + chrono::Duration::from_std(self.ttl)?;++ self.client+ .put_item()+ .table_name(self.table.as_ref())+ .item("id", AttributeValue::S(id.0.clone()))+ .item(+ "status",+ AttributeValue::S(JobStatus::Running.as_str().to_string()),+ )+ .item("enqueued", AttributeValue::N("0".to_string()))+ .item("started_at", AttributeValue::S(started_at.to_rfc3339()))+ .item("entity", AttributeValue::S(entity.to_string()))+ .item(+ "expires_at",+ AttributeValue::N(expires_at.timestamp().to_string()),+ )+ .send()+ .await?;+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,+ self.local_cancels+ .lock()+ .unwrap()+ .insert(id.clone(), cancel.clone());++ Ok(JobHandle {+ id: id.clone(),+ progress: Arc::new(JobProgress::dynamo(+ self.client.clone(),+ self.table.clone(),+ id,+ )),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;+ /// to the status endpoint. Drops the local cancellation entry — a+ /// finished job can no longer be cancelled.+ pub async fn finish(+ &self,+ id: &JobId,+ result: Result<BackfillReceipt, BackfillError>,+ ) -> anyhow::Result<()> {+ let was_cancelled = self+ .local_cancels+ .lock()+ .unwrap()+ .remove(id)+ .is_some_and(|t| t.is_cancelled());++ let (status, error) = match result {+ Ok(_) if was_cancelled => (JobStatus::Cancelled, None),+ Ok(_) => (JobStatus::Completed, None),+ Err(e) => (JobStatus::Failed, Some(format!("{e}"))),};- 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}"),- },++ let mut update = self+ .client+ .update_item()+ .table_name(self.table.as_ref())+ .key("id", AttributeValue::S(id.0.clone()))+ .expression_attribute_names("#s", "status")+ .expression_attribute_values(":s", AttributeValue::S(status.as_str().to_string()))+ .expression_attribute_values(":f", AttributeValue::S(Utc::now().to_rfc3339()));++ let expr = if let Some(e) = error {+ update = update+ .expression_attribute_names("#e", "error")+ .expression_attribute_values(":e", AttributeValue::S(e));+ "SET #s = :s, finished_at = :f, #e = :e"+ } else {+ "SET #s = :s, finished_at = :f"};++ update.update_expression(expr).send().await?;+ Ok(())}- pub fn snapshot(&self, id: &JobId) -> Option<JobSnapshot> {- let guard = self.inner.lock().unwrap();- let record = guard.get(id)?;- Some(JobSnapshot {+ /// Read the current state of a job from DynamoDB. `Ok(None)` when the+ /// item has expired or never existed.+ pub async fn snapshot(&self, id: &JobId) -> anyhow::Result<Option<JobSnapshot>> {+ let resp = self+ .client+ .get_item()+ .table_name(self.table.as_ref())+ .key("id", AttributeValue::S(id.0.clone()))+ .send()+ .await?;+ let Some(item) = resp.item else {+ return Ok(None);+ };++ let status = item+ .get("status")+ .and_then(|v| v.as_s().ok())+ .and_then(|s| JobStatus::from_str(s))+ .unwrap_or(JobStatus::Running);+ let enqueued: usize = item+ .get("enqueued")+ .and_then(|v| v.as_n().ok())+ .and_then(|s| s.parse().ok())+ .unwrap_or(0);+ let started_at = item+ .get("started_at")+ .and_then(|v| v.as_s().ok())+ .and_then(|s| DateTime::parse_from_rfc3339(s).ok())+ .map(|dt| dt.with_timezone(&Utc))+ .unwrap_or_else(Utc::now);+ let finished_at = item+ .get("finished_at")+ .and_then(|v| v.as_s().ok())+ .and_then(|s| DateTime::parse_from_rfc3339(s).ok())+ .map(|dt| dt.with_timezone(&Utc));+ let error = item+ .get("error")+ .and_then(|v| v.as_s().ok())+ .map(|s| s.to_string());++ Ok(Some(JobSnapshot {job_id: id.clone(),- status: record.status.clone(),- enqueued: record.progress.enqueued(),- started_at: record.started_at,- finished_at: record.finished_at,- })+ status,+ enqueued,+ started_at,+ finished_at,+ error,+ }))}- /// Fire every tracked job's cancellation token. Used on graceful+ /// Fire every locally tracked 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();+ /// mid-publish when the runtime exits. Cancellation does not propagate+ /// across pods — that'd require a cancel endpoint we don't have.+ pub fn cancel_all_local(&self) {+ let guard = self.local_cancels.lock().unwrap();+ for cancel in guard.values() {+ 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());- }-}+mod test;diff --git a/rust/cloud-storage/search_processing_service/src/domain/jobs/test.rs b/rust/cloud-storage/search_processing_service/src/domain/jobs/test.rsnew file mode 100644index 0000000000..66c6b24577--- /dev/null+++ b/rust/cloud-storage/search_processing_service/src/domain/jobs/test.rs@@ -0,0 +1,138 @@+//! Integration-ish tests for the DynamoDB-backed backfill registry.+//!+//! These exercise local DynamoDB (the `my-dynamodb` container started by+//! `just ensure_dynamodb`). Each test uses the same shared table; fresh+//! `JobId`s (UUIDs) keep parallel runs from clobbering each other. Tests+//! short-circuit if dynamodb-local isn't reachable so `cargo test` works+//! without the container running.++use std::time::Duration;++use aws_sdk_dynamodb::config::{BehaviorVersion, Credentials, Region};++use super::*;++const LOCAL_TABLE: &str = "search_processing_backfill_jobs_test";+const LOCAL_ENDPOINT: &str = "http://127.0.0.1:8000";++async fn try_jobs() -> Option<BackfillJobs> {+ // Build the DynamoDB client config directly via the SDK's own builder+ // — `aws-config` is wrapped by `macro_aws_config` workspace-wide, but+ // we need a per-client endpoint override that the wrapper doesn't+ // expose, so use the SDK builder here and skip `aws-config` entirely.+ let config = aws_sdk_dynamodb::config::Builder::new()+ .behavior_version(BehaviorVersion::latest())+ .region(Region::new("us-east-1"))+ .credentials_provider(Credentials::new("fake", "fake", None, None, "test"))+ .endpoint_url(LOCAL_ENDPOINT)+ .build();+ let client = aws_sdk_dynamodb::Client::from_conf(config);+ // Probe: list_tables fails fast if dynamodb-local isn't running.+ if client.list_tables().send().await.is_err() {+ return None;+ }+ let jobs = BackfillJobs::new(client, LOCAL_TABLE, Duration::from_secs(60));+ jobs.ensure_table().await.ok()?;+ Some(jobs)+}++#[tokio::test]+async fn snapshot_reflects_progress_updates() {+ let Some(jobs) = try_jobs().await else {+ eprintln!("skipping: dynamodb-local not reachable at {LOCAL_ENDPOINT}");+ return;+ };+ let handle = jobs.start("calls").await.expect("start");++ handle.progress.add(7).await;+ handle.progress.add(3).await;++ let snap = jobs.snapshot(&handle.id).await.expect("snapshot").unwrap();+ assert_eq!(snap.enqueued, 10);+ assert_eq!(snap.status, JobStatus::Running);+ assert!(snap.finished_at.is_none());+}++#[tokio::test]+async fn finish_ok_after_cancel_marks_cancelled() {+ let Some(jobs) = try_jobs().await else {+ eprintln!("skipping: dynamodb-local not reachable at {LOCAL_ENDPOINT}");+ return;+ };+ let handle = jobs.start("chats").await.expect("start");+ handle.cancel.cancel();+ jobs.finish(&handle.id, Ok(BackfillReceipt { enqueued: 0 }))+ .await+ .expect("finish");++ let snap = jobs.snapshot(&handle.id).await.expect("snapshot").unwrap();+ assert_eq!(snap.status, JobStatus::Cancelled);+ assert!(snap.finished_at.is_some());+}++#[tokio::test]+async fn finish_err_records_failure_message() {+ let Some(jobs) = try_jobs().await else {+ eprintln!("skipping: dynamodb-local not reachable at {LOCAL_ENDPOINT}");+ return;+ };+ let handle = jobs.start("documents").await.expect("start");+ jobs.finish(+ &handle.id,+ Err(BackfillError::Source(anyhow::anyhow!("boom"))),+ )+ .await+ .expect("finish");++ let snap = jobs.snapshot(&handle.id).await.expect("snapshot").unwrap();+ assert_eq!(snap.status, JobStatus::Failed);+ assert!(+ snap.error+ .as_deref()+ .is_some_and(|e| e.contains("failed reading backfill source"))+ );+}++#[tokio::test]+async fn cancel_all_local_fires_every_local_token() {+ let Some(jobs) = try_jobs().await else {+ eprintln!("skipping: dynamodb-local not reachable at {LOCAL_ENDPOINT}");+ return;+ };+ let a = jobs.start("calls").await.expect("a");+ let b = jobs.start("chats").await.expect("b");++ jobs.cancel_all_local();++ assert!(a.cancel.is_cancelled());+ assert!(b.cancel.is_cancelled());+}++#[tokio::test]+async fn snapshot_returns_none_for_unknown_id() {+ let Some(jobs) = try_jobs().await else {+ eprintln!("skipping: dynamodb-local not reachable at {LOCAL_ENDPOINT}");+ return;+ };+ assert!(+ jobs.snapshot(&JobId::new())+ .await+ .expect("snapshot")+ .is_none()+ );+}++#[tokio::test]+async fn finish_drops_local_cancel_entry() {+ let Some(jobs) = try_jobs().await else {+ eprintln!("skipping: dynamodb-local not reachable at {LOCAL_ENDPOINT}");+ return;+ };+ let handle = jobs.start("emails").await.expect("start");+ let id = handle.id.clone();+ jobs.finish(&id, Ok(BackfillReceipt { enqueued: 0 }))+ .await+ .expect("finish");++ assert!(!jobs.local_cancels.lock().unwrap().contains_key(&id));+}diff --git a/rust/cloud-storage/search_processing_service/src/domain/service.rs b/rust/cloud-storage/search_processing_service/src/domain/service.rsindex 8ad73236c7..a4a6a409e9 100644--- a/rust/cloud-storage/search_processing_service/src/domain/service.rs+++ b/rust/cloud-storage/search_processing_service/src/domain/service.rs@@ -105,7 +105,7 @@ wherepublisher.publish(page.messages).await?;enqueued += page.rows_consumed;offset += page.rows_consumed;- progress.add(page.rows_consumed);+ progress.add(page.rows_consumed).await;}Ok(BackfillReceipt { enqueued })diff --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 ba73ea6779..4dae5b5108 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@@ -112,7 +112,7 @@ fn page(messages: Vec<SearchQueueMessage>) -> SourcePage {}fn detached() -> (JobProgress, CancellationToken) {- (JobProgress::default(), CancellationToken::new())+ (JobProgress::detached(), CancellationToken::new())}#[tokio::test]@@ -134,7 +134,7 @@ async fn drains_source_across_full_pages() {.unwrap();assert_eq!(receipt.enqueued, 15);- assert_eq!(progress.enqueued(), 15);+ assert_eq!(progress.local_count(), 15);assert_eq!(publisher.batch_count(), 3);assert_eq!(publisher.total_messages(), 15);assert_eq!(publisher.batch_sizes(), vec![5, 5, 5]);@@ -312,7 +312,7 @@ async fn cancel_between_pages_stops_drain_after_current_page() {.unwrap();assert_eq!(receipt.enqueued, 5);- assert_eq!(progress.enqueued(), 5);+ assert_eq!(progress.local_count(), 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 d97eeea461..d8f61e2198 100644--- a/rust/cloud-storage/search_processing_service/src/main.rs+++ b/rust/cloud-storage/search_processing_service/src/main.rs@@ -196,7 +196,18 @@ async fn main() -> anyhow::Result<()> {run_search_processing_workers(ctx, config.worker_count);}- let backfill_jobs = BackfillJobs::new();+ let dynamodb_client = aws_sdk_dynamodb::Client::new(&aws_config);+ let backfill_jobs = BackfillJobs::new(+ dynamodb_client,+ config.backfill_jobs_table.clone(),+ std::time::Duration::from_secs(config.backfill_job_ttl_seconds),+ );+ if matches!(config.environment, Environment::Local) {+ backfill_jobs+ .ensure_table()+ .await+ .context("failed to ensure backfill jobs table exists")?;+ }api::setup_and_serve(ApiContext {db,