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 refresh handler (#4275)
Will Hutchinsoncbf5a0c78e1f
diff --git a/.github/services-config.json b/.github/services-config.jsonindex e37a0aafdf..4aafa90143 100644--- a/.github/services-config.json+++ b/.github/services-config.json@@ -82,11 +82,15 @@},"document-cognition-service": {"source_paths": [- "rust/cloud-storage/document_cognition_service/**"+ "rust/cloud-storage/document_cognition_service/**",+ "rust/cloud-storage/ai_projections_refresh_handler/**"],"stack_path": "infra/stacks/document-cognition-service/**","deploy_binaries": ["document_cognition_service"+ ],+ "deploy_lambdas": [+ "ai_projections_refresh_handler"]},"document-storage-service": {diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex daffd5301a..63e058ce63 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -112,6 +112,47 @@"user_quota","workspace-hack"],+ "ai_projections_refresh_handler": [+ "agent",+ "ai_projections_refresh_handler",+ "ai_toolset",+ "ai_usage",+ "attachment",+ "authentication_service_client",+ "cowlike",+ "crm",+ "document_sub_type",+ "email",+ "email_utils",+ "entity_access",+ "filter_ast",+ "frecency",+ "item_filters",+ "macro_aws_config",+ "macro_config",+ "macro_config_derive",+ "macro_entrypoint",+ "macro_env",+ "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",+ "remote_env_var",+ "s3_key",+ "sqs_client",+ "unfurl",+ "workspace-hack"+ ],"ai_tools": ["agent","ai_tools",diff --git a/infra/stacks/document-cognition-service/Pulumi.dev.yaml b/infra/stacks/document-cognition-service/Pulumi.dev.yamlindex 7cfff4d829..69738b7399 100644--- a/infra/stacks/document-cognition-service/Pulumi.dev.yaml+++ b/infra/stacks/document-cognition-service/Pulumi.dev.yaml@@ -15,4 +15,5 @@ config:document-cognition:sync_service_auth_key: sync-service-key-devdocument-cognition:perplexity-api-key: perplexity-api-keydocument-cognition:authentication_service_internal_api_key: authentication-service-internal-api-key-dev+ document-cognition:macro_db_proxy_secret_key: macrodb-rds-proxy-devdatadog:validate: "false"diff --git a/infra/stacks/document-cognition-service/Pulumi.prod.yaml b/infra/stacks/document-cognition-service/Pulumi.prod.yamlindex 6610177e14..afca9dfc5f 100644--- a/infra/stacks/document-cognition-service/Pulumi.prod.yaml+++ b/infra/stacks/document-cognition-service/Pulumi.prod.yaml@@ -15,3 +15,4 @@ config:document-cognition:sync_service_auth_key: sync-service-key-proddocument-cognition:perplexity-api-key: perplexity-api-keydocument-cognition:authentication_service_internal_api_key: authentication-service-internal-api-key-prod+ document-cognition:macro_db_proxy_secret_key: macrodb-rds-proxy-proddiff --git a/infra/stacks/document-cognition-service/ai-projections-refresh-trigger.ts b/infra/stacks/document-cognition-service/ai-projections-refresh-trigger.tsnew file mode 100644index 0000000000..4552d654bc--- /dev/null+++ b/infra/stacks/document-cognition-service/ai-projections-refresh-trigger.ts@@ -0,0 +1,201 @@+import * as aws from '@pulumi/aws';+import * as pulumi from '@pulumi/pulumi';+import { Lambda } from '../../packages/lambda';+import { CLOUD_TRAIL_SNS_TOPIC_ARN, stack } from '../../packages/shared';++const LAMBDA_BASE_NAME = 'ai_projections_refresh_handler';+const CLOUD_STORAGE_BASE = `../../../rust/cloud-storage`;+const ZIP_LOCATION = `${CLOUD_STORAGE_BASE}/target/lambda/${LAMBDA_BASE_NAME}/bootstrap.zip`;++// Each cadence maps to its own schedule frequency. The lambda is invoked once+// per cadence with a constant input identifying which projections to sweep, so+// `refresh_cadence` controls how often a cadence's projections are checked.+const CADENCE_SCHEDULES: {+ cadence: 'high' | 'medium' | 'low';+ rate: string;+}[] = [+ { cadence: 'high', rate: 'rate(6 hours)' },+ { cadence: 'medium', rate: 'rate(1 day)' },+ { cadence: 'low', rate: 'rate(3 days)' },+];++export type AiProjectionsRefreshTriggerEnvVars = {+ DATABASE_URL: pulumi.Output<string> | string;+ AI_PROJECTION_QUEUE: pulumi.Output<string> | string;+ ENVIRONMENT: pulumi.Output<string> | string;+ RUST_LOG: pulumi.Output<string> | string;+};++type AiProjectionsRefreshTriggerArgs = {+ envVars: AiProjectionsRefreshTriggerEnvVars;+ aiProjectionQueueArn: pulumi.Output<string> | string;+ vpc: {+ vpcId: pulumi.Output<string> | string;+ publicSubnetIds: pulumi.Output<string[]> | string[];+ privateSubnetIds: pulumi.Output<string[]> | string[];+ };+ tags: { [key: string]: string };+};++export class AiProjectionsRefreshTrigger extends pulumi.ComponentResource {+ role: aws.iam.Role;+ lambda: aws.lambda.Function;+ tags: { [key: string]: string };+ constructor(+ name: string,+ args: AiProjectionsRefreshTriggerArgs,+ opts?: pulumi.ComponentResourceOptions+ ) {+ super('my:components:AiProjectionsRefreshTrigger', name, {}, opts);+ const { aiProjectionQueueArn, vpc, envVars, tags } = args;++ this.tags = tags;++ const sqsPolicy = new aws.iam.Policy(+ `${LAMBDA_BASE_NAME}-sqs-policy`,+ {+ policy: pulumi.output({+ Version: '2012-10-17',+ Statement: [+ {+ Action: ['sqs:SendMessage'],+ Resource: [pulumi.interpolate`${aiProjectionQueueArn}`],+ Effect: 'Allow',+ },+ ],+ }),+ tags: this.tags,+ },+ { parent: this }+ );++ this.role = new aws.iam.Role(+ `${LAMBDA_BASE_NAME}-role`,+ {+ name: `${LAMBDA_BASE_NAME}-role-${stack}`,+ assumeRolePolicy: JSON.stringify({+ Version: '2012-10-17',+ Statement: [+ {+ Action: 'sts:AssumeRole',+ Effect: 'Allow',+ Principal: {+ Service: 'lambda.amazonaws.com',+ },+ },+ ],+ }),+ managedPolicyArns: [+ aws.iam.ManagedPolicy.AWSLambdaBasicExecutionRole,+ aws.iam.ManagedPolicy.AWSLambdaRole,+ aws.iam.ManagedPolicy.AWSLambdaVPCAccessExecutionRole,+ aws.iam.ManagedPolicy.CloudWatchLogsFullAccess,+ sqsPolicy.arn,+ ],+ tags: this.tags,+ },+ { parent: this }+ );++ const aiProjectionsRefreshLambda =+ new Lambda<AiProjectionsRefreshTriggerEnvVars>(+ `${LAMBDA_BASE_NAME}-lambda`,+ {+ baseName: LAMBDA_BASE_NAME,+ handlerBase: CLOUD_STORAGE_BASE,+ zipLocation: ZIP_LOCATION,+ vpc,+ envVars,+ role: this.role,+ timeout: 60,+ tags: this.tags,+ },+ { parent: this }+ );++ this.lambda = aiProjectionsRefreshLambda.lambda;++ // One scheduled rule per cadence, each passing a constant input that tells+ // the handler which cadence's projections to sweep.+ for (const { cadence, rate } of CADENCE_SCHEDULES) {+ const triggerRule = new aws.cloudwatch.EventRule(+ `${LAMBDA_BASE_NAME}-${cadence}-rule`,+ {+ name: `${LAMBDA_BASE_NAME}-${cadence}-rule-${stack}`,+ scheduleExpression: rate,+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.cloudwatch.EventTarget(+ `${LAMBDA_BASE_NAME}-${cadence}-target-${stack}`,+ {+ rule: triggerRule.name,+ arn: this.lambda.arn,+ input: JSON.stringify({ refresh_cadence: cadence }),+ },+ { parent: this }+ );++ new aws.lambda.Permission(+ `${LAMBDA_BASE_NAME}-${cadence}-permission-${stack}`,+ {+ action: 'lambda:InvokeFunction',+ function: this.lambda.name,+ principal: 'events.amazonaws.com',+ sourceArn: triggerRule.arn,+ },+ { parent: this }+ );+ }++ this.setupLambdaAlarms();+ }++ setupLambdaAlarms() {+ new aws.cloudwatch.MetricAlarm(+ `${LAMBDA_BASE_NAME}-throttle-alarm`,+ {+ name: `${LAMBDA_BASE_NAME}-throttle-count-${stack}`,+ metricName: 'Throttles',+ namespace: 'AWS/Lambda',+ statistic: 'Sum',+ period: 300,+ evaluationPeriods: 1,+ threshold: 50,+ comparisonOperator: 'GreaterThanOrEqualToThreshold',+ dimensions: {+ FunctionName: this.lambda.name,+ },+ alarmDescription: `Alarm when ${LAMBDA_BASE_NAME} lambda experiences throttling.`,+ actionsEnabled: true,+ alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.cloudwatch.MetricAlarm(+ `${LAMBDA_BASE_NAME}-error-alarm`,+ {+ name: `${LAMBDA_BASE_NAME}-error-count-${stack}`,+ metricName: 'Errors',+ namespace: 'AWS/Lambda',+ statistic: 'Sum',+ period: 300,+ evaluationPeriods: 1,+ threshold: 1,+ comparisonOperator: 'GreaterThanOrEqualToThreshold',+ dimensions: {+ FunctionName: this.lambda.name,+ },+ alarmDescription: `Alarm when ${LAMBDA_BASE_NAME} lambda experiences errors.`,+ actionsEnabled: true,+ alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],+ tags: this.tags,+ },+ { parent: this }+ );+ }+}diff --git a/infra/stacks/document-cognition-service/index.ts b/infra/stacks/document-cognition-service/index.tsindex ca12e1fa2f..ddf57f0feb 100644--- a/infra/stacks/document-cognition-service/index.ts+++ b/infra/stacks/document-cognition-service/index.ts@@ -16,6 +16,7 @@ import {DocumentCognitionService,SERVICE_DOMAIN_NAME,} from './document-cognition-service';+import { AiProjectionsRefreshTrigger } from './ai-projections-refresh-trigger';const tags = {environment: stack,@@ -32,6 +33,13 @@ const DATABASE_URL = aws.secretsmanager}).apply((secret) => secret.secretString);+// NOTE: NEVER EVER EVER EXPORT THIS. ITS A SECRET VALUE+const PROXY_DATABASE_URL = aws.secretsmanager+ .getSecretVersionOutput({+ secretId: config.require(`macro_db_proxy_secret_key`),+ })+ .apply((secret) => secret.secretString);+const JWT_SECRET_KEY = config.require(`jwt_secret_key`);const jwtSecretKeyArn: pulumi.Output<string> = aws.secretsmanager.getSecretVersionOutput({ secretId: JWT_SECRET_KEY })@@ -171,6 +179,27 @@ const aiProjectionQueue = new Queue('ai-projection', {visibilityTimeoutSeconds: 120,});+// Background refresh: scheduled lambda that sweeps user_ai_projection per+// cadence, deleting inactive instances and enqueuing refreshes for stale ones+// onto the ai projection queue owned above.+const aiProjectionsRefreshTrigger = new AiProjectionsRefreshTrigger(+ `ai-projections-refresh-trigger-${stack}`,+ {+ envVars: {+ AI_PROJECTION_QUEUE: pulumi.interpolate`${aiProjectionQueue.queue.name}`,+ DATABASE_URL: pulumi.interpolate`${PROXY_DATABASE_URL}`,+ ENVIRONMENT: stack,+ RUST_LOG: 'ai_projections_refresh_handler=trace,sqs_client=trace',+ },+ aiProjectionQueueArn: aiProjectionQueue.queue.arn,+ vpc: coparse_api_vpc,+ tags,+ }+);++export const aiProjectionsRefreshTriggerLambdaName =+ aiProjectionsRefreshTrigger.lambda.name;+const MACRO_API_TOKENS = getMacroApiToken();const documentCognitionService = new DocumentCognitionService(diff --git a/rust/cloud-storage/.sqlx/query-f3d1ff560e0f56fbaa9d7dfc7c0b6c5db474bfc4d596e29c5618abc5307e1e52.json b/rust/cloud-storage/.sqlx/query-4f7d47d4b75fd81a44c21bd147957428788a190933c8f4aef68587165b10eb74.jsonsimilarity index 69%rename from rust/cloud-storage/.sqlx/query-f3d1ff560e0f56fbaa9d7dfc7c0b6c5db474bfc4d596e29c5618abc5307e1e52.jsonrename to rust/cloud-storage/.sqlx/query-4f7d47d4b75fd81a44c21bd147957428788a190933c8f4aef68587165b10eb74.jsonindex e63dd7cc6f..d5d5affcf8 100644--- a/rust/cloud-storage/.sqlx/query-f3d1ff560e0f56fbaa9d7dfc7c0b6c5db474bfc4d596e29c5618abc5307e1e52.json+++ b/rust/cloud-storage/.sqlx/query-4f7d47d4b75fd81a44c21bd147957428788a190933c8f4aef68587165b10eb74.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO user_ai_projection (ai_projection_id, target_id, prompt_hash, status)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (target_id, ai_projection_id) DO NOTHING\n ",+ "query": "\n INSERT INTO user_ai_projection (ai_projection_id, target_id, prompt_hash, status)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (target_id, ai_projection_id)\n DO UPDATE SET last_requested_at = NOW(), updated_at = NOW()\n ","describe": {"columns": [],"parameters": {@@ -13,5 +13,5 @@},"nullable": []},- "hash": "f3d1ff560e0f56fbaa9d7dfc7c0b6c5db474bfc4d596e29c5618abc5307e1e52"+ "hash": "4f7d47d4b75fd81a44c21bd147957428788a190933c8f4aef68587165b10eb74"}diff --git a/rust/cloud-storage/.sqlx/query-9f6467483d25b651cc6521a33b9af371ba30b6c4d9be95071aa4f8be34140e48.json b/rust/cloud-storage/.sqlx/query-9f6467483d25b651cc6521a33b9af371ba30b6c4d9be95071aa4f8be34140e48.jsonnew file mode 100644index 0000000000..de7835140f--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-9f6467483d25b651cc6521a33b9af371ba30b6c4d9be95071aa4f8be34140e48.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM user_ai_projection u\n USING ai_projection p\n WHERE u.ai_projection_id = p.id\n AND p.refresh_cadence = $1\n AND u.last_requested_at < NOW() - (\n CASE p.expiry\n WHEN 'day' THEN INTERVAL '1 day'\n WHEN 'week' THEN INTERVAL '7 days'\n WHEN 'month' THEN INTERVAL '30 days'\n END)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "9f6467483d25b651cc6521a33b9af371ba30b6c4d9be95071aa4f8be34140e48"+}diff --git a/rust/cloud-storage/.sqlx/query-a1c2f53a2400350d4ccde0d3a07e4f2d85893cdbdda343830d4e4ff721e183b9.json b/rust/cloud-storage/.sqlx/query-a1c2f53a2400350d4ccde0d3a07e4f2d85893cdbdda343830d4e4ff721e183b9.jsonnew file mode 100644index 0000000000..e7199c82c8--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-a1c2f53a2400350d4ccde0d3a07e4f2d85893cdbdda343830d4e4ff721e183b9.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE user_ai_projection u\n SET status = 'refreshing', updated_at = NOW()\n FROM ai_projection p\n WHERE u.ai_projection_id = p.id\n AND p.refresh_cadence = $1\n AND u.stale_at IS NOT NULL\n AND u.stale_at < NOW()\n AND u.last_requested_at >= NOW() - (\n CASE p.expiry\n WHEN 'day' THEN INTERVAL '1 day'\n WHEN 'week' THEN INTERVAL '7 days'\n WHEN 'month' THEN INTERVAL '30 days'\n END)\n AND (\n u.status IN ('ready', 'error')\n OR (u.status = 'refreshing' AND u.updated_at < NOW() - INTERVAL '15 minutes')\n )\n RETURNING u.ai_projection_id, u.target_id, p.prompt_hash\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "ai_projection_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "target_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "prompt_hash",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "a1c2f53a2400350d4ccde0d3a07e4f2d85893cdbdda343830d4e4ff721e183b9"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex ae22a1b436..ead9f3c356 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -128,6 +128,32 @@ dependencies = ["workspace-hack",]+[[package]]+name = "ai_projections_refresh_handler"+version = "0.1.0"+dependencies = [+ "anyhow",+ "aws-sdk-sqs",+ "aws-smithy-types",+ "chrono",+ "futures",+ "lambda_runtime",+ "macro_aws_config",+ "macro_config",+ "macro_db_migrator",+ "macro_entrypoint",+ "macro_env",+ "macro_env_var",+ "models_ai_projection",+ "serde",+ "serde_json",+ "sqlx",+ "sqs_client",+ "tokio",+ "tracing",+ "workspace-hack",+]+[[package]]name = "ai_tools"version = "0.1.0"diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex f6a36b4a0c..ce6f8cf296 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -4,6 +4,7 @@ resolver = "2"members = ["agent","ai_projections",+ "ai_projections_refresh_handler","ai_usage","authentication_service","backfill_entity_access",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.rsindex e600951e84..3102e2a6a7 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@@ -90,11 +90,18 @@ impl AiProjectionRepository for AiProjectionRepositoryImpl {target_id: &str,prompt_hash: &str,) -> Result<UserAiProjection, AiProjectionError> {+ // A request for a projection bumps `last_requested_at` so the background+ // refresh handler can tell active instances apart from abandoned ones+ // (which it eventually deletes once they fall outside their expiry+ // window). The prompt and status are intentionally left untouched on+ // conflict: the definition's prompt is immutable and the materialization+ // lifecycle is owned by the worker.sqlx::query!(r#"INSERT INTO user_ai_projection (ai_projection_id, target_id, prompt_hash, status)VALUES ($1, $2, $3, $4)- ON CONFLICT (target_id, ai_projection_id) DO NOTHING+ ON CONFLICT (target_id, ai_projection_id)+ DO UPDATE SET last_requested_at = NOW(), updated_at = NOW()"#,ai_projection_id,target_id,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.rsindex 956d32ad0c..6282ebe70f 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@@ -83,6 +83,68 @@ async fn get_or_create_target_projection_is_idempotent(pool: Pool<Postgres>) ->Ok(())}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("ai_projections"))+)]+async fn get_or_create_target_projection_bumps_last_requested_at(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = AiProjectionRepositoryImpl::new(pool.clone());+ let user = MacroUserIdStr::parse_from_str("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", user.as_ref(), "hash_v1")+ .await?;++ // Backdate the instance so a fresh request must visibly move the timestamp+ // forward (deterministic, no sleeps).+ sqlx::query!(+ r#"+ UPDATE user_ai_projection+ SET last_requested_at = NOW() - INTERVAL '10 days'+ WHERE ai_projection_id = $1 AND target_id = $2+ "#,+ "inbox/important",+ user.as_ref(),+ )+ .execute(&pool)+ .await?;++ // A subsequent request bumps last_requested_at back to ~now, marking the+ // instance as active so the refresh handler won't reap it.+ repo.get_or_create_target_projection("inbox/important", user.as_ref(), "hash_v1")+ .await?;++ let last_requested_at: chrono::DateTime<chrono::Utc> = sqlx::query_scalar!(+ r#"+ SELECT last_requested_at+ FROM user_ai_projection+ WHERE ai_projection_id = $1 AND target_id = $2+ "#,+ "inbox/important",+ user.as_ref(),+ )+ .fetch_one(&pool)+ .await?;++ assert!(+ last_requested_at > chrono::Utc::now() - chrono::Duration::minutes(1),+ "expected last_requested_at to be bumped to ~now, got {last_requested_at}"+ );++ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("ai_projections"))diff --git a/rust/cloud-storage/ai_projections_refresh_handler/Cargo.toml b/rust/cloud-storage/ai_projections_refresh_handler/Cargo.tomlnew file mode 100644index 0000000000..aa7dec3e10--- /dev/null+++ b/rust/cloud-storage/ai_projections_refresh_handler/Cargo.toml@@ -0,0 +1,32 @@+[package]+edition = "2024"+name = "ai_projections_refresh_handler"+publish = false+version = "0.1.0"++[dependencies]+anyhow = { workspace = true }+aws-sdk-sqs = { workspace = true }+macro_aws_config = { path = "../macro_aws_config" }+aws-smithy-types = { workspace = true }+chrono = { workspace = true }+futures = { workspace = true }+lambda_runtime = { workspace = true }+macro_entrypoint = { path = "../macro_entrypoint" }+macro_env = { path = "../macro_env" }+macro_env_var = { path = "../macro_env_var" }+models_ai_projection = { path = "../models_ai_projection" }+serde = { workspace = true }+serde_json = { workspace = true }+sqlx = { workspace = true }+sqs_client = { path = "../sqs_client", default-features = false, features = [+ "ai_projection",+] }+tokio = { workspace = true }+tracing = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }+macro_config = { path = "../macro_config" }++[dev-dependencies]+macro_db_migrator = { path = "../macro_db_migrator" }+tokio = { workspace = true }diff --git a/rust/cloud-storage/ai_projections_refresh_handler/justfile b/rust/cloud-storage/ai_projections_refresh_handler/justfilenew file mode 100644index 0000000000..8d61771833--- /dev/null+++ b/rust/cloud-storage/ai_projections_refresh_handler/justfile@@ -0,0 +1,12 @@+lambda_name := file_name(justfile_directory())++mod ci '../ci.just'++test:+ cargo test --all-features++build compiler="":+ SQLX_OFFLINE=true cargo lambda build {{ if compiler == "" { "" } else { "--compiler " + compiler } }} --release --bin {{lambda_name}} --output-format zip++check:+ SQLX_OFFLINE=true cargo checkdiff --git a/rust/cloud-storage/ai_projections_refresh_handler/src/config.rs b/rust/cloud-storage/ai_projections_refresh_handler/src/config.rsnew file mode 100644index 0000000000..b0ca7cafe8--- /dev/null+++ b/rust/cloud-storage/ai_projections_refresh_handler/src/config.rs@@ -0,0 +1,23 @@+use anyhow::Context;+use macro_env_var::env_vars;++env_vars! {+ pub struct DatabaseUrl;+ pub struct AiProjectionQueue;+}++#[derive(macro_config::MacroConfig)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub struct Config {+ /// The connection URL for the Postgres database this application should use.+ pub database_url: DatabaseUrl,++ /// The ai projection queue+ pub ai_projection_queue: AiProjectionQueue,+}++impl Config {+ pub fn from_env() -> anyhow::Result<Self> {+ macro_config::ConfigLoader::load::<Config>().context("failed to load config")+ }+}diff --git a/rust/cloud-storage/ai_projections_refresh_handler/src/context.rs b/rust/cloud-storage/ai_projections_refresh_handler/src/context.rsnew file mode 100644index 0000000000..7b9c0db64e--- /dev/null+++ b/rust/cloud-storage/ai_projections_refresh_handler/src/context.rs@@ -0,0 +1,7 @@+use std::sync::Arc;++#[derive(Clone)]+pub struct Context {+ pub db: sqlx::Pool<sqlx::Postgres>,+ pub sqs_client: Arc<sqs_client::SQS>,+}diff --git a/rust/cloud-storage/ai_projections_refresh_handler/src/event.rs b/rust/cloud-storage/ai_projections_refresh_handler/src/event.rsnew file mode 100644index 0000000000..2fbda14637--- /dev/null+++ b/rust/cloud-storage/ai_projections_refresh_handler/src/event.rs@@ -0,0 +1,39 @@+//! The EventBridge payload this lambda is invoked with.+//!+//! Each scheduled EventBridge rule fires at a frequency matching one refresh+//! cadence and passes a constant input of the form `{"refresh_cadence":"high"}`.+//! Because the target uses a constant input, the lambda receives this object+//! verbatim rather than the usual EventBridge envelope.++/// How frequently the projections of this cadence are swept. The concrete+/// schedule frequency lives in infrastructure; here the value only selects which+/// projection definitions a given invocation operates on.+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum RefreshCadence {+ /// Swept most frequently.+ High,+ /// Swept at a moderate frequency.+ Medium,+ /// Swept least frequently.+ Low,+}++impl RefreshCadence {+ /// The value as stored in `ai_projection.refresh_cadence`, used to scope+ /// queries to the cadence this invocation is responsible for.+ pub fn as_str(self) -> &'static str {+ match self {+ RefreshCadence::High => "high",+ RefreshCadence::Medium => "medium",+ RefreshCadence::Low => "low",+ }+ }+}++/// The payload delivered by the scheduled EventBridge rule.+#[derive(Debug, serde::Deserialize)]+pub struct RefreshEvent {+ /// The cadence whose projections this invocation should sweep.+ pub refresh_cadence: RefreshCadence,+}diff --git a/rust/cloud-storage/ai_projections_refresh_handler/src/main.rs b/rust/cloud-storage/ai_projections_refresh_handler/src/main.rsnew file mode 100644index 0000000000..fadc62e7d2--- /dev/null+++ b/rust/cloud-storage/ai_projections_refresh_handler/src/main.rs@@ -0,0 +1,75 @@+#![recursion_limit = "256"]+mod config;+mod context;+mod event;+mod refresh;++use anyhow::Context;+use config::Config;+use event::RefreshEvent;+use lambda_runtime::{+ Error, LambdaEvent, run, service_fn,+ tracing::{self},+};+use macro_entrypoint::MacroEntrypoint;+use sqlx::postgres::PgPoolOptions;+use std::sync::Arc;++#[tokio::main]+async fn main() -> Result<(), Error> {+ MacroEntrypoint::default().init();+ tracing::trace!("initiating lambda");++ let config = Config::from_env().context("all necessary env vars should be available")?;++ tracing::trace!("initialized config");++ // We should only ever need 1 connection+ let db = PgPoolOptions::new()+ .min_connections(1)+ .max_connections(1)+ .connect(&config.database_url)+ .await+ .context("could not connect to db")?;++ let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(+ ¯o_aws_config::get_macro_aws_config().await,+ ))+ .ai_projection_queue(&config.ai_projection_queue);++ let ctx = context::Context {+ db,+ sqs_client: Arc::new(sqs_client),+ };++ let func = service_fn(move |event: LambdaEvent<RefreshEvent>| {+ let ctx = ctx.clone();++ async move { handler(ctx, event).await }+ });++ run(func).await+}++/// Runs a refresh sweep for the cadence carried by the scheduled EventBridge+/// event: delete inactive instances, and enqueue a refresh for stale ones.+#[tracing::instrument(skip(ctx, event), err)]+async fn handler(ctx: context::Context, event: LambdaEvent<RefreshEvent>) -> Result<(), Error> {+ let cadence = event.payload.refresh_cadence;+ tracing::info!(+ cadence = cadence.as_str(),+ "running ai projection refresh sweep"+ );++ let stats = refresh::run(&ctx, cadence).await?;++ tracing::info!(+ cadence = cadence.as_str(),+ deleted = stats.deleted,+ refreshed = stats.refreshed,+ enqueue_failures = stats.enqueue_failures,+ "ai projection refresh sweep complete"+ );++ Ok(())+}diff --git a/rust/cloud-storage/ai_projections_refresh_handler/src/refresh.rs b/rust/cloud-storage/ai_projections_refresh_handler/src/refresh.rsnew file mode 100644index 0000000000..e4d5417638--- /dev/null+++ b/rust/cloud-storage/ai_projections_refresh_handler/src/refresh.rs@@ -0,0 +1,177 @@+//! The refresh sweep: for a single cadence, decide per `user_ai_projection`+//! instance whether to delete it, refresh it, or leave it untouched.+//!+//! Decision rules (see `ai_projections.md`):+//! - **Delete** when an instance has not been requested within its expiry window+//! (`now() - last_requested_at > expiry`). A future request recreates it.+//! - **Refresh** when an instance is still active but its cached result is stale+//! (`now() > stale_at`) and it is not already in flight.+//! - **Leave** everything else ("hot") alone.+//!+//! All queries live here in the lambda crate. The `expiry` window is expressed+//! directly in SQL via a `CASE` over the definition's `expiry` text.++#[cfg(test)]+mod test;++use futures::StreamExt;+use models_ai_projection::AiProjectionQueueMessage;+use sqlx::{Pool, Postgres};++use crate::context::Context;+use crate::event::RefreshCadence;++/// How many refresh messages to enqueue concurrently.+const ENQUEUE_CONCURRENCY: usize = 10;++/// Counts produced by a single sweep, for logging.+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]+pub struct RefreshStats {+ /// Inactive instances deleted.+ pub deleted: u64,+ /// Stale instances claimed and queued for refresh.+ pub refreshed: u64,+ /// Refresh messages that failed to enqueue.+ pub enqueue_failures: u64,+}++/// A stale instance that has been claimed (marked `refreshing`) and needs a+/// materialization message enqueued.+#[derive(Debug, Clone, PartialEq, Eq)]+struct RefreshTarget {+ ai_projection_id: String,+ target_id: String,+ prompt_hash: String,+}++/// Runs the refresh sweep for the given cadence: delete inactive instances,+/// claim stale-but-active instances, and enqueue a materialization message for+/// each claimed instance.+#[tracing::instrument(skip(ctx), err)]+pub async fn run(ctx: &Context, cadence: RefreshCadence) -> anyhow::Result<RefreshStats> {+ let deleted = delete_inactive(&ctx.db, cadence).await?;+ tracing::info!(+ cadence = cadence.as_str(),+ deleted,+ "deleted inactive instances"+ );++ let targets = claim_stale(&ctx.db, cadence).await?;+ tracing::info!(+ cadence = cadence.as_str(),+ claimed = targets.len(),+ "claimed stale instances for refresh"+ );++ let enqueue_failures = enqueue_all(ctx, targets.iter()).await;++ let stats = RefreshStats {+ deleted,+ refreshed: targets.len() as u64,+ enqueue_failures,+ };+ Ok(stats)+}++/// Deletes instances of this cadence that have not been requested within their+/// expiry window, regardless of status. Returns the number of rows deleted.+#[tracing::instrument(skip(db), err)]+async fn delete_inactive(db: &Pool<Postgres>, cadence: RefreshCadence) -> anyhow::Result<u64> {+ let result = sqlx::query!(+ r#"+ DELETE FROM user_ai_projection u+ USING ai_projection p+ WHERE u.ai_projection_id = p.id+ AND p.refresh_cadence = $1+ AND u.last_requested_at < NOW() - (+ CASE p.expiry+ WHEN 'day' THEN INTERVAL '1 day'+ WHEN 'week' THEN INTERVAL '7 days'+ WHEN 'month' THEN INTERVAL '30 days'+ END)+ "#,+ cadence.as_str(),+ )+ .execute(db)+ .await?;++ Ok(result.rows_affected())+}++/// Atomically marks stale-but-active instances of this cadence as `refreshing`+/// and returns them so a materialization message can be enqueued for each.+///+/// Doing the selection and the status flip in one statement prevents two+/// overlapping sweeps from both enqueuing the same instance. Instances stuck in+/// `refreshing` for more than 15 minutes (e.g. a previous sweep that failed to+/// enqueue) are reclaimed, mirroring the `processing_ai_projections` lease+/// reclaim convention used by the worker.+#[tracing::instrument(skip(db), err)]+async fn claim_stale(+ db: &Pool<Postgres>,+ cadence: RefreshCadence,+) -> anyhow::Result<Vec<RefreshTarget>> {+ let rows = sqlx::query!(+ r#"+ UPDATE user_ai_projection u+ SET status = 'refreshing', updated_at = NOW()+ FROM ai_projection p+ WHERE u.ai_projection_id = p.id+ AND p.refresh_cadence = $1+ AND u.stale_at IS NOT NULL+ AND u.stale_at < NOW()+ AND u.last_requested_at >= NOW() - (+ CASE p.expiry+ WHEN 'day' THEN INTERVAL '1 day'+ WHEN 'week' THEN INTERVAL '7 days'+ WHEN 'month' THEN INTERVAL '30 days'+ END)+ AND (+ u.status IN ('ready', 'error')+ OR (u.status = 'refreshing' AND u.updated_at < NOW() - INTERVAL '15 minutes')+ )+ RETURNING u.ai_projection_id, u.target_id, p.prompt_hash+ "#,+ cadence.as_str(),+ )+ .fetch_all(db)+ .await?;++ Ok(rows+ .into_iter()+ .map(|row| RefreshTarget {+ ai_projection_id: row.ai_projection_id,+ target_id: row.target_id,+ prompt_hash: row.prompt_hash,+ })+ .collect())+}++/// Enqueues a materialization message for each claimed target with bounded+/// concurrency. A failed enqueue is logged and counted; the instance stays+/// `refreshing` and is reclaimed by a later sweep after the 15-minute window.+async fn enqueue_all<'a>(ctx: &Context, targets: impl Iterator<Item = &'a RefreshTarget>) -> u64 {+ futures::stream::iter(targets)+ .map(|target| async move {+ ctx.sqs_client+ .enqueue_ai_projection_message(AiProjectionQueueMessage {+ ai_projection_id: target.ai_projection_id.clone(),+ target_id: target.target_id.clone(),+ prompt_hash: target.prompt_hash.clone(),+ })+ .await+ .inspect_err(|e| {+ tracing::error!(+ error = ?e,+ ai_projection_id = %target.ai_projection_id,+ target_id = %target.target_id,+ "failed to enqueue ai projection refresh"+ );+ })+ .is_err()+ })+ .buffer_unordered(ENQUEUE_CONCURRENCY)+ .filter(|failed| futures::future::ready(*failed))+ .count()+ .await as u64+}diff --git a/rust/cloud-storage/ai_projections_refresh_handler/src/refresh/test.rs b/rust/cloud-storage/ai_projections_refresh_handler/src/refresh/test.rsnew file mode 100644index 0000000000..f02ecd2602--- /dev/null+++ b/rust/cloud-storage/ai_projections_refresh_handler/src/refresh/test.rs@@ -0,0 +1,362 @@+//! Tests for the refresh sweep query logic, run against a live macrodb.+//!+//! These exercise `delete_inactive` and `claim_stale` directly (the SQS enqueue+//! step is a thin wrapper over `sqs_client` and needs no DB).++use chrono::{DateTime, Duration, Utc};+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::{Pool, Postgres};++use super::*;++/// Inserts a projection definition with the given cadence/expiry.+async fn insert_projection(+ pool: &Pool<Postgres>,+ id: &str,+ refresh_cadence: &str,+ expiry: &str,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO ai_projection (id, prompt, prompt_hash, target_type, refresh_cadence, expiry)+ VALUES ($1, 'prompt', 'hash_v1', 'user', $2, $3)+ "#,+ id,+ refresh_cadence,+ expiry,+ )+ .execute(pool)+ .await?;+ Ok(())+}++/// Inserts a per-target instance with explicit timestamps and status.+#[allow(clippy::too_many_arguments)]+async fn insert_instance(+ pool: &Pool<Postgres>,+ ai_projection_id: &str,+ target_id: &str,+ status: &str,+ generated_at: Option<DateTime<Utc>>,+ stale_at: Option<DateTime<Utc>>,+ last_requested_at: DateTime<Utc>,+ updated_at: DateTime<Utc>,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO user_ai_projection+ (ai_projection_id, target_id, prompt_hash, status,+ generated_at, stale_at, last_requested_at, updated_at)+ VALUES ($1, $2, 'hash_v1', $3, $4, $5, $6, $7)+ "#,+ ai_projection_id,+ target_id,+ status,+ generated_at,+ stale_at,+ last_requested_at,+ updated_at,+ )+ .execute(pool)+ .await?;+ Ok(())+}++/// Reads back an instance's status.+async fn status_of(+ pool: &Pool<Postgres>,+ ai_projection_id: &str,+ target_id: &str,+) -> anyhow::Result<Option<String>> {+ let status = sqlx::query_scalar!(+ r#"+ SELECT status FROM user_ai_projection+ WHERE ai_projection_id = $1 AND target_id = $2+ "#,+ ai_projection_id,+ target_id,+ )+ .fetch_optional(pool)+ .await?;+ Ok(status)+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn delete_inactive_removes_only_inactive_of_cadence(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ insert_projection(&pool, "high/day", "high", "day").await?;+ insert_projection(&pool, "low/day", "low", "day").await?;++ let now = Utc::now();+ let stale = Some(now - Duration::hours(1));+ let generated = Some(now - Duration::days(2));++ // Inactive (not requested in 2 days, day expiry) -> should be deleted.+ insert_instance(+ &pool,+ "high/day",+ "inactive",+ "ready",+ generated,+ stale,+ now - Duration::days(2),+ now - Duration::days(2),+ )+ .await?;+ // Inactive but a different cadence -> the high sweep must not touch it.+ insert_instance(+ &pool,+ "low/day",+ "inactive_low",+ "ready",+ generated,+ stale,+ now - Duration::days(2),+ now - Duration::days(2),+ )+ .await?;+ // Active (requested just now) -> must survive.+ insert_instance(+ &pool, "high/day", "active", "ready", generated, stale, now, now,+ )+ .await?;+ // Cold and inactive -> deletion applies regardless of status.+ insert_instance(+ &pool,+ "high/day",+ "cold_inactive",+ "cold",+ None,+ None,+ now - Duration::days(5),+ now - Duration::days(5),+ )+ .await?;++ let deleted = delete_inactive(&pool, RefreshCadence::High).await?;+ assert_eq!(+ deleted, 2,+ "inactive ready + inactive cold of the high cadence"+ );++ assert_eq!(status_of(&pool, "high/day", "inactive").await?, None);+ assert_eq!(status_of(&pool, "high/day", "cold_inactive").await?, None);+ assert_eq!(+ status_of(&pool, "high/day", "active").await?.as_deref(),+ Some("ready")+ );+ // Untouched: belongs to the low cadence.+ assert_eq!(+ status_of(&pool, "low/day", "inactive_low")+ .await?+ .as_deref(),+ Some("ready")+ );++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn claim_stale_selects_and_marks_refreshing(pool: Pool<Postgres>) -> anyhow::Result<()> {+ insert_projection(&pool, "high/day", "high", "day").await?;+ insert_projection(&pool, "med/day", "medium", "day").await?;++ let now = Utc::now();+ let generated = Some(now - Duration::hours(2));+ let stale_past = Some(now - Duration::hours(1));+ let stale_future = Some(now + Duration::hours(1));+ let active = now; // requested recently++ // stale + active + ready -> claimed.+ insert_instance(+ &pool,+ "high/day",+ "ready_stale",+ "ready",+ generated,+ stale_past,+ active,+ now,+ )+ .await?;+ // stale + active + error -> claimed (we retry errored instances).+ insert_instance(+ &pool,+ "high/day",+ "error_stale",+ "error",+ generated,+ stale_past,+ active,+ now,+ )+ .await?;+ // stale + active + loading -> in flight, skipped.+ insert_instance(+ &pool,+ "high/day",+ "loading_stale",+ "loading",+ generated,+ stale_past,+ active,+ now,+ )+ .await?;+ // stale + active + cold -> freshly queued, skipped.+ insert_instance(+ &pool,+ "high/day",+ "cold_stale",+ "cold",+ None,+ stale_past,+ active,+ now,+ )+ .await?;+ // hot (stale_at in the future) + ready -> left alone.+ insert_instance(+ &pool,+ "high/day",+ "ready_hot",+ "ready",+ generated,+ stale_future,+ active,+ now,+ )+ .await?;+ // refreshing but stuck > 15 min + stale -> reclaimed.+ insert_instance(+ &pool,+ "high/day",+ "stuck_refreshing",+ "refreshing",+ generated,+ stale_past,+ active,+ now - Duration::minutes(20),+ )+ .await?;+ // refreshing recently (< 15 min) -> still in flight, skipped.+ insert_instance(+ &pool,+ "high/day",+ "fresh_refreshing",+ "refreshing",+ generated,+ stale_past,+ active,+ now - Duration::minutes(2),+ )+ .await?;+ // stale + ready but a different cadence -> not touched by the high sweep.+ insert_instance(+ &pool,+ "med/day",+ "other_cadence",+ "ready",+ generated,+ stale_past,+ active,+ now,+ )+ .await?;++ let mut claimed = claim_stale(&pool, RefreshCadence::High).await?;+ claimed.sort_by(|a, b| a.target_id.cmp(&b.target_id));++ let claimed_ids: Vec<&str> = claimed.iter().map(|t| t.target_id.as_str()).collect();+ assert_eq!(+ claimed_ids,+ vec!["error_stale", "ready_stale", "stuck_refreshing"]+ );+ // The returned prompt_hash comes from the definition.+ assert!(claimed.iter().all(|t| t.prompt_hash == "hash_v1"));++ // Claimed instances are now marked refreshing.+ for id in ["ready_stale", "error_stale", "stuck_refreshing"] {+ assert_eq!(+ status_of(&pool, "high/day", id).await?.as_deref(),+ Some("refreshing"),+ "{id} should be marked refreshing"+ );+ }+ // Skipped instances keep their status.+ assert_eq!(+ status_of(&pool, "high/day", "loading_stale")+ .await?+ .as_deref(),+ Some("loading")+ );+ assert_eq!(+ status_of(&pool, "high/day", "cold_stale").await?.as_deref(),+ Some("cold")+ );+ assert_eq!(+ status_of(&pool, "high/day", "ready_hot").await?.as_deref(),+ Some("ready")+ );+ assert_eq!(+ status_of(&pool, "high/day", "fresh_refreshing")+ .await?+ .as_deref(),+ Some("refreshing")+ );+ assert_eq!(+ status_of(&pool, "med/day", "other_cadence")+ .await?+ .as_deref(),+ Some("ready")+ );++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn expiry_window_scales_with_definition(pool: Pool<Postgres>) -> anyhow::Result<()> {+ // Same cadence, different expiry windows.+ insert_projection(&pool, "high/week", "high", "week").await?;++ let now = Utc::now();+ let stale = Some(now - Duration::hours(1));+ let generated = Some(now - Duration::days(2));++ // Requested 3 days ago: inactive under a `day` expiry, but still active under+ // a `week` expiry -> not deleted, and (being stale) eligible for refresh.+ insert_instance(+ &pool,+ "high/week",+ "three_days",+ "ready",+ generated,+ stale,+ now - Duration::days(3),+ now - Duration::days(3),+ )+ .await?;+ // Requested 10 days ago: inactive even under a `week` expiry -> deleted.+ insert_instance(+ &pool,+ "high/week",+ "ten_days",+ "ready",+ generated,+ stale,+ now - Duration::days(10),+ now - Duration::days(10),+ )+ .await?;++ let deleted = delete_inactive(&pool, RefreshCadence::High).await?;+ assert_eq!(deleted, 1);+ assert_eq!(status_of(&pool, "high/week", "ten_days").await?, None);++ let claimed = claim_stale(&pool, RefreshCadence::High).await?;+ assert_eq!(claimed.len(), 1);+ assert_eq!(claimed[0].target_id, "three_days");++ Ok(())+}diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex f8ff897f03..62e957c8fc 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -57,6 +57,7 @@ build_lambdas compiler="":ulimit -n 10240 && just email_scheduled_handler/build {{compiler}}ulimit -n 10240 && just email_sfs_delete_handler/build {{compiler}}ulimit -n 10240 && just image_optimizer/build {{compiler}}+ ulimit -n 10240 && just ai_projections_refresh_handler/build {{compiler}}# TESTING@@ -114,6 +115,7 @@ setup_test_envs:echo "DATABASE_URL={{ DATABASE_URL }}" >> ./call_recording_preview_handler/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./share_permission_db_utils/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./ai_projections/.env+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./ai_projections_refresh_handler/.envsetup_macrodb:just macro_db_client/create_db