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
feat(ai): projection poller (#4245)
Will Hutchinson82c06bef706e
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex fc7eae997a..08aff259e3 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -17,11 +17,39 @@"workspace-hack"],"ai_projections": [+ "agent","ai_projections",+ "ai_toolset",+ "ai_usage",+ "attachment",+ "authentication_service_client","cowlike",+ "crm",+ "document_sub_type",+ "email",+ "email_utils",+ "entity_access",+ "filter_ast",+ "frecency",+ "item_filters",+ "macro_env_var","macro_user_id",+ "macro_uuid",+ "model",+ "model-entity","model-error-response",+ "model_file_type","model_user",+ "models_ai_projection",+ "models_bulk_upload",+ "models_email",+ "models_pagination",+ "models_permissions",+ "non_empty",+ "s3_key",+ "sqs_client",+ "sqs_worker",+ "unfurl","workspace-hack"],"ai_tools": [@@ -78,6 +106,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -217,6 +246,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -329,6 +359,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -400,6 +431,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -485,6 +517,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -565,6 +598,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -655,6 +689,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -888,6 +923,7 @@"model-error-response","model_file_type","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -1001,6 +1037,7 @@"model-error-response","model_file_type","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -1082,6 +1119,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -1195,6 +1233,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -1341,6 +1380,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -1421,6 +1461,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -1483,6 +1524,7 @@"model-error-response","model_file_type","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -1601,6 +1643,7 @@"model-error-response","model_file_type","model_user",+ "models_ai_projection","models_bulk_upload","models_email","models_pagination",@@ -1638,6 +1681,7 @@"model-error-response","model_file_type","model_user",+ "models_ai_projection","models_bulk_upload","models_email","models_pagination",@@ -1693,6 +1737,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -1777,6 +1822,7 @@"model-error-response","model_file_type","model_user",+ "models_ai_projection","models_bulk_upload","models_email","models_pagination",@@ -1979,6 +2025,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -2160,6 +2207,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -2465,6 +2513,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -2560,6 +2609,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -2673,6 +2723,10 @@"model_user","workspace-hack"],+ "models_ai_projection": [+ "models_ai_projection",+ "workspace-hack"+ ],"models_bulk_upload": ["models_bulk_upload","workspace-hack"@@ -2760,6 +2814,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -2838,6 +2893,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -3050,6 +3106,7 @@"model-error-response","model_file_type","model_user",+ "models_ai_projection","models_bulk_upload","models_email","models_pagination",@@ -3087,6 +3144,7 @@"model-error-response","model_file_type","model_user",+ "models_ai_projection","models_bulk_upload","models_email","models_pagination",@@ -3318,6 +3376,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -3410,6 +3469,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -3486,6 +3546,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -3561,6 +3622,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -3617,6 +3679,7 @@"model-error-response","model_file_type","model_user",+ "models_ai_projection","models_bulk_upload","models_email","models_pagination",@@ -3680,6 +3743,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -3779,6 +3843,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -3829,6 +3894,7 @@"model-error-response","model_file_type","model_user",+ "models_ai_projection","models_bulk_upload","models_email","models_pagination",@@ -3992,6 +4058,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_dcs","models_email",@@ -4052,6 +4119,7 @@"model_file_type","model_notifications","model_user",+ "models_ai_projection","models_bulk_upload","models_email","models_pagination",@@ -4114,6 +4182,7 @@"model-error-response","model_file_type","model_user",+ "models_ai_projection","models_bulk_upload","models_email","models_pagination",@@ -4152,6 +4221,7 @@"model-error-response","model_file_type","model_user",+ "models_ai_projection","models_bulk_upload","models_email","models_pagination",diff --git a/docker-compose.local-e2e.yml b/docker-compose.local-e2e.ymlindex 745d931670..482df4bb75 100644--- a/docker-compose.local-e2e.yml+++ b/docker-compose.local-e2e.yml@@ -42,6 +42,7 @@ x-local-e2e-env: &local-e2e-envNOTIFICATION_INGRESS_QUEUE: http://localstack:4566/000000000000/notification-ingress-queuePUSH_NOTIFICATION_EVENT_HANDLER_QUEUE: push-delivery-queueSEARCH_EVENT_QUEUE: search-event-queue+ AI_PROJECTION_QUEUE: http://localstack:4566/000000000000/ai-projection-queueSFS_DELETE_QUEUE: email-sfs-delete-queueSFS_UPLOADER_QUEUE: email-service-sfs-mapper-queueSTATIC_FILE_SERVICE_S3_EVENT_QUEUE_URL: http://localstack:4566/000000000000/static-file-s3-event-notification-queuediff --git a/infra/stacks/document-cognition-service/document-cognition-service.ts b/infra/stacks/document-cognition-service/document-cognition-service.tsindex b45733e344..beb2ce7351 100644--- a/infra/stacks/document-cognition-service/document-cognition-service.ts+++ b/infra/stacks/document-cognition-service/document-cognition-service.ts@@ -155,6 +155,7 @@ export class DocumentCognitionService extends pulumi.ComponentResource {{Action: ['sqs:SendMessage',+ 'sqs:ReceiveMessage','sqs:DeleteMessage','sqs:GetQueueAttributes',],diff --git a/infra/stacks/document-cognition-service/index.ts b/infra/stacks/document-cognition-service/index.tsindex be5fb6f951..ca12e1fa2f 100644--- a/infra/stacks/document-cognition-service/index.ts+++ b/infra/stacks/document-cognition-service/index.ts@@ -10,6 +10,7 @@ import {ServiceUrl,stack,} from '../../packages/shared';+import { Queue } from '../../packages/resources';import { get_coparse_api_vpc } from '../../packages/vpc';import {DocumentCognitionService,@@ -159,6 +160,17 @@ const { notificationIngressQueueName, notificationIngressQueueArn } =const { searchEventQueueName, searchEventQueueArn } = getSearchEventQueue();+// ── AI projection queue ──────────────────────────────────────────────────────+// This service both produces (on upsert) and consumes (via the inbound worker)+// ai projection materialization messages, so the queue is owned here. The Queue+// component provisions the queue, its DLQ, and the associated alarms.+const aiProjectionQueue = new Queue('ai-projection', {+ tags,+ maxReceiveCount: 2,+ // Give each message up to 2 minutes to process before it's re-queued.+ visibilityTimeoutSeconds: 120,+});+const MACRO_API_TOKENS = getMacroApiToken();const documentCognitionService = new DocumentCognitionService(@@ -185,6 +197,7 @@ const documentCognitionService = new DocumentCognitionService(deleteChatQueueArn,searchEventQueueArn,notificationIngressQueueArn,+ aiProjectionQueue.queue.arn,...aiTools.queueArns,],connectionTablePolicyArn: connectionGatewayTablePolicyArn,@@ -243,6 +256,10 @@ const documentCognitionService = new DocumentCognitionService(name: 'SEARCH_EVENT_QUEUE',value: pulumi.interpolate`${searchEventQueueName}`,},+ {+ name: 'AI_PROJECTION_QUEUE',+ value: pulumi.interpolate`${aiProjectionQueue.queue.name}`,+ },{name: 'MACRO_API_TOKEN_ISSUER',value: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenIssuer}`,@@ -297,3 +314,5 @@ export const documentCognitionServiceAlbSgId =export const documentCognitionServiceUrl = pulumi.interpolate`${documentCognitionService.domain}`;export const documentCognitionServiceRoleArn =documentCognitionService.role.arn;+export const aiProjectionQueueArn = aiProjectionQueue.queue.arn;+export const aiProjectionQueueName = aiProjectionQueue.queue.name;diff --git a/local_stack.just b/local_stack.justindex 4833071cc4..bb32b2a156 100644--- a/local_stack.just+++ b/local_stack.just@@ -43,6 +43,7 @@ create_local_queues:aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name email-service-gmail-ops-retry-queue || trueaws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name email-service-refresh-queue || trueaws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name search-event-queue || true+ aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name ai-projection-queue || trueaws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name email-sfs-delete-queue || trueaws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name email-service-sfs-mapper-queue || trueaws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name static-file-s3-event-notification-queue || truediff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 01c91312e9..3739506b48 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -99,6 +99,7 @@ name = "ai_projections"version = "0.1.0"dependencies = ["anyhow",+ "aws-sdk-sqs","axum","chrono","http-body-util",@@ -106,10 +107,13 @@ dependencies = ["macro_user_id","model-error-response","model_user",+ "models_ai_projection","serde","serde_json","sha2 0.10.9","sqlx",+ "sqs_client",+ "sqs_worker","thiserror 2.0.18","tokio","tower 0.5.3",@@ -3567,6 +3571,7 @@ dependencies = ["soup","sqlx","sqs_client",+ "sqs_worker","static_file","stream","strum",@@ -7590,6 +7595,14 @@ dependencies = ["workspace-hack",]+[[package]]+name = "models_ai_projection"+version = "0.1.0"+dependencies = [+ "serde",+ "workspace-hack",+]+[[package]]name = "models_bulk_upload"version = "0.1.0"@@ -11725,6 +11738,7 @@ dependencies = ["email","futures","model",+ "models_ai_projection","models_email","s3_key","serde",diff --git a/rust/cloud-storage/ai_projections/Cargo.toml b/rust/cloud-storage/ai_projections/Cargo.tomlindex d556dc40cd..732ddfe444 100644--- a/rust/cloud-storage/ai_projections/Cargo.toml+++ b/rust/cloud-storage/ai_projections/Cargo.toml@@ -11,19 +11,28 @@ axum = ["dep:model_user","dep:utoipa",]-default = ["axum", "inbound", "outbound", "ports"]+default = ["axum", "inbound", "outbound", "ports", "worker"]inbound = ["axum", "ports"]outbound = ["dep:sqlx",+ "dep:sqs_client",+ "dep:serde_json","ports",]ports = ["dep:tokio"]+worker = [+ "ports",+ "dep:sqs_worker",+ "dep:aws-sdk-sqs",+ "dep:serde_json",+][dependencies]# Coreanyhow = { workspace = true }chrono = { workspace = true }macro_user_id = { path = "../macro_user_id" }+models_ai_projection = { path = "../models_ai_projection" }serde = { workspace = true }sha2 = { workspace = true }thiserror = { workspace = true }@@ -42,6 +51,14 @@ utoipa = { workspace = true, optional = true }# Outbound dependenciessqlx = { workspace = true, optional = true }+sqs_client = { path = "../sqs_client", default-features = false, features = [+ "ai_projection",+], optional = true }++# Worker (inbound SQS poller) dependencies+sqs_worker = { path = "../sqs_worker", optional = true }+aws-sdk-sqs = { workspace = true, optional = true }+serde_json = { workspace = true, optional = true }[dev-dependencies]http-body-util = { workspace = true }diff --git a/rust/cloud-storage/ai_projections/src/domain.rs b/rust/cloud-storage/ai_projections/src/domain.rsindex cb85d0f9ee..715c37cdd0 100644--- a/rust/cloud-storage/ai_projections/src/domain.rs+++ b/rust/cloud-storage/ai_projections/src/domain.rs@@ -1,5 +1,6 @@//! Contains the domain logic for ai projections+pub mod ai_projection_queue;pub mod ai_projection_repo;pub mod ai_projection_service;pub mod model;diff --git a/rust/cloud-storage/ai_projections/src/domain/ai_projection_queue.rs b/rust/cloud-storage/ai_projections/src/domain/ai_projection_queue.rsnew file mode 100644index 0000000000..cda05a3a5e--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/domain/ai_projection_queue.rs@@ -0,0 +1,15 @@+//! Outbound port for enqueueing ai projection materialization requests.++use models_ai_projection::AiProjectionQueueMessage;++use crate::domain::model::AiProjectionError;++/// The AiProjectionQueue defines how the service hands off a projection+/// instance for asynchronous materialization (e.g. by enqueueing onto SQS).+pub trait AiProjectionQueue: Clone + Send + Sync + 'static {+ /// Enqueues a request to materialize the referenced projection instance.+ fn enqueue_materialization(+ &self,+ message: AiProjectionQueueMessage,+ ) -> impl Future<Output = Result<(), AiProjectionError>> + Send;+}diff --git a/rust/cloud-storage/ai_projections/src/domain/ai_projection_service.rs b/rust/cloud-storage/ai_projections/src/domain/ai_projection_service.rsindex 2ae7c5c1cc..e8d9e6a4f8 100644--- a/rust/cloud-storage/ai_projections/src/domain/ai_projection_service.rs+++ b/rust/cloud-storage/ai_projections/src/domain/ai_projection_service.rs@@ -4,13 +4,15 @@mod test;use macro_user_id::user_id::MacroUserIdStr;+use models_ai_projection::AiProjectionQueueMessage;use sha2::{Digest, Sha256};use crate::domain::{+ ai_projection_queue::AiProjectionQueue,ai_projection_repo::AiProjectionRepository,model::{- AiProjectionError, TargetType, UpsertProjectionError, UpsertProjectionParams,- UserAiProjection,+ AiProjectionError, ProjectionStatus, TargetType, UpsertProjectionError,+ UpsertProjectionParams, UserAiProjection,},};@@ -34,24 +36,37 @@ pub trait AiProjectionService: Clone + Send + Sync + 'static {&self,user_id: &MacroUserIdStr<'_>,) -> impl Future<Output = Result<bool, AiProjectionError>> + Send;++ /// Materializes the projection instance referenced by the queue message.+ ///+ /// This is invoked by the inbound worker for each dequeued message and is+ /// responsible for (eventually) generating the AI result and persisting it.+ fn materialize(+ &self,+ message: AiProjectionQueueMessage,+ ) -> impl Future<Output = Result<(), AiProjectionError>> + Send;}-/// Implementation of [`AiProjectionService`] backed by an [`AiProjectionRepository`].+/// Implementation of [`AiProjectionService`] backed by an+/// [`AiProjectionRepository`] and an [`AiProjectionQueue`].#[derive(Debug, Clone)]-pub struct AiProjectionServiceImpl<R>+pub struct AiProjectionServiceImpl<R, Q>whereR: AiProjectionRepository,+ Q: AiProjectionQueue,{repository: R,+ queue: Q,}-impl<R> AiProjectionServiceImpl<R>+impl<R, Q> AiProjectionServiceImpl<R, Q>whereR: AiProjectionRepository,+ Q: AiProjectionQueue,{/// Creates a new AiProjectionServiceImpl.- pub fn new(repository: R) -> Self {- Self { repository }+ pub fn new(repository: R, queue: Q) -> Self {+ Self { repository, queue }}/// Resolves the concrete target id from the authenticated user and the@@ -92,9 +107,10 @@ pub fn hash_prompt(prompt: &str) -> String {hex}-impl<R> AiProjectionService for AiProjectionServiceImpl<R>+impl<R, Q> AiProjectionService for AiProjectionServiceImpl<R, Q>whereR: AiProjectionRepository,+ Q: AiProjectionQueue,{#[tracing::instrument(skip(self), err)]async fn upsert_projection(@@ -134,6 +150,23 @@ where.get_or_create_target_projection(&projection.id, &target_id, &projection.prompt_hash).await?;+ // A cold instance has no materialized result yet, so request async+ // materialization. The instance already exists, so a failed enqueue is+ // logged and swallowed rather than failing the request.+ if target_projection.status == ProjectionStatus::Cold {+ self.queue+ .enqueue_materialization(AiProjectionQueueMessage {+ ai_projection_id: target_projection.ai_projection_id.clone(),+ target_id: target_projection.target_id.clone(),+ prompt_hash: target_projection.prompt_hash.clone(),+ })+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, "failed to enqueue ai projection materialization");+ })+ .ok();+ }+Ok(target_projection)}@@ -146,4 +179,22 @@ where.user_has_permission(user_id, READ_PROFESSIONAL_FEATURES).await}++ #[tracing::instrument(skip(self), err)]+ async fn materialize(+ &self,+ message: AiProjectionQueueMessage,+ ) -> Result<(), AiProjectionError> {+ tracing::info!(+ ai_projection_id = %message.ai_projection_id,+ target_id = %message.target_id,+ prompt_hash = %message.prompt_hash,+ "materializing ai projection"+ );++ // TODO: load the target projection, mark it as Loading/Refreshing, call+ // the LLM to generate the result, and persist it with status=Ready (or+ // status=Error on failure). This currently only acknowledges the message.+ Ok(())+ }}diff --git a/rust/cloud-storage/ai_projections/src/domain/ai_projection_service/test.rs b/rust/cloud-storage/ai_projections/src/domain/ai_projection_service/test.rsindex d79e1ed46e..5a6d737da9 100644--- a/rust/cloud-storage/ai_projections/src/domain/ai_projection_service/test.rs+++ b/rust/cloud-storage/ai_projections/src/domain/ai_projection_service/test.rs@@ -2,8 +2,10 @@ use std::sync::{Arc, Mutex};use chrono::Utc;use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use models_ai_projection::AiProjectionQueueMessage;use crate::domain::{+ ai_projection_queue::AiProjectionQueue,ai_projection_repo::AiProjectionRepository,ai_projection_service::{AiProjectionService, AiProjectionServiceImpl, hash_prompt},model::{@@ -12,6 +14,27 @@ use crate::domain::{},};+/// A tiny in-memory mock queue that records enqueued materialization messages.+#[derive(Clone, Default)]+struct MockQueue {+ enqueued: Arc<Mutex<Vec<AiProjectionQueueMessage>>>,+}++impl AiProjectionQueue for MockQueue {+ async fn enqueue_materialization(+ &self,+ message: AiProjectionQueueMessage,+ ) -> Result<(), AiProjectionError> {+ self.enqueued.lock().unwrap().push(message);+ Ok(())+ }+}++/// Builds a service from a repo, using a default mock queue.+fn service_with(repo: MockRepo) -> AiProjectionServiceImpl<MockRepo, MockQueue> {+ AiProjectionServiceImpl::new(repo, MockQueue::default())+}+/// A tiny in-memory mock repository for exercising the service layer.#[derive(Clone, Default)]struct MockRepo {@@ -100,13 +123,13 @@ fn hash_prompt_is_deterministic_and_hex() {#[tokio::test]async fn has_professional_features_delegates_to_repo() {- let service = AiProjectionServiceImpl::new(MockRepo {+ let service = service_with(MockRepo {has_permission: true,..Default::default()});assert!(service.has_professional_features(&user_id()).await.unwrap());- let service = AiProjectionServiceImpl::new(MockRepo {+ let service = service_with(MockRepo {has_permission: false,..Default::default()});@@ -126,7 +149,7 @@ fn user_params(id: &str, prompt: &str) -> UpsertProjectionParams {#[tokio::test]async fn upsert_projection_creates_cold_target_instance_for_user() {let repo = MockRepo::default();- let service = AiProjectionServiceImpl::new(repo.clone());+ let service = service_with(repo.clone());let target_projection = service.upsert_projection(@@ -147,6 +170,40 @@ async fn upsert_projection_creates_cold_target_instance_for_user() {assert_eq!(repo.created_target_projections.lock().unwrap().len(), 1);}+#[tokio::test]+async fn upsert_projection_enqueues_materialization_for_cold_instance() {+ let repo = MockRepo::default();+ let queue = MockQueue::default();+ let service = AiProjectionServiceImpl::new(repo, queue.clone());++ service+ .upsert_projection(+ &user_id(),+ user_params("inbox/important", "What is important?"),+ )+ .await+ .unwrap();++ let enqueued = queue.enqueued.lock().unwrap();+ assert_eq!(enqueued.len(), 1);+ assert_eq!(enqueued[0].ai_projection_id, "inbox/important");+ assert_eq!(enqueued[0].target_id, "macro|[email protected]");+ assert_eq!(enqueued[0].prompt_hash, hash_prompt("What is important?"));+}++#[tokio::test]+async fn materialize_acknowledges_message() {+ let service = service_with(MockRepo::default());+ service+ .materialize(AiProjectionQueueMessage {+ ai_projection_id: "inbox/important".to_string(),+ target_id: "macro|[email protected]".to_string(),+ prompt_hash: hash_prompt("What is important?"),+ })+ .await+ .unwrap();+}+#[tokio::test]async fn upsert_projection_resolves_team_target_from_user() {let team_id = uuid::Uuid::new_v4();@@ -154,7 +211,7 @@ async fn upsert_projection_resolves_team_target_from_user() {team_ids: vec![team_id],..Default::default()};- let service = AiProjectionServiceImpl::new(repo.clone());+ let service = service_with(repo.clone());let target_projection = service.upsert_projection(@@ -176,7 +233,7 @@ async fn upsert_projection_resolves_team_target_from_user() {#[tokio::test]async fn upsert_projection_team_target_errors_without_exactly_one_team() {// Zero teams -> bad request.- let service = AiProjectionServiceImpl::new(MockRepo::default());+ let service = service_with(MockRepo::default());let err = service.upsert_projection(&user_id(),@@ -193,7 +250,7 @@ async fn upsert_projection_team_target_errors_without_exactly_one_team() {assert!(matches!(err, UpsertProjectionError::BadRequest(_)));// Multiple teams -> ambiguous bad request.- let service = AiProjectionServiceImpl::new(MockRepo {+ let service = service_with(MockRepo {team_ids: vec![uuid::Uuid::new_v4(), uuid::Uuid::new_v4()],..Default::default()});@@ -215,7 +272,7 @@ async fn upsert_projection_team_target_errors_without_exactly_one_team() {#[tokio::test]async fn upsert_projection_rejects_empty_id_and_prompt() {- let service = AiProjectionServiceImpl::new(MockRepo::default());+ let service = service_with(MockRepo::default());let err = service.upsert_projection(&user_id(), user_params(" ", "valid"))diff --git a/rust/cloud-storage/ai_projections/src/inbound/axum_router/test.rs b/rust/cloud-storage/ai_projections/src/inbound/axum_router/test.rsindex 816e78cb48..18729ec3ed 100644--- a/rust/cloud-storage/ai_projections/src/inbound/axum_router/test.rs+++ b/rust/cloud-storage/ai_projections/src/inbound/axum_router/test.rs@@ -46,6 +46,13 @@ impl AiProjectionService for MockService {) -> Result<bool, AiProjectionError> {Ok(self.has_permission)}++ async fn materialize(+ &self,+ _message: models_ai_projection::AiProjectionQueueMessage,+ ) -> Result<(), AiProjectionError> {+ Ok(())+ }}fn test_user_context() -> UserContext {diff --git a/rust/cloud-storage/ai_projections/src/lib.rs b/rust/cloud-storage/ai_projections/src/lib.rsindex 6907fa30d9..7f1eb3034a 100644--- a/rust/cloud-storage/ai_projections/src/lib.rs+++ b/rust/cloud-storage/ai_projections/src/lib.rs@@ -23,3 +23,7 @@ pub mod inbound;/// The outbound module contains the outbound adapters for ai projections#[cfg(feature = "outbound")]pub mod outbound;++/// The worker module contains the inbound SQS poller for ai projections+#[cfg(feature = "worker")]+pub mod worker;diff --git a/rust/cloud-storage/ai_projections/src/outbound.rs b/rust/cloud-storage/ai_projections/src/outbound.rsindex 5d86bc5af7..1dce3f4614 100644--- a/rust/cloud-storage/ai_projections/src/outbound.rs+++ b/rust/cloud-storage/ai_projections/src/outbound.rs@@ -1,3 +1,4 @@//! Outbound adapters for the ai projections domain.pub mod ai_projection_repo;+pub mod sqs_queue;diff --git a/rust/cloud-storage/ai_projections/src/outbound/sqs_queue.rs b/rust/cloud-storage/ai_projections/src/outbound/sqs_queue.rsnew file mode 100644index 0000000000..c81204adbe--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/outbound/sqs_queue.rs@@ -0,0 +1,17 @@+//! SQS-backed implementation of the [`AiProjectionQueue`] outbound port.++use models_ai_projection::AiProjectionQueueMessage;+use sqs_client::SQS;++use crate::domain::{ai_projection_queue::AiProjectionQueue, model::AiProjectionError};++impl AiProjectionQueue for SQS {+ async fn enqueue_materialization(+ &self,+ message: AiProjectionQueueMessage,+ ) -> Result<(), AiProjectionError> {+ self.enqueue_ai_projection_message(message)+ .await+ .map_err(AiProjectionError::StorageLayerError)+ }+}diff --git a/rust/cloud-storage/ai_projections/src/worker.rs b/rust/cloud-storage/ai_projections/src/worker.rsnew file mode 100644index 0000000000..ee679110e6--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/worker.rs@@ -0,0 +1,67 @@+//! Inbound SQS worker that polls `ai_projection_queue` and materializes the+//! referenced projection instances via the [`AiProjectionService`].++#[cfg(test)]+mod test;++use anyhow::Context;+use models_ai_projection::AiProjectionQueueMessage;+use sqs_worker::SQSWorker;++use crate::domain::ai_projection_service::AiProjectionService;++/// SQS-based worker that polls for ai projection materialization messages and+/// delegates processing to the [`AiProjectionService`].+pub struct AiProjectionWorker<S: AiProjectionService> {+ sqs: SQSWorker,+ service: S,+}++impl<S: AiProjectionService> AiProjectionWorker<S> {+ /// Creates a new worker with the given SQS client and service.+ pub fn new(sqs: SQSWorker, service: S) -> Self {+ Self { sqs, service }+ }++ /// Polls SQS indefinitely, processing each received message.+ #[tracing::instrument(skip(self))]+ pub async fn poll(&self) {+ tracing::info!("initiated ai projection worker");+ loop {+ tracing::trace!("polling for messages");+ match self.sqs.receive_messages().await {+ Ok(messages) => {+ if messages.is_empty() {+ tracing::trace!("no messages found");+ continue;+ }+ for message in messages {+ if let Err(e) = self.process_message(&message).await {+ tracing::error!(error=?e, "error processing message");+ }+ }+ }+ Err(e) => {+ tracing::error!(error=?e, "error receiving messages");+ }+ }+ }+ }++ #[tracing::instrument(skip(self, message), fields(message_id = message.message_id), err)]+ async fn process_message(&self, message: &aws_sdk_sqs::types::Message) -> anyhow::Result<()> {+ let parsed = parse_message(message)?;+ self.service.materialize(parsed).await?;+ self.sqs.cleanup_message(message).await?;+ Ok(())+ }+}++/// Extracts and deserializes the body of an SQS message into an+/// [`AiProjectionQueueMessage`].+fn parse_message(+ message: &aws_sdk_sqs::types::Message,+) -> anyhow::Result<AiProjectionQueueMessage> {+ let body = message.body().context("message body is empty")?;+ serde_json::from_str(body).context("failed to deserialize ai projection queue message")+}diff --git a/rust/cloud-storage/ai_projections/src/worker/test.rs b/rust/cloud-storage/ai_projections/src/worker/test.rsnew file mode 100644index 0000000000..1f4fefc17a--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/worker/test.rs@@ -0,0 +1,34 @@+use aws_sdk_sqs::types::Message;+use models_ai_projection::AiProjectionQueueMessage;++use super::parse_message;++fn sqs_message(body: &str) -> Message {+ Message::builder().body(body).build()+}++#[test]+fn parse_message_deserializes_valid_body() {+ let original = AiProjectionQueueMessage {+ ai_projection_id: "inbox/important".to_string(),+ target_id: "macro|[email protected]".to_string(),+ prompt_hash: "abc123".to_string(),+ };+ let body = serde_json::to_string(&original).unwrap();++ let parsed = parse_message(&sqs_message(&body)).unwrap();++ assert_eq!(parsed.ai_projection_id, original.ai_projection_id);+ assert_eq!(parsed.target_id, original.target_id);+ assert_eq!(parsed.prompt_hash, original.prompt_hash);+}++#[test]+fn parse_message_errors_on_malformed_body() {+ assert!(parse_message(&sqs_message("not json")).is_err());+}++#[test]+fn parse_message_errors_on_empty_body() {+ assert!(parse_message(&Message::builder().build()).is_err());+}diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.tomlindex f2c11a1c02..690a24f949 100644--- a/rust/cloud-storage/document_cognition_service/Cargo.toml+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml@@ -108,12 +108,14 @@ serde_json = { workspace = true }soup = { path = "../soup", features = ["outbound"] }sqlx = { workspace = true }sqs_client = { path = "../sqs_client", default-features = false, features = [+ "ai_projection","chat","document_text_extractor","email","gmail","search",] }+sqs_worker = { path = "../sqs_worker" }static_file = { path = "../static_file", features = ["attachment"] }stream = { path = "../stream" }strum = { workspace = true }diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rsindex 565eee0821..d5088820c2 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs@@ -58,10 +58,12 @@ pub type DcsMemoryService =pub type DcsUsageService =ai_usage::domain::service::UsageServiceImpl<ai_usage::outbound::PgUsageRepo>;-/// The AI projections service wired to the Postgres projection repo.+/// The AI projections service wired to the Postgres projection repo and the SQS+/// materialization queue.pub type DcsAiProjectionService =ai_projections::domain::ai_projection_service::AiProjectionServiceImpl<ai_projections::outbound::ai_projection_repo::AiProjectionRepositoryImpl,+ sqs_client::SQS,>;/// Concrete MCP router state for DCS.diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rsindex 0abf596505..3b5f8de475 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs@@ -352,6 +352,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arai_projections::outbound::ai_projection_repo::AiProjectionRepositoryImpl::new(pool.clone(),),+ sqs_client.clone(),),);diff --git a/rust/cloud-storage/document_cognition_service/src/config.rs b/rust/cloud-storage/document_cognition_service/src/config.rsindex 2aba36183b..f79d1929c6 100644--- a/rust/cloud-storage/document_cognition_service/src/config.rs+++ b/rust/cloud-storage/document_cognition_service/src/config.rs@@ -37,6 +37,8 @@ pub struct Config {/// The sqs queue to send notifications topub notification_queue: String,pub search_event_queue: String,+ /// The sqs queue used to enqueue and poll ai projection materialization jobs+ pub ai_projection_queue: String,pub sync_service_url: String,pub sync_service_auth_key: String,pub lexical_service_url: String,@@ -75,6 +77,7 @@ env_var!(pub NotificationQueue,pub DocumentStorageServiceAuthKey,pub SearchEventQueue,+ pub AiProjectionQueue,pub SyncServiceAuthKey,pub AuthenticationServiceUrl,pub AuthenticationServiceSecretKey,@@ -125,6 +128,7 @@ impl Config {notification_queue,document_storage_service_auth_key,search_event_queue,+ ai_projection_queue,sync_service_auth_key,authentication_service_url,authentication_service_secret_key,@@ -149,6 +153,7 @@ impl Config {email_scheduled_queue: email_scheduled_queue.to_string(),notification_queue: notification_queue.to_string(),search_event_queue: search_event_queue.to_string(),+ ai_projection_queue: ai_projection_queue.to_string(),sync_service_auth_key: sync_service_auth_key.to_string(),sync_service_url,lexical_service_url,@@ -185,6 +190,7 @@ impl Config {email_scheduled_queue: Default::default(),notification_queue: Default::default(),search_event_queue: Default::default(),+ ai_projection_queue: Default::default(),sync_service_url: Default::default(),sync_service_auth_key: Default::default(),lexical_service_url: Default::default(),diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex c27923005c..3b46623063 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -88,7 +88,8 @@ async fn main() -> anyhow::Result<()> {.document_text_extractor_queue(&config.document_text_extractor_queue).chat_delete_queue(&config.chat_delete_queue).email_scheduled_queue(&config.email_scheduled_queue)- .search_event_queue(&config.search_event_queue);+ .search_event_queue(&config.search_event_queue)+ .ai_projection_queue(&config.ai_projection_queue);let secretsmanager_client = secretsmanager_client::SecretsManager::new(aws_sdk_secretsmanager::Client::new(&aws_config),@@ -412,13 +413,30 @@ async fn main() -> anyhow::Result<()> {tracing::info!("initialized ai cost service");- let ai_projections_service = Arc::new(+ let ai_projections_service_impl =ai_projections::domain::ai_projection_service::AiProjectionServiceImpl::new(ai_projections::outbound::ai_projection_repo::AiProjectionRepositoryImpl::new(db.clone(),),+ sqs_client.clone(),+ );++ // Spawn the inbound worker that polls ai_projection_queue and materializes+ // projection instances. It owns its own clone of the service.+ let ai_projection_worker = ai_projections::worker::AiProjectionWorker::new(+ sqs_worker::SQSWorker::new(+ aws_sdk_sqs::Client::new(&aws_config),+ config.ai_projection_queue.clone(),+ 10,+ 10,),+ ai_projections_service_impl.clone(),);+ tokio::spawn(async move {+ ai_projection_worker.poll().await;+ });++ let ai_projections_service = Arc::new(ai_projections_service_impl);tracing::info!("initialized ai projections service");diff --git a/rust/cloud-storage/models_ai_projection/Cargo.toml b/rust/cloud-storage/models_ai_projection/Cargo.tomlnew file mode 100644index 0000000000..8eb6c46d2c--- /dev/null+++ b/rust/cloud-storage/models_ai_projection/Cargo.toml@@ -0,0 +1,9 @@+[package]+edition = "2024"+name = "models_ai_projection"+publish = false+version = "0.1.0"++[dependencies]+serde = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }diff --git a/rust/cloud-storage/models_ai_projection/src/lib.rs b/rust/cloud-storage/models_ai_projection/src/lib.rsnew file mode 100644index 0000000000..66fbb35360--- /dev/null+++ b/rust/cloud-storage/models_ai_projection/src/lib.rs@@ -0,0 +1,16 @@+#![deny(missing_docs)]+//! Shared message types for the ai projection queue.++use serde::{Deserialize, Serialize};++/// Message enqueued onto `ai_projection_queue` to request async materialization+/// of a per-target projection instance.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct AiProjectionQueueMessage {+ /// The id of the projection definition to materialize.+ pub ai_projection_id: String,+ /// The target (user id or team id) whose instance should be materialized.+ pub target_id: String,+ /// The prompt hash of the instance to materialize, used to detect staleness.+ pub prompt_hash: String,+}diff --git a/rust/cloud-storage/sqs_client/Cargo.toml b/rust/cloud-storage/sqs_client/Cargo.tomlindex 23b6c7c167..8bd735d13f 100644--- a/rust/cloud-storage/sqs_client/Cargo.toml+++ b/rust/cloud-storage/sqs_client/Cargo.toml@@ -5,9 +5,11 @@ publish = falseversion = "0.1.0"[features]+ai_projection = ["dep:models_ai_projection"]chat = []convert = ["model"]default = [+ "ai_projection","chat","convert","document",@@ -36,6 +38,7 @@ aws-sdk-sqs = { workspace = true }chrono = { workspace = true, optional = true }email = { path = "../email", features = ["ports"], optional = true }model = { path = "../model", optional = true }+models_ai_projection = { path = "../models_ai_projection", optional = true }s3_key = { path = "../s3_key" }models_email = { path = "../models_email", optional = true }serde = { workspace = true }diff --git a/rust/cloud-storage/sqs_client/src/ai_projection/mod.rs b/rust/cloud-storage/sqs_client/src/ai_projection/mod.rsnew file mode 100644index 0000000000..61bca40e29--- /dev/null+++ b/rust/cloud-storage/sqs_client/src/ai_projection/mod.rs@@ -0,0 +1,42 @@+use anyhow::Context;+use models_ai_projection::AiProjectionQueueMessage;++use crate::SQS;++impl SQS {+ /// Sets the ai_projection_queue.+ pub fn ai_projection_queue(mut self, ai_projection_queue: &str) -> Self {+ self.ai_projection_queue = Some(ai_projection_queue.to_string());+ self+ }++ /// Sends a message to the ai projection queue to trigger async+ /// materialization of the referenced per-target projection instance.+ #[tracing::instrument(skip(self), err)]+ pub async fn enqueue_ai_projection_message(+ &self,+ message: AiProjectionQueueMessage,+ ) -> anyhow::Result<()> {+ if let Some(ai_projection_queue) = &self.ai_projection_queue {+ return enqueue_ai_projection_message(&self.inner, ai_projection_queue, message).await;+ }+ anyhow::bail!("ai_projection_queue is not configured")+ }+}++#[tracing::instrument(skip(sqs_client), err)]+async fn enqueue_ai_projection_message(+ sqs_client: &aws_sdk_sqs::Client,+ queue_url: &str,+ message: AiProjectionQueueMessage,+) -> anyhow::Result<()> {+ let message_str = serde_json::to_string(&message).context("unable to serialize message")?;++ sqs_client+ .send_message()+ .queue_url(queue_url)+ .message_body(message_str)+ .send()+ .await?;+ Ok(())+}diff --git a/rust/cloud-storage/sqs_client/src/lib.rs b/rust/cloud-storage/sqs_client/src/lib.rsindex e2fc8a342c..8b05979497 100644--- a/rust/cloud-storage/sqs_client/src/lib.rs+++ b/rust/cloud-storage/sqs_client/src/lib.rs@@ -1,5 +1,8 @@mod message_attribute;+#[cfg(feature = "ai_projection")]+pub mod ai_projection;+#[cfg(feature = "chat")]pub mod chat;@@ -52,6 +55,8 @@ pub trait PrimaryId {#[derive(Clone, Debug)]pub struct SQS {inner: sqs::Client,+ #[cfg(feature = "ai_projection")]+ ai_projection_queue: Option<String>,#[cfg(feature = "organization_retention")]organization_retention_queue: Option<String>,#[cfg(feature = "document")]@@ -90,6 +95,8 @@ impl SQS {pub fn new(inner: sqs::Client) -> Self {Self {inner,+ #[cfg(feature = "ai_projection")]+ ai_projection_queue: None,#[cfg(feature = "organization_retention")]organization_retention_queue: None,#[cfg(feature = "document")]