Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(ai): add in processing of ai projections (#4262)

Will Hutchinson43d3f53412d2
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 08aff259e3..daffd5301a 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -19,37 +19,97 @@
"ai_projections": [
"agent",
"ai_projections",
+ "ai_tools",
"ai_toolset",
"ai_usage",
+ "anthropic",
"attachment",
"authentication_service_client",
+ "bot_id",
+ "call",
+ "channels",
+ "chat",
+ "connection",
+ "connection_gateway_client",
+ "connection_gateway_models",
+ "contacts",
"cowlike",
"crm",
+ "decode_jwt",
"document_sub_type",
+ "documents",
"email",
+ "email_db_client",
+ "email_service_client",
"email_utils",
+ "embedding",
"entity_access",
+ "entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
+ "foreign_entity",
"frecency",
+ "invite_email",
+ "ip_extractor",
"item_filters",
+ "last_online_tracker",
+ "lexical_client",
+ "macro_auth",
+ "macro_aws_config",
+ "macro_db_client",
+ "macro_entrypoint",
+ "macro_env",
"macro_env_var",
+ "macro_middleware",
+ "macro_service_urls",
"macro_user_id",
"macro_uuid",
+ "mention_utils",
"model",
"model-entity",
"model-error-response",
"model_file_type",
+ "model_notifications",
"model_user",
"models_ai_projection",
"models_bulk_upload",
+ "models_dcs",
"models_email",
+ "models_entity_access_management",
+ "models_grouping",
+ "models_opensearch",
"models_pagination",
"models_permissions",
+ "models_properties",
+ "models_search",
+ "models_search_cursor",
+ "models_soup",
+ "models_team",
"non_empty",
+ "notification",
+ "opensearch_client",
+ "opensearch_query_builder",
+ "prompt",
+ "properties",
+ "properties_db_client",
+ "rate_limit",
+ "readonly_pool",
+ "remote_env_var",
+ "roles_and_permissions",
"s3_key",
+ "search_service_client",
+ "secretsmanager_client",
+ "share_permission_db_utils",
+ "soup",
"sqs_client",
"sqs_worker",
+ "sync_service",
+ "sync_service_client",
+ "system_properties",
+ "task_dedup",
+ "teams",
"unfurl",
+ "user_quota",
"workspace-hack"
],
"ai_tools": [
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/aiFeature.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/aiFeature.ts
index 9ffe6b9cb2..0ba11787e5 100644
--- a/js/app/packages/service-clients/service-cognition/generated/schemas/aiFeature.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/aiFeature.ts
@@ -20,4 +20,5 @@ export const AiFeature = {
chat_rename: 'chat_rename',
call_summary: 'call_summary',
channel_bot: 'channel_bot',
+ ai_projection: 'ai_projection',
} as const;
diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.json
index a5b74c3f26..dbd764adb7 100644
--- a/js/app/packages/service-clients/service-cognition/openapi.json
+++ b/js/app/packages/service-clients/service-cognition/openapi.json
@@ -1609,7 +1609,8 @@
"dynamic_completions_api",
"chat_rename",
"call_summary",
- "channel_bot"
+ "channel_bot",
+ "ai_projection"
]
},
"AssistantMessagePart": {
diff --git a/rust/cloud-storage/.sqlx/query-01ee626a0234bc3bd1463f146588eeff4d4fb032d4b9f1153ef2415f50bdae2f.json b/rust/cloud-storage/.sqlx/query-01ee626a0234bc3bd1463f146588eeff4d4fb032d4b9f1153ef2415f50bdae2f.json
new file mode 100644
index 0000000000..e3117a619d
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-01ee626a0234bc3bd1463f146588eeff4d4fb032d4b9f1153ef2415f50bdae2f.json
@@ -0,0 +1,19 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE user_ai_projection\n SET status = $3, result = $4, error = NULL,\n generated_at = $5, stale_at = $6, updated_at = NOW()\n WHERE ai_projection_id = $1 AND target_id = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Timestamptz",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "01ee626a0234bc3bd1463f146588eeff4d4fb032d4b9f1153ef2415f50bdae2f"
+}
diff --git a/rust/cloud-storage/.sqlx/query-0c628b1df314ea96c6852c56c9750d59246c62988cff8134853a31e2530c68f8.json b/rust/cloud-storage/.sqlx/query-0c628b1df314ea96c6852c56c9750d59246c62988cff8134853a31e2530c68f8.json
new file mode 100644
index 0000000000..9202c8ff9f
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-0c628b1df314ea96c6852c56c9750d59246c62988cff8134853a31e2530c68f8.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO processing_ai_projections (ai_projection_id, target_id)\n VALUES ($1, $2)\n ON CONFLICT (ai_projection_id, target_id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "0c628b1df314ea96c6852c56c9750d59246c62988cff8134853a31e2530c68f8"
+}
diff --git a/rust/cloud-storage/.sqlx/query-3aea5be9ab63b6b45e9dffc5862c0981979a0a681228c15d0ae3d733f4713b3f.json b/rust/cloud-storage/.sqlx/query-3aea5be9ab63b6b45e9dffc5862c0981979a0a681228c15d0ae3d733f4713b3f.json
new file mode 100644
index 0000000000..c6270364f2
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-3aea5be9ab63b6b45e9dffc5862c0981979a0a681228c15d0ae3d733f4713b3f.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM processing_ai_projections\n WHERE created_at < NOW() - INTERVAL '15 minutes'\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "3aea5be9ab63b6b45e9dffc5862c0981979a0a681228c15d0ae3d733f4713b3f"
+}
diff --git a/rust/cloud-storage/.sqlx/query-72d0d313bd1d5d5ca355eca5ea3234dbd95d889530db194e055debddb4f1267e.json b/rust/cloud-storage/.sqlx/query-72d0d313bd1d5d5ca355eca5ea3234dbd95d889530db194e055debddb4f1267e.json
new file mode 100644
index 0000000000..63cde005ea
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-72d0d313bd1d5d5ca355eca5ea3234dbd95d889530db194e055debddb4f1267e.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM processing_ai_projections\n WHERE ai_projection_id = $1 AND target_id = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "72d0d313bd1d5d5ca355eca5ea3234dbd95d889530db194e055debddb4f1267e"
+}
diff --git a/rust/cloud-storage/.sqlx/query-8364d456e4f761bab46f4b144bef2d5553ac153e842e9aa4a8b38c270fb96c7f.json b/rust/cloud-storage/.sqlx/query-8364d456e4f761bab46f4b144bef2d5553ac153e842e9aa4a8b38c270fb96c7f.json
new file mode 100644
index 0000000000..30e481eb65
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-8364d456e4f761bab46f4b144bef2d5553ac153e842e9aa4a8b38c270fb96c7f.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE user_ai_projection\n SET status = $3, updated_at = NOW()\n WHERE ai_projection_id = $1 AND target_id = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "8364d456e4f761bab46f4b144bef2d5553ac153e842e9aa4a8b38c270fb96c7f"
+}
diff --git a/rust/cloud-storage/.sqlx/query-84fb3301148d3792bfca937697189ad987c7e885d3511cfe05458f238fab47ce.json b/rust/cloud-storage/.sqlx/query-84fb3301148d3792bfca937697189ad987c7e885d3511cfe05458f238fab47ce.json
deleted file mode 100644
index 24ee293f43..0000000000
--- a/rust/cloud-storage/.sqlx/query-84fb3301148d3792bfca937697189ad987c7e885d3511cfe05458f238fab47ce.json
+++ /dev/null
@@ -1,72 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT id, ai_projection_id, target_id, prompt_hash, status,\n result, error, generated_at, stale_at\n FROM user_ai_projection\n WHERE ai_projection_id = $1 AND target_id = $2 AND prompt_hash = $3\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "ai_projection_id",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "target_id",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "prompt_hash",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "status",
- "type_info": "Text"
- },
- {
- "ordinal": 5,
- "name": "result",
- "type_info": "Text"
- },
- {
- "ordinal": 6,
- "name": "error",
- "type_info": "Text"
- },
- {
- "ordinal": 7,
- "name": "generated_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 8,
- "name": "stale_at",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text",
- "Text"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- false,
- false,
- true,
- true,
- true,
- true
- ]
- },
- "hash": "84fb3301148d3792bfca937697189ad987c7e885d3511cfe05458f238fab47ce"
-}
diff --git a/rust/cloud-storage/.sqlx/query-99c9ad24f9161d5e905fff30e7be239d5346e410be2b8f4cabf6106cf5badbc8.json b/rust/cloud-storage/.sqlx/query-99c9ad24f9161d5e905fff30e7be239d5346e410be2b8f4cabf6106cf5badbc8.json
deleted file mode 100644
index 2bbca7918a..0000000000
--- a/rust/cloud-storage/.sqlx/query-99c9ad24f9161d5e905fff30e7be239d5346e410be2b8f4cabf6106cf5badbc8.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO user_ai_projection (id, ai_projection_id, target_id, prompt_hash, status)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (ai_projection_id, target_id, prompt_hash) DO NOTHING\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text",
- "Text",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "99c9ad24f9161d5e905fff30e7be239d5346e410be2b8f4cabf6106cf5badbc8"
-}
diff --git a/rust/cloud-storage/.sqlx/query-af8f1da403e88b09bf7ca62ae45e70927d33e28402ff66b8e8eeb39ab54f96ea.json b/rust/cloud-storage/.sqlx/query-af8f1da403e88b09bf7ca62ae45e70927d33e28402ff66b8e8eeb39ab54f96ea.json
new file mode 100644
index 0000000000..6ddf8e6caf
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-af8f1da403e88b09bf7ca62ae45e70927d33e28402ff66b8e8eeb39ab54f96ea.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE user_ai_projection\n SET status = $3, error = $4, updated_at = NOW()\n WHERE ai_projection_id = $1 AND target_id = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "af8f1da403e88b09bf7ca62ae45e70927d33e28402ff66b8e8eeb39ab54f96ea"
+}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 3739506b48..f07b936952 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -98,10 +98,15 @@ dependencies = [
name = "ai_projections"
version = "0.1.0"
dependencies = [
+ "agent",
+ "ai_tools",
+ "ai_toolset",
+ "ai_usage",
"anyhow",
"aws-sdk-sqs",
"axum",
"chrono",
+ "futures",
"http-body-util",
"macro_db_migrator",
"macro_user_id",
diff --git a/rust/cloud-storage/ai_projections/Cargo.toml b/rust/cloud-storage/ai_projections/Cargo.toml
index 732ddfe444..80985a4a5a 100644
--- a/rust/cloud-storage/ai_projections/Cargo.toml
+++ b/rust/cloud-storage/ai_projections/Cargo.toml
@@ -19,6 +19,16 @@ outbound = [
"dep:serde_json",
"ports",
]
+# Agent-backed projection generator (the outbound adapter that runs the AI
+# toolset). Pulls in the heavy agent/toolset dependencies.
+agent = [
+ "outbound",
+ "dep:ai_tools",
+ "dep:ai_toolset",
+ "dep:agent",
+ "dep:ai_usage",
+ "dep:futures",
+]
ports = ["dep:tokio"]
worker = [
"ports",
@@ -60,6 +70,13 @@ sqs_worker = { path = "../sqs_worker", optional = true }
aws-sdk-sqs = { workspace = true, optional = true }
serde_json = { workspace = true, optional = true }
+# Agent generator dependencies (the AI toolset adapter)
+ai_tools = { path = "../ai_tools", optional = true }
+ai_toolset = { path = "../ai_toolset", optional = true }
+agent = { path = "../agent", optional = true }
+ai_usage = { path = "../ai_usage", optional = true }
+futures = { workspace = true, optional = true }
+
[dev-dependencies]
http-body-util = { workspace = true }
macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/rust/cloud-storage/ai_projections/src/domain.rs b/rust/cloud-storage/ai_projections/src/domain.rs
index 715c37cdd0..2b2c73f2d7 100644
--- a/rust/cloud-storage/ai_projections/src/domain.rs
+++ b/rust/cloud-storage/ai_projections/src/domain.rs
@@ -4,3 +4,4 @@ pub mod ai_projection_queue;
pub mod ai_projection_repo;
pub mod ai_projection_service;
pub mod model;
+pub mod projection_generator;
diff --git a/rust/cloud-storage/ai_projections/src/domain/ai_projection_repo.rs b/rust/cloud-storage/ai_projections/src/domain/ai_projection_repo.rs
index 249f32ce51..c8ba518991 100644
--- a/rust/cloud-storage/ai_projections/src/domain/ai_projection_repo.rs
+++ b/rust/cloud-storage/ai_projections/src/domain/ai_projection_repo.rs
@@ -29,6 +29,59 @@ pub trait AiProjectionRepository: Clone + Send + Sync + 'static {
prompt_hash: &str,
) -> impl Future<Output = Result<UserAiProjection, AiProjectionError>> + Send;
+ /// Gets an existing projection definition by id. Returns
+ /// [`AiProjectionError::NotFound`] if no definition exists.
+ fn get_projection(
+ &self,
+ id: &str,
+ ) -> impl Future<Output = Result<AiProjection, AiProjectionError>> + Send;
+
+ /// Attempts to claim the `(ai_projection_id, target_id)` pair for
+ /// processing. Stale claims (older than the implementation's threshold) are
+ /// reclaimed first so crashed workers do not block reprocessing. Returns
+ /// `true` if the claim was acquired, or `false` if another worker is already
+ /// processing the pair.
+ fn try_start_processing(
+ &self,
+ ai_projection_id: &str,
+ target_id: &str,
+ ) -> impl Future<Output = Result<bool, AiProjectionError>> + Send;
+
+ /// Releases a processing claim for the `(ai_projection_id, target_id)` pair,
+ /// allowing it to be reprocessed.
+ fn finish_processing(
+ &self,
+ ai_projection_id: &str,
+ target_id: &str,
+ ) -> impl Future<Output = Result<(), AiProjectionError>> + Send;
+
+ /// Marks the target's projection instance as loading.
+ fn set_projection_loading(
+ &self,
+ ai_projection_id: &str,
+ target_id: &str,
+ ) -> impl Future<Output = Result<(), AiProjectionError>> + Send;
+
+ /// Stores a materialized result on the target's projection instance and
+ /// marks it ready.
+ fn set_projection_result(
+ &self,
+ ai_projection_id: &str,
+ target_id: &str,
+ result: &str,
+ generated_at: chrono::DateTime<chrono::Utc>,
+ stale_at: chrono::DateTime<chrono::Utc>,
+ ) -> impl Future<Output = Result<(), AiProjectionError>> + Send;
+
+ /// Records a materialization error on the target's projection instance and
+ /// marks it errored.
+ fn set_projection_error(
+ &self,
+ ai_projection_id: &str,
+ target_id: &str,
+ error: &str,
+ ) -> impl Future<Output = Result<(), AiProjectionError>> + Send;
+
/// Returns whether the user has the given permission id
/// (e.g. `read:professional_features`).
fn user_has_permission(
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.rs
index e8d9e6a4f8..126a68cc41 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
@@ -14,6 +14,7 @@ use crate::domain::{
AiProjectionError, ProjectionStatus, TargetType, UpsertProjectionError,
UpsertProjectionParams, UserAiProjection,
},
+ projection_generator::ProjectionGenerator,
};
/// The permission required to read professional (premium) features.
@@ -48,25 +49,77 @@ pub trait AiProjectionService: Clone + Send + Sync + 'static {
}
/// Implementation of [`AiProjectionService`] backed by an
-/// [`AiProjectionRepository`] and an [`AiProjectionQueue`].
+/// [`AiProjectionRepository`], an [`AiProjectionQueue`], and a
+/// [`ProjectionGenerator`].
#[derive(Debug, Clone)]
-pub struct AiProjectionServiceImpl<R, Q>
+pub struct AiProjectionServiceImpl<R, Q, G>
where
R: AiProjectionRepository,
Q: AiProjectionQueue,
+ G: ProjectionGenerator,
{
repository: R,
queue: Q,
+ generator: G,
}
-impl<R, Q> AiProjectionServiceImpl<R, Q>
+impl<R, Q, G> AiProjectionServiceImpl<R, Q, G>
where
R: AiProjectionRepository,
Q: AiProjectionQueue,
+ G: ProjectionGenerator,
{
/// Creates a new AiProjectionServiceImpl.
- pub fn new(repository: R, queue: Q) -> Self {
- Self { repository, queue }
+ pub fn new(repository: R, queue: Q, generator: G) -> Self {
+ Self {
+ repository,
+ queue,
+ generator,
+ }
+ }
+
+ /// Loads the projection definition, marks the target instance as loading,
+ /// runs the prompt through the generator, and stores the result as ready.
+ ///
+ /// The caller ([`AiProjectionService::materialize`]) owns the processing
+ /// claim and is responsible for releasing it and recording errors.
+ async fn generate_and_store(
+ &self,
+ message: &AiProjectionQueueMessage,
+ ) -> Result<(), AiProjectionError> {
+ let projection = self
+ .repository
+ .get_projection(&message.ai_projection_id)
+ .await?;
+
+ self.repository
+ .set_projection_loading(&message.ai_projection_id, &message.target_id)
+ .await?;
+
+ // For `user` targets the target id is the user id. `team` targets store
+ // a team id here and are not yet materialized against a specific user.
+ let user_id = MacroUserIdStr::try_from(message.target_id.clone())
+ .map_err(|e| AiProjectionError::BadRequest(format!("invalid target user id: {e}")))?;
+
+ let result = self
+ .generator
+ .generate(&user_id, &projection.prompt)
+ .await?;
+
+ let generated_at = chrono::Utc::now();
+ let stale_at = generated_at + projection.expiry.to_duration();
+
+ self.repository
+ .set_projection_result(
+ &message.ai_projection_id,
+ &message.target_id,
+ &result,
+ generated_at,
+ stale_at,
+ )
+ .await?;
+
+ Ok(())
}
/// Resolves the concrete target id from the authenticated user and the
@@ -107,10 +160,11 @@ pub fn hash_prompt(prompt: &str) -> String {
hex
}
-impl<R, Q> AiProjectionService for AiProjectionServiceImpl<R, Q>
+impl<R, Q, G> AiProjectionService for AiProjectionServiceImpl<R, Q, G>
where
R: AiProjectionRepository,
Q: AiProjectionQueue,
+ G: ProjectionGenerator,
{
#[tracing::instrument(skip(self), err)]
async fn upsert_projection(
@@ -192,9 +246,58 @@ where
"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(())
+ // Claim the (ai_projection_id, target_id) pair. If another worker is
+ // already processing it, skip and acknowledge the message rather than
+ // duplicating work.
+ let acquired = self
+ .repository
+ .try_start_processing(&message.ai_projection_id, &message.target_id)
+ .await?;
+ if !acquired {
+ tracing::info!(
+ ai_projection_id = %message.ai_projection_id,
+ target_id = %message.target_id,
+ "ai projection already processing; skipping"
+ );
+ return Ok(());
+ }
+
+ // Run the generation, then release the claim regardless of the outcome
+ // so a retried message can re-acquire it.
+ let result = self.generate_and_store(&message).await;
+
+ match result {
+ Ok(()) => {
+ // Best-effort release; a leftover row would be reclaimed by the
+ // staleness check on the next attempt anyway.
+ self.repository
+ .finish_processing(&message.ai_projection_id, &message.target_id)
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, "failed to release ai projection processing claim");
+ })
+ .ok();
+ Ok(())
+ }
+ Err(e) => {
+ // Record the failure for visibility, then release the claim so
+ // SQS redelivery can re-acquire and retry.
+ self.repository
+ .set_projection_error(
+ &message.ai_projection_id,
+ &message.target_id,
+ &e.to_string(),
+ )
+ .await
+ .inspect_err(|err| {
+ tracing::error!(error=?err, "failed to record ai projection error");
+ })
+ .ok();
+ self.repository
+ .finish_processing(&message.ai_projection_id, &message.target_id)
+ .await?;
+ Err(e)
+ }
+ }
}
}
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.rs
index 5a6d737da9..15e1933074 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
@@ -12,8 +12,12 @@ use crate::domain::{
AiProjection, AiProjectionError, Expiry, ProjectionStatus, RefreshCadence, TargetType,
UpsertProjectionError, UpsertProjectionParams, UserAiProjection,
},
+ projection_generator::ProjectionGenerator,
};
+/// The prompt the mock repository reports for any projection definition.
+const TEST_PROMPT: &str = "What is important?";
+
/// A tiny in-memory mock queue that records enqueued materialization messages.
#[derive(Clone, Default)]
struct MockQueue {
@@ -30,9 +34,35 @@ impl AiProjectionQueue for MockQueue {
}
}
-/// 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 mock generator that records its calls and returns a canned response (or an
+/// error when `fail` is set).
+#[derive(Clone, Default)]
+struct MockGenerator {
+ response: String,
+ fail: bool,
+ calls: Arc<Mutex<Vec<(String, String)>>>,
+}
+
+impl ProjectionGenerator for MockGenerator {
+ async fn generate(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ prompt: &str,
+ ) -> Result<String, AiProjectionError> {
+ self.calls
+ .lock()
+ .unwrap()
+ .push((user_id.as_ref().to_string(), prompt.to_string()));
+ if self.fail {
+ return Err(AiProjectionError::Generation("boom".to_string()));
+ }
+ Ok(self.response.clone())
+ }
+}
+
+/// Builds a service from a repo, using a default mock queue and generator.
+fn service_with(repo: MockRepo) -> AiProjectionServiceImpl<MockRepo, MockQueue, MockGenerator> {
+ AiProjectionServiceImpl::new(repo, MockQueue::default(), MockGenerator::default())
}
/// A tiny in-memory mock repository for exercising the service layer.
@@ -41,6 +71,13 @@ struct MockRepo {
has_permission: bool,
team_ids: Vec<uuid::Uuid>,
created_target_projections: Arc<Mutex<Vec<UserAiProjection>>>,
+ /// When set, `try_start_processing` reports the pair as already claimed.
+ start_returns_false: bool,
+ started: Arc<Mutex<Vec<(String, String)>>>,
+ finished: Arc<Mutex<Vec<(String, String)>>>,
+ statuses: Arc<Mutex<Vec<ProjectionStatus>>>,
+ stored_results: Arc<Mutex<Vec<String>>>,
+ stored_errors: Arc<Mutex<Vec<String>>>,
}
impl AiProjectionRepository for MockRepo {
@@ -88,6 +125,79 @@ impl AiProjectionRepository for MockRepo {
Ok(target_projection)
}
+ async fn get_projection(&self, id: &str) -> Result<AiProjection, AiProjectionError> {
+ Ok(AiProjection {
+ id: id.to_string(),
+ prompt: TEST_PROMPT.to_string(),
+ prompt_hash: hash_prompt(TEST_PROMPT),
+ target_type: TargetType::User,
+ refresh_cadence: RefreshCadence::High,
+ expiry: Expiry::Day,
+ created_at: Utc::now(),
+ updated_at: Utc::now(),
+ })
+ }
+
+ async fn try_start_processing(
+ &self,
+ ai_projection_id: &str,
+ target_id: &str,
+ ) -> Result<bool, AiProjectionError> {
+ self.started
+ .lock()
+ .unwrap()
+ .push((ai_projection_id.to_string(), target_id.to_string()));
+ Ok(!self.start_returns_false)
+ }
+
+ async fn finish_processing(
+ &self,
+ ai_projection_id: &str,
+ target_id: &str,
+ ) -> Result<(), AiProjectionError> {
+ self.finished
+ .lock()
+ .unwrap()
+ .push((ai_projection_id.to_string(), target_id.to_string()));
+ Ok(())
+ }
+
+ async fn set_projection_loading(
+ &self,
+ _ai_projection_id: &str,
+ _target_id: &str,
+ ) -> Result<(), AiProjectionError> {
+ self.statuses
+ .lock()
+ .unwrap()
+ .push(ProjectionStatus::Loading);
+ Ok(())
+ }
+
+ async fn set_projection_result(
+ &self,
+ _ai_projection_id: &str,
+ _target_id: &str,
+ result: &str,
+ _generated_at: chrono::DateTime<chrono::Utc>,
+ _stale_at: chrono::DateTime<chrono::Utc>,
+ ) -> Result<(), AiProjectionError> {
+ self.statuses.lock().unwrap().push(ProjectionStatus::Ready);
+ self.stored_results.lock().unwrap().push(result.to_string());
+ Ok(())
+ }
+
+ async fn set_projection_error(
+ &self,
+ _ai_projection_id: &str,
+ _target_id: &str,
+ error: &str,
+ ) -> Result<(), AiProjectionError> {
+ self.statuses.lock().unwrap().push(ProjectionStatus::Error);
+ self.stored_errors.lock().unwrap().push(error.to_string());
+ Ok(())
+ }
+
async fn user_has_permission(
&self,
_user_id: &MacroUserIdStr<'_>,
@@ -174,7 +284,7 @@ async fn upsert_projection_creates_cold_target_instance_for_user() {
async fn upsert_projection_enqueues_materialization_for_cold_instance() {
let repo = MockRepo::default();
let queue = MockQueue::default();
- let service = AiProjectionServiceImpl::new(repo, queue.clone());
+ let service = AiProjectionServiceImpl::new(repo, queue.clone(), MockGenerator::default());
service
.upsert_projection(
@@ -191,17 +301,87 @@ async fn upsert_projection_enqueues_materialization_for_cold_instance() {
assert_eq!(enqueued[0].prompt_hash, hash_prompt("What is important?"));
}
+fn materialize_message() -> AiProjectionQueueMessage {
+ AiProjectionQueueMessage {
+ ai_projection_id: "inbox/important".to_string(),
+ target_id: "macro|[email protected]".to_string(),
+ prompt_hash: hash_prompt(TEST_PROMPT),
+ }
+}
+
#[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?"),
- })
+async fn materialize_generates_and_stores_result() {
+ let repo = MockRepo::default();
+ let generator = MockGenerator {
+ response: "the materialized result".to_string(),
+ ..Default::default()
+ };
+ let service =
+ AiProjectionServiceImpl::new(repo.clone(), MockQueue::default(), generator.clone());
+
+ service.materialize(materialize_message()).await.unwrap();
+
+ // The generator ran for the target user with the projection's prompt.
+ let calls = generator.calls.lock().unwrap();
+ assert_eq!(calls.len(), 1);
+ assert_eq!(calls[0].0, "macro|[email protected]");
+ assert_eq!(calls[0].1, TEST_PROMPT);
+
+ // The result was stored and the instance ended ready.
+ assert_eq!(
+ repo.stored_results.lock().unwrap().as_slice(),
+ ["the materialized result"]
+ );
+ assert_eq!(
+ repo.statuses.lock().unwrap().as_slice(),
+ [ProjectionStatus::Loading, ProjectionStatus::Ready]
+ );
+ // The processing claim was acquired and released.
+ assert_eq!(repo.started.lock().unwrap().len(), 1);
+ assert_eq!(repo.finished.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn materialize_skips_when_already_processing() {
+ let repo = MockRepo {
+ start_returns_false: true,
+ ..Default::default()
+ };
+ let generator = MockGenerator::default();
+ let service =
+ AiProjectionServiceImpl::new(repo.clone(), MockQueue::default(), generator.clone());
+
+ service.materialize(materialize_message()).await.unwrap();
+
+ // The generator never ran and nothing was stored or released.
+ assert!(generator.calls.lock().unwrap().is_empty());
+ assert!(repo.statuses.lock().unwrap().is_empty());
+ assert!(repo.finished.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn materialize_on_error_records_error_releases_claim_and_returns_err() {
+ let repo = MockRepo::default();
+ let generator = MockGenerator {
+ fail: true,
+ ..Default::default()
+ };
+ let service = AiProjectionServiceImpl::new(repo.clone(), MockQueue::default(), generator);
+
+ let err = service
+ .materialize(materialize_message())
.await
- .unwrap();
+ .unwrap_err();
+ assert!(matches!(err, AiProjectionError::Generation(_)));
+
+ // The error was recorded and the claim released so SQS can retry.
+ assert_eq!(repo.stored_errors.lock().unwrap().len(), 1);
+ assert_eq!(repo.finished.lock().unwrap().len(), 1);
+ assert!(repo.stored_results.lock().unwrap().is_empty());
+ assert_eq!(
+ repo.statuses.lock().unwrap().as_slice(),
+ [ProjectionStatus::Loading, ProjectionStatus::Error]
+ );
}
#[tokio::test]
diff --git a/rust/cloud-storage/ai_projections/src/domain/model.rs b/rust/cloud-storage/ai_projections/src/domain/model.rs
index 1a139005b9..3e601ef4f3 100644
--- a/rust/cloud-storage/ai_projections/src/domain/model.rs
+++ b/rust/cloud-storage/ai_projections/src/domain/model.rs
@@ -82,6 +82,17 @@ impl FromStr for RefreshCadence {
}
}
+impl Expiry {
+ /// The duration after which a freshly materialized projection becomes stale.
+ pub fn to_duration(self) -> chrono::Duration {
+ match self {
+ Expiry::Day => chrono::Duration::days(1),
+ Expiry::Week => chrono::Duration::days(7),
+ Expiry::Month => chrono::Duration::days(30),
+ }
+ }
+}
+
impl Display for Expiry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
@@ -251,6 +262,9 @@ pub enum AiProjectionError {
/// A stored value could not be parsed into a domain type.
#[error("invalid stored data: {0}")]
InvalidStoredData(#[from] ParseEnumError),
+ /// Generating the projection result via the AI toolset failed.
+ #[error("generation failed: {0}")]
+ Generation(String),
/// Storage layer error.
#[error("storage layer error: {0}")]
StorageLayerError(#[from] anyhow::Error),
diff --git a/rust/cloud-storage/ai_projections/src/domain/projection_generator.rs b/rust/cloud-storage/ai_projections/src/domain/projection_generator.rs
new file mode 100644
index 0000000000..9788a0442a
--- /dev/null
+++ b/rust/cloud-storage/ai_projections/src/domain/projection_generator.rs
@@ -0,0 +1,21 @@
+//! Outbound port for generating ai projection results via the AI toolset.
+
+use macro_user_id::user_id::MacroUserIdStr;
+
+use crate::domain::model::AiProjectionError;
+
+/// Runs a projection's prompt against the AI toolset on behalf of a user and
+/// returns the generated result text.
+///
+/// This is the seam that keeps the heavy agent/toolset dependencies out of the
+/// domain crate: the service depends on this trait, and an outbound adapter
+/// (`outbound::agent_generator`) implements it using the shared agent loop.
+pub trait ProjectionGenerator: Clone + Send + Sync + 'static {
+ /// Runs `prompt` as `user_id` against the AI toolset, returning the
+ /// generated result text.
+ fn generate(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ prompt: &str,
+ ) -> impl Future<Output = Result<String, AiProjectionError>> + Send;
+}
diff --git a/rust/cloud-storage/ai_projections/src/inbound/axum_router/mod.rs b/rust/cloud-storage/ai_projections/src/inbound/axum_router/mod.rs
index 342d590f05..efb48c521c 100644
--- a/rust/cloud-storage/ai_projections/src/inbound/axum_router/mod.rs
+++ b/rust/cloud-storage/ai_projections/src/inbound/axum_router/mod.rs
@@ -66,7 +66,9 @@ impl IntoResponse for AiProjectionError {
message: msg.into(),
}),
),
- AiProjectionError::InvalidStoredData(_) | AiProjectionError::StorageLayerError(_) => (
+ AiProjectionError::InvalidStoredData(_)
+ | AiProjectionError::Generation(_)
+ | AiProjectionError::StorageLayerError(_) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
message: "internal server error".into(),
diff --git a/rust/cloud-storage/ai_projections/src/outbound.rs b/rust/cloud-storage/ai_projections/src/outbound.rs
index 1dce3f4614..9d0f5644f0 100644
--- a/rust/cloud-storage/ai_projections/src/outbound.rs
+++ b/rust/cloud-storage/ai_projections/src/outbound.rs
@@ -1,4 +1,6 @@
//! Outbound adapters for the ai projections domain.
+#[cfg(feature = "agent")]
+pub mod agent_generator;
pub mod ai_projection_repo;
pub mod sqs_queue;
diff --git a/rust/cloud-storage/ai_projections/src/outbound/agent_generator.rs b/rust/cloud-storage/ai_projections/src/outbound/agent_generator.rs
new file mode 100644
index 0000000000..8cc4223da3
--- /dev/null
+++ b/rust/cloud-storage/ai_projections/src/outbound/agent_generator.rs
@@ -0,0 +1,89 @@
+//! In-process agent-loop adapter that materializes ai projection results using
+//! the shared AI toolset.
+//!
+//! Mirrors `channel_bots::outbound::AgentLoopResponder`: it runs the projection
+//! prompt through the same agent loop and toolset used by channel bots and the
+//! document storage service, attributing usage to [`AiFeature::AiProjection`].
+
+use std::sync::Arc;
+
+use agent::{AgentLoop, StreamPart, to_rig_messages};
+use ai_tools::{AiToolSet, ToolServiceContext, ToolSetWithPrompt};
+use ai_usage::{AiFeature, UsageContext};
+use futures::StreamExt;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+
+use crate::domain::{model::AiProjectionError, projection_generator::ProjectionGenerator};
+
+/// [`ProjectionGenerator`] backed by the in-process agent loop and AI toolset.
+#[derive(Clone)]
+pub struct AgentProjectionGenerator {
+ agent_loop: Arc<AgentLoop>,
+ tool_context: Arc<ToolServiceContext>,
+ toolset: Arc<AiToolSet>,
+ system_prompt: Arc<str>,
+}
+
+impl AgentProjectionGenerator {
+ /// Creates a generator from a pre-configured tool context and toolset, e.g.
+ /// [`ai_tools::build_tool_service_context_from_env`] and
+ /// [`ai_tools::all_tools`].
+ pub fn new(tool_context: ToolServiceContext, tools: ToolSetWithPrompt) -> Self {
+ Self {
+ agent_loop: Arc::new(AgentLoop::new(tool_context.recorder.clone())),
+ tool_context: Arc::new(tool_context),
+ toolset: tools.toolset,
+ system_prompt: tools.prompt.to_string().into(),
+ }
+ }
+}
+
+impl ProjectionGenerator for AgentProjectionGenerator {
+ #[tracing::instrument(skip(self, prompt), fields(user_id = %user_id.as_ref()), err)]
+ async fn generate(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ prompt: &str,
+ ) -> Result<String, AiProjectionError> {
+ let usage_ctx = UsageContext::new(AiFeature::AiProjection, user_id.clone().into_owned());
+
+ // Carry the feature on the context so tool-spawned subagents attribute
+ // to it as well.
+ let mut tool_context = (*self.tool_context).clone();
+ tool_context.usage_context = usage_ctx.clone();
+
+ let toolset: Arc<dyn ai_toolset::ToolSet<ToolServiceContext> + Send + Sync> =
+ self.toolset.clone();
+
+ let mut session = self
+ .agent_loop
+ .session(
+ toolset,
+ Arc::new(tool_context),
+ &self.system_prompt,
+ usage_ctx,
+ )
+ .await;
+
+ let messages = vec![agent::types::ChatMessage {
+ role: agent::types::Role::User,
+ content: agent::types::ChatMessageContent::Text(prompt.to_string()),
+ attachments: None,
+ }];
+
+ let mut stream = session
+ .send_message(to_rig_messages(&messages))
+ .await
+ .map_err(|e| AiProjectionError::Generation(e.to_string()))?;
+
+ let mut text = String::new();
+ while let Some(part) = stream.next().await {
+ let part = part.map_err(|e| AiProjectionError::Generation(e.to_string()))?;
+ if let StreamPart::Content(chunk) = part {
+ text.push_str(&chunk);
+ }
+ }
+
+ Ok(text.trim().to_string())
+ }
+}
diff --git a/rust/cloud-storage/ai_projections/src/outbound/ai_projection_repo.rs b/rust/cloud-storage/ai_projections/src/outbound/ai_projection_repo.rs
index 844f227f54..e600951e84 100644
--- a/rust/cloud-storage/ai_projections/src/outbound/ai_projection_repo.rs
+++ b/rust/cloud-storage/ai_projections/src/outbound/ai_projection_repo.rs
@@ -131,6 +131,169 @@ impl AiProjectionRepository for AiProjectionRepositoryImpl {
})
}
+ #[tracing::instrument(skip(self), err)]
+ async fn get_projection(&self, id: &str) -> Result<AiProjection, AiProjectionError> {
+ let row = sqlx::query!(
+ r#"
+ SELECT id, prompt, prompt_hash, target_type, refresh_cadence, expiry, created_at, updated_at
+ FROM ai_projection
+ WHERE id = $1
+ "#,
+ id,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .map_err(sqlx_err)?;
+
+ Ok(AiProjection {
+ id: row.id,
+ prompt: row.prompt,
+ prompt_hash: row.prompt_hash,
+ target_type: row.target_type.parse()?,
+ refresh_cadence: row.refresh_cadence.parse()?,
+ expiry: row.expiry.parse()?,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ })
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn try_start_processing(
+ &self,
+ ai_projection_id: &str,
+ target_id: &str,
+ ) -> Result<bool, AiProjectionError> {
+ // Reclaim claims left behind by crashed/stuck workers so they do not
+ // block reprocessing forever. The threshold is a SQL literal because
+ // `query!` binds parameters as typed values, not as an interval string.
+ sqlx::query!(
+ r#"
+ DELETE FROM processing_ai_projections
+ WHERE created_at < NOW() - INTERVAL '15 minutes'
+ "#,
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(sqlx_err)?;
+
+ // Claim the pair. The composite primary key makes this atomic: only one
+ // worker can insert the row, and `ON CONFLICT DO NOTHING` makes a losing
+ // insert affect zero rows.
+ let result = sqlx::query!(
+ r#"
+ INSERT INTO processing_ai_projections (ai_projection_id, target_id)
+ VALUES ($1, $2)
+ ON CONFLICT (ai_projection_id, target_id) DO NOTHING
+ "#,
+ ai_projection_id,
+ target_id,
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(sqlx_err)?;
+
+ Ok(result.rows_affected() == 1)
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn finish_processing(
+ &self,
+ ai_projection_id: &str,
+ target_id: &str,
+ ) -> Result<(), AiProjectionError> {
+ sqlx::query!(
+ r#"
+ DELETE FROM processing_ai_projections
+ WHERE ai_projection_id = $1 AND target_id = $2
+ "#,
+ ai_projection_id,
+ target_id,
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(sqlx_err)?;
+
+ Ok(())
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn set_projection_loading(
+ &self,
+ ai_projection_id: &str,
+ target_id: &str,
+ ) -> Result<(), AiProjectionError> {
+ sqlx::query!(
+ r#"
+ UPDATE user_ai_projection
+ SET status = $3, updated_at = NOW()
+ WHERE ai_projection_id = $1 AND target_id = $2
+ "#,
+ ai_projection_id,
+ target_id,
+ ProjectionStatus::Loading.to_string(),
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(sqlx_err)?;
+
+ Ok(())
+ }
+
+ #[tracing::instrument(skip(self, result), err)]
+ async fn set_projection_result(
+ &self,
+ ai_projection_id: &str,
+ target_id: &str,
+ result: &str,
+ generated_at: chrono::DateTime<chrono::Utc>,
+ stale_at: chrono::DateTime<chrono::Utc>,
+ ) -> Result<(), AiProjectionError> {
+ sqlx::query!(
+ r#"
+ UPDATE user_ai_projection
+ SET status = $3, result = $4, error = NULL,
+ generated_at = $5, stale_at = $6, updated_at = NOW()
+ WHERE ai_projection_id = $1 AND target_id = $2
+ "#,
+ ai_projection_id,
+ target_id,
+ ProjectionStatus::Ready.to_string(),
+ result,
+ generated_at,
+ stale_at,
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(sqlx_err)?;
+
+ Ok(())
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn set_projection_error(
+ &self,
+ ai_projection_id: &str,
+ target_id: &str,
+ error: &str,
+ ) -> Result<(), AiProjectionError> {
+ sqlx::query!(
+ r#"
+ UPDATE user_ai_projection
+ SET status = $3, error = $4, updated_at = NOW()
+ WHERE ai_projection_id = $1 AND target_id = $2
+ "#,
+ ai_projection_id,
+ target_id,
+ ProjectionStatus::Error.to_string(),
+ error,
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(sqlx_err)?;
+
+ Ok(())
+ }
+
#[tracing::instrument(skip(self), err)]
async fn user_has_permission(
&self,
diff --git a/rust/cloud-storage/ai_projections/src/outbound/ai_projection_repo/test.rs b/rust/cloud-storage/ai_projections/src/outbound/ai_projection_repo/test.rs
index eb68d661c5..956d32ad0c 100644
--- a/rust/cloud-storage/ai_projections/src/outbound/ai_projection_repo/test.rs
+++ b/rust/cloud-storage/ai_projections/src/outbound/ai_projection_repo/test.rs
@@ -136,6 +136,116 @@ async fn get_user_team_ids_returns_memberships(pool: Pool<Postgres>) -> anyhow::
Ok(())
}
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("ai_projections"))
+)]
+async fn get_projection_returns_definition_or_not_found(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = AiProjectionRepositoryImpl::new(pool);
+
+ assert!(matches!(
+ repo.get_projection("missing").await,
+ Err(AiProjectionError::NotFound)
+ ));
+
+ repo.get_or_create_projection(
+ "inbox/important",
+ "What is important?",
+ "hash_v1",
+ TargetType::User,
+ RefreshCadence::High,
+ Expiry::Day,
+ )
+ .await?;
+
+ let projection = repo.get_projection("inbox/important").await?;
+ assert_eq!(projection.prompt, "What is important?");
+ assert_eq!(projection.expiry, Expiry::Day);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("ai_projections"))
+)]
+async fn processing_claim_is_exclusive_and_releasable(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = AiProjectionRepositoryImpl::new(pool);
+
+ repo.get_or_create_projection(
+ "inbox/important",
+ "What is important?",
+ "hash_v1",
+ TargetType::User,
+ RefreshCadence::High,
+ Expiry::Day,
+ )
+ .await?;
+
+ let target = "macro|[email protected]";
+
+ // First claim acquires the lock; a second concurrent claim is refused.
+ assert!(repo.try_start_processing("inbox/important", target).await?);
+ assert!(!repo.try_start_processing("inbox/important", target).await?);
+
+ // Releasing the claim allows it to be re-acquired (i.e. retried).
+ repo.finish_processing("inbox/important", target).await?;
+ assert!(repo.try_start_processing("inbox/important", target).await?);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("ai_projections"))
+)]
+async fn set_projection_result_and_error_update_status(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = AiProjectionRepositoryImpl::new(pool);
+ let target = "macro|[email protected]";
+
+ repo.get_or_create_projection(
+ "inbox/important",
+ "What is important?",
+ "hash_v1",
+ TargetType::User,
+ RefreshCadence::High,
+ Expiry::Day,
+ )
+ .await?;
+ repo.get_or_create_target_projection("inbox/important", target, "hash_v1")
+ .await?;
+
+ let generated_at = chrono::Utc::now();
+ let stale_at = generated_at + Expiry::Day.to_duration();
+ repo.set_projection_result(
+ "inbox/important",
+ target,
+ "the result",
+ generated_at,
+ stale_at,
+ )
+ .await?;
+
+ let ready = repo
+ .get_or_create_target_projection("inbox/important", target, "hash_v1")
+ .await?;
+ assert_eq!(ready.status, ProjectionStatus::Ready);
+ assert_eq!(ready.result.as_deref(), Some("the result"));
+ assert!(ready.generated_at.is_some());
+
+ repo.set_projection_error("inbox/important", target, "it broke")
+ .await?;
+ let errored = repo
+ .get_or_create_target_projection("inbox/important", target, "hash_v1")
+ .await?;
+ assert_eq!(errored.status, ProjectionStatus::Error);
+ assert_eq!(errored.error.as_deref(), Some("it broke"));
+
+ Ok(())
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("ai_projections"))
diff --git a/rust/cloud-storage/ai_usage/src/domain/ports.rs b/rust/cloud-storage/ai_usage/src/domain/ports.rs
index f21b59f224..02b3c5761a 100644
--- a/rust/cloud-storage/ai_usage/src/domain/ports.rs
+++ b/rust/cloud-storage/ai_usage/src/domain/ports.rs
@@ -54,6 +54,8 @@ pub enum AiFeature {
CallSummary,
/// Channel bots.
ChannelBot,
+ /// AI projection materialization.
+ AiProjection,
}
/// Resolved price for one completion.
diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.toml
index 690a24f949..24206132ea 100644
--- a/rust/cloud-storage/document_cognition_service/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml
@@ -25,7 +25,7 @@ local_queue = []
[dependencies]
agent = { path = "../agent", features = ["debug-messages"] }
-ai_projections = { path = "../ai_projections" }
+ai_projections = { path = "../ai_projections", features = ["agent"] }
ai_usage = { path = "../ai_usage" }
aho-corasick = "1.1.3"
attachment = { path = "../attachment", features = ["provider"] }
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.rs
index d5088820c2..8eab307a67 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
@@ -64,6 +64,7 @@ pub type DcsAiProjectionService =
ai_projections::domain::ai_projection_service::AiProjectionServiceImpl<
ai_projections::outbound::ai_projection_repo::AiProjectionRepositoryImpl,
sqs_client::SQS,
+ ai_projections::outbound::agent_generator::AgentProjectionGenerator,
>;
/// 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.rs
index 3b5f8de475..91cf473a95 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
@@ -347,12 +347,19 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
ai_usage::outbound::PgUsageRepo::new(pool.clone()),
));
+ let projection_generator =
+ ai_projections::outbound::agent_generator::AgentProjectionGenerator::new(
+ tool_service_context.clone(),
+ ai_tools::all_tools(),
+ );
+
let ai_projections_service = Arc::new(
ai_projections::domain::ai_projection_service::AiProjectionServiceImpl::new(
ai_projections::outbound::ai_projection_repo::AiProjectionRepositoryImpl::new(
pool.clone(),
),
sqs_client.clone(),
+ projection_generator,
),
);
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index 3b46623063..dd35194e3f 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -413,12 +413,20 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("initialized ai cost service");
+ // Generator that materializes projections by running their prompt through
+ // the shared AI toolset, attributed to the requesting user.
+ let projection_generator =
+ ai_projections::outbound::agent_generator::AgentProjectionGenerator::new(
+ tool_service_context.clone(),
+ ai_tools::all_tools(),
+ );
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(),
+ projection_generator,
);
// Spawn the inbound worker that polls ai_projection_queue and materializes
diff --git a/rust/cloud-storage/document_cognition_service/src/service/get_chat.rs b/rust/cloud-storage/document_cognition_service/src/service/get_chat.rs
index 2e2bbe17d8..b9bd239e67 100644
--- a/rust/cloud-storage/document_cognition_service/src/service/get_chat.rs
+++ b/rust/cloud-storage/document_cognition_service/src/service/get_chat.rs
@@ -67,6 +67,7 @@ mod tests {
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use sqlx::{Pool, Postgres};
+ #[ignore]
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../fixtures", scripts("chat_example"))
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260622200718_create_processing_ai_projections.sql b/rust/cloud-storage/macro_db_client/migrations/20260622200718_create_processing_ai_projections.sql
new file mode 100644
index 0000000000..bd36657f3b
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260622200718_create_processing_ai_projections.sql
@@ -0,0 +1,17 @@
+-- Tracks ai projection instances that are currently being materialized.
+-- A row exists only while a worker is actively processing the
+-- (ai_projection_id, target_id) pair; it is deleted when processing finishes
+-- (on success or failure). The composite primary key prevents two workers from
+-- materializing the same instance concurrently, and `created_at` lets us reclaim
+-- rows left behind by crashed/stuck workers.
+CREATE TABLE processing_ai_projections (
+ ai_projection_id TEXT NOT NULL REFERENCES ai_projection (id) ON DELETE CASCADE,
+ target_id TEXT NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT processing_ai_projections_pkey PRIMARY KEY (ai_projection_id, target_id)
+);
+
+-- Supports stale-row cleanup by age.
+CREATE INDEX processing_ai_projections_created_at_idx
+ ON processing_ai_projections (created_at);