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.

chore: remove insight service (#897)

Eric Hayes28743fdad25c
diff --git a/.github/services-config.json b/.github/services-config.json
index 4d0beffde9..a18967a5ec 100644
--- a/.github/services-config.json
+++ b/.github/services-config.json
@@ -85,12 +85,6 @@
],
"stack_path": "infra/stacks/experiment-service/**"
},
- "insight-service": {
- "source_paths": [
- "rust/cloud-storage/insight_service/**"
- ],
- "stack_path": "infra/stacks/insight-service/**"
- },
"metering-service": {
"source_paths": [
"rust/cloud-storage/metering_service/**"
diff --git a/.github/workflows/deploy-service-generic.yml b/.github/workflows/deploy-service-generic.yml
index 109dfc7f40..4e1694ace2 100644
--- a/.github/workflows/deploy-service-generic.yml
+++ b/.github/workflows/deploy-service-generic.yml
@@ -24,7 +24,6 @@ on:
- email-service
- email-suppression
- experiment-service
- - insight-service
- lambda-aggregate-frecency
- link-sharing
- metering-service
diff --git a/infra/bun.lock b/infra/bun.lock
index b268e46f87..e5c6654063 100644
--- a/infra/bun.lock
+++ b/infra/bun.lock
@@ -118,10 +118,7 @@
"name": "fusion-auth",
"version": "0.0.0",
},
- "stacks/insight-service": {
- "name": "insight-service-stack",
- "version": "0.0.0",
- },
+
"stacks/link-sharing": {
"name": "link-sharing-stack",
"version": "0.0.0",
@@ -712,7 +709,6 @@
"ini": ["[email protected]", "", {}, "sha512-7PnF4oN3CvZF23ADhA5wRaYEQpJ8qygSkbtTXWBeXWXmEVRXK+1ITciHWwHhsjv1TmW0MgacIv6hEi5pX5NQdA=="],
- "insight-service-stack": ["insight-service-stack@workspace:stacks/insight-service"],
"ip-address": ["[email protected]", "", { "dependencies": { "jsbn": "1.1.0", "sprintf-js": "^1.1.3" } }, "sha512-zHtQzGojZXTwZTHQqra+ETKd4Sn3vgi7uBmlPoXVWZqYvuKmtI0l/VZTjqGmJY9x88GGOaZ9+G9ES8hC4T4X8g=="],
diff --git a/infra/stacks/document-cognition-service/index.ts b/infra/stacks/document-cognition-service/index.ts
index 9b4a369800..d4de2949f3 100644
--- a/infra/stacks/document-cognition-service/index.ts
+++ b/infra/stacks/document-cognition-service/index.ts
@@ -148,23 +148,6 @@ export const deleteChatQueueName: pulumi.Output<string> =
const { notificationQueueName, notificationQueueArn } = getMacroNotify();
-// import the insight-service-block
-const insightServiceStack = new pulumi.StackReference('insight-service-stack', {
- name: `macro-inc/insight-service/${stack}`,
-});
-
-const insightContextQueueArn: pulumi.Output<string> = insightServiceStack
- .getOutput('contextQueueArn')
- .apply((arn) => arn as string);
-
-const insightContextQueueName: pulumi.Output<string> = insightServiceStack
- .getOutput('contextQueueName')
- .apply((name) => name as string)
- .apply((name) => {
- pulumi.log.info(`INSIGHT QUEUE NAME, ${name}`);
- return name;
- });
-
const { searchEventQueueName, searchEventQueueArn } = getSearchEventQueue();
const searchServiceStack = new pulumi.StackReference('search-service-stack', {
@@ -199,7 +182,6 @@ const documentCognitionService = new DocumentCognitionService(
documentTextExtractorQueueArn,
deleteChatQueueArn,
searchEventQueueArn,
- insightContextQueueArn,
notificationQueueArn,
],
containerEnvVars: [
@@ -274,10 +256,6 @@ const documentCognitionService = new DocumentCognitionService(
stack === 'prod' ? '' : `-${stack}`
}.macro.com`,
},
- {
- name: 'INSIGHT_CONTEXT_QUEUE',
- value: pulumi.interpolate`${insightContextQueueName}`,
- },
{
name: 'COMMS_SERVICE_URL',
value: `https://comms-service${
diff --git a/infra/stacks/email-service/index.ts b/infra/stacks/email-service/index.ts
index fdb4352c46..12a386f04a 100644
--- a/infra/stacks/email-service/index.ts
+++ b/infra/stacks/email-service/index.ts
@@ -187,18 +187,6 @@ export const sfsUploaderQueueName = pulumi.interpolate`${sfs_uploader_queue.queu
const { searchEventQueueName, searchEventQueueArn } = getSearchEventQueue();
-const insightServiceStack = new pulumi.StackReference('insight-service-stack', {
- name: `macro-inc/insight-service/${stack}`,
-});
-
-const insightContextQueueArn: pulumi.Output<string> = insightServiceStack
- .getOutput('contextQueueArn')
- .apply((arn) => arn as string);
-
-const insightContextQueueName: pulumi.Output<string> = insightServiceStack
- .getOutput('contextQueueName')
- .apply((name) => name as string);
-
// Retrieve name of queue used Contacts Service
const contactsServiceStack: pulumi.StackReference = new pulumi.StackReference(
'contacts-service-stack',
@@ -244,7 +232,6 @@ const queueArns = [
linkManagerQueueArn,
scheduledQueueArn,
searchEventQueueArn,
- insightContextQueueArn,
backfillQueueArn,
sfsUploaderQueueArn,
contactsQueueArn,
@@ -337,7 +324,7 @@ emailAttachmentBucket.attachCloudfrontPolicy({
const containerEnvVars = [
{
name: 'RUST_LOG',
- value: `email=${stack === 'prod' ? 'debug' : 'debug'},email_service=${stack === 'prod' ? 'debug' : 'debug'},pubsub_workers=${stack === 'prod' ? 'debug' : 'debug'},email_db_client=${stack === 'prod' ? 'info' : 'debug'},gmail_client=${stack === 'prod' ? 'info' : 'debug'},tower_http=info,insight_service_client=${stack === 'prod' ? 'info' : 'debug'}`,
+ value: `email=${stack === 'prod' ? 'debug' : 'debug'},email_service=${stack === 'prod' ? 'debug' : 'debug'},pubsub_workers=${stack === 'prod' ? 'debug' : 'debug'},email_db_client=${stack === 'prod' ? 'info' : 'debug'},gmail_client=${stack === 'prod' ? 'info' : 'debug'},tower_http=info`,
},
{
name: 'ENVIRONMENT',
@@ -383,10 +370,6 @@ const containerEnvVars = [
name: 'NOTIFICATION_QUEUE',
value: pulumi.interpolate`${notificationQueueName}`,
},
- {
- name: 'INSIGHT_CONTEXT_QUEUE',
- value: pulumi.interpolate`${insightContextQueueName}`,
- },
{
name: 'JWT_SECRET_KEY',
value: pulumi.interpolate`${JWT_SECRET_KEY}`,
diff --git a/infra/stacks/insight-service/Pulumi.dev.yaml b/infra/stacks/insight-service/Pulumi.dev.yaml
deleted file mode 100644
index 512db116d2..0000000000
--- a/infra/stacks/insight-service/Pulumi.dev.yaml
+++ /dev/null
@@ -1,10 +0,0 @@
-config:
- aws-native:region: us-east-1
- aws:region: us-east-1
- insight-service:macro_db_secret_key: macro-db-dev
- insight-service:jwt_secret_key: fusionauth-jwt-secret-dev
- insight-service:fusionauth_client_id: fusionauth-client-id-key-dev
- insight-service:fusionauth_issuer: fusionauth-dev.macro.com
- insight-service:open-router-api-key: open-router-api-key-dev-v2
- insight-service:sync_service_auth_key: sync-service-key-dev
- insight-service:service_internal_auth_key: document-storage-service-auth-key-dev
diff --git a/infra/stacks/insight-service/Pulumi.prod.yaml b/infra/stacks/insight-service/Pulumi.prod.yaml
deleted file mode 100644
index d05e4c5480..0000000000
--- a/infra/stacks/insight-service/Pulumi.prod.yaml
+++ /dev/null
@@ -1,10 +0,0 @@
-config:
- aws-native:region: us-east-1
- aws:region: us-east-1
- insight-service:macro_db_secret_key: macro-db-prod
- insight-service:jwt_secret_key: fusionauth-jwt-secret-prod
- insight-service:fusionauth_client_id: fusionauth-client-id-key-prod
- insight-service:fusionauth_issuer: auth.macro.com
- insight-service:open-router-api-key: open-router-api-key-prod-v2
- insight-service:sync_service_auth_key: sync-service-key-prod
- insight-service:service_internal_auth_key: document-storage-service-auth-key-prod
diff --git a/infra/stacks/insight-service/Pulumi.yaml b/infra/stacks/insight-service/Pulumi.yaml
deleted file mode 100644
index c2d5051874..0000000000
--- a/infra/stacks/insight-service/Pulumi.yaml
+++ /dev/null
@@ -1,3 +0,0 @@
-name: insight-service
-runtime: nodejs
-description: Macro insight service
diff --git a/infra/stacks/insight-service/index.ts b/infra/stacks/insight-service/index.ts
deleted file mode 100644
index 2337cd39cd..0000000000
--- a/infra/stacks/insight-service/index.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-import * as aws from '@pulumi/aws';
-import * as pulumi from '@pulumi/pulumi';
-import { Queue } from '../../packages/resources';
-import { config, getMacroApiToken, stack } from '../../packages/shared';
-import { get_coparse_api_vpc } from '../../packages/vpc';
-import { InsightService } from './service';
-
-const project = 'insight-service';
-
-const tags = {
- environment: stack,
- tech_lead: 'ehayes',
- project,
-};
-
-const contextQueue = new Queue(project, {
- tags,
- maxReceiveCount: 2,
- fifoQueue: true,
-});
-
-export const contextQueueArn = contextQueue.queue.arn;
-export const contextQueueName = contextQueue.queue.name;
-
-const MACRODB_URL = aws.secretsmanager
- .getSecretVersionOutput({
- secretId: config.require(`macro_db_secret_key`),
- })
- .apply((secret) => secret.secretString);
-
-const coparse_api_vpc = get_coparse_api_vpc();
-
-type InsightServiceEnvVars = {
- MACRODB_URL: pulumi.Output<string> | string;
- ENVIRONMENT: pulumi.Output<string> | string;
- RUST_LOG: pulumi.Output<string> | string;
- INSIGHT_CONTEXT_QUEUE: pulumi.Output<string> | string;
- OPEN_ROUTER_API_KEY: pulumi.Output<string> | string;
- AUDIENCE: pulumi.Output<string> | string;
- ISSUER: pulumi.Output<string> | string;
- JWT_SECRET_KEY: pulumi.Output<string> | string;
- SERVICE_INTERNAL_AUTH_KEY: pulumi.Output<string> | string;
- DOCUMENT_STORAGE_SERVICE_URL: pulumi.Output<string> | string;
- DOCUMENT_COGNITION_SERVICE_URL: pulumi.Output<string> | string;
- SYNC_SERVICE_AUTH_KEY: pulumi.Output<string> | string;
- SYNC_SERVICE_URL: pulumi.Output<string> | string;
- EMAIL_SERVICE_URL: pulumi.Output<string> | string;
- MACRO_API_TOKEN_ISSUER: pulumi.Output<string> | string;
- MACRO_API_TOKEN_PUBLIC_KEY: pulumi.Output<string> | string;
- LEXICAL_SERVICE_URL: pulumi.Output<string> | string;
-};
-const cloudStorageStack = new pulumi.StackReference('cloud-storage-stack', {
- name: `macro-inc/document-storage/${stack}`,
-});
-
-const cloudStorageClusterArn: pulumi.Output<string> = cloudStorageStack
- .getOutput('cloudStorageClusterArn')
- .apply((arn) => arn as string);
-
-const OPEN_ROUTER_API_KEY = aws.secretsmanager
- .getSecretVersionOutput({
- secretId: config.require('open-router-api-key'),
- })
- .apply((secret) => secret.secretString);
-
-const JWT_SECRET_KEY = config.require(`jwt_secret_key`);
-const fusionauthClientIdSecretKey = config.require(`fusionauth_client_id`);
-
-const FUSIONAUTH_CLIENT_ID = aws.secretsmanager
- .getSecretVersionOutput({
- secretId: fusionauthClientIdSecretKey,
- })
- .apply((secret) => secret.secretString);
-const FUSIONAUTH_ISSUER = config.require(`fusionauth_issuer`);
-
-const SERVICE_INTERNAL_AUTH_KEY_KEY = config.require(
- `service_internal_auth_key`
-);
-const SERVICE_INTERNAL_AUTH_KEY: pulumi.Output<string> = aws.secretsmanager
- .getSecretVersionOutput({ secretId: SERVICE_INTERNAL_AUTH_KEY_KEY })
- .apply((secret) => secret.secretString);
-
-const SYNC_SERVICE_AUTH_KEY = config.require(`sync_service_auth_key`);
-const syncServiceAuthKeyArn: pulumi.Output<string> = aws.secretsmanager
- .getSecretVersionOutput({ secretId: SYNC_SERVICE_AUTH_KEY })
- .apply((secret) => secret.arn);
-
-const DOCUMENT_STORAGE_SERVICE_URL = `https://cloud-storage${stack === 'prod' ? '' : `-${stack}`}.macro.com`;
-const DOCUMENT_COGNITION_SERVICE_URL = `https://document-cognition${stack === 'prod' ? '' : `-${stack}`}.macro.com`;
-
-// NOTE: from email-service-stack, hardcoded to avoid circular dependency
-const emailServiceUrl = `https://email-service${stack === 'prod' ? '' : `-${stack}`}.macro.com`;
-
-const MACRO_API_TOKENS = getMacroApiToken();
-
-const vars: InsightServiceEnvVars = {
- MACRODB_URL: pulumi.interpolate`${MACRODB_URL}`,
- ENVIRONMENT: stack,
- RUST_LOG: `insight_service=${stack === 'prod' ? 'info' : 'debug'},ai=${stack === 'prod' ? 'info' : 'debug'}`,
- INSIGHT_CONTEXT_QUEUE: pulumi.interpolate`${contextQueueName}`,
- OPEN_ROUTER_API_KEY: pulumi.interpolate`${OPEN_ROUTER_API_KEY}`,
- JWT_SECRET_KEY: pulumi.interpolate`${JWT_SECRET_KEY}`,
- AUDIENCE: pulumi.interpolate`${FUSIONAUTH_CLIENT_ID}`,
- ISSUER: pulumi.interpolate`${FUSIONAUTH_ISSUER}`,
- SERVICE_INTERNAL_AUTH_KEY: pulumi.interpolate`${SERVICE_INTERNAL_AUTH_KEY}`,
- DOCUMENT_STORAGE_SERVICE_URL,
- DOCUMENT_COGNITION_SERVICE_URL,
- SYNC_SERVICE_AUTH_KEY: pulumi.interpolate`${SYNC_SERVICE_AUTH_KEY}`,
- SYNC_SERVICE_URL: `https://sync-service-${stack === 'prod' ? 'prod2' : 'dev3'}.macroverse.workers.dev`,
- EMAIL_SERVICE_URL: pulumi.interpolate`${emailServiceUrl}`,
- MACRO_API_TOKEN_ISSUER: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenIssuer}`,
- MACRO_API_TOKEN_PUBLIC_KEY: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenPublicKey}`,
- LEXICAL_SERVICE_URL: `https://lexical-service-${stack}.macroverse.workers.dev`,
-};
-
-const insightGenerationServiceEnvVars = Object.entries(vars).map(([k, v]) => ({
- name: k,
- value: v,
-}));
-
-const jwtSecretKeyArn: pulumi.Output<string> = aws.secretsmanager
- .getSecretVersionOutput({ secretId: JWT_SECRET_KEY })
- .apply((secret) => secret.arn);
-
-const secretKeyArns = [
- jwtSecretKeyArn,
- syncServiceAuthKeyArn,
- MACRO_API_TOKENS.macroApiTokenPublicKeyArn,
-];
-
-new InsightService(`insight-service-${stack}`, {
- ecsClusterArn: cloudStorageClusterArn,
- vpc: coparse_api_vpc,
- platform: {
- family: 'linux',
- architecture: 'amd64',
- },
- queueArn: contextQueueArn,
- envVars: insightGenerationServiceEnvVars,
- tags,
- secretKeyArns,
- port: 8080,
-});
diff --git a/infra/stacks/insight-service/justfile b/infra/stacks/insight-service/justfile
deleted file mode 100644
index 952ac1089f..0000000000
--- a/infra/stacks/insight-service/justfile
+++ /dev/null
@@ -1,3 +0,0 @@
-deploy-dev:
- pulumi up --stack macro-inc/dev
-
diff --git a/infra/stacks/insight-service/package.json b/infra/stacks/insight-service/package.json
deleted file mode 100644
index 23aa7bcdf5..0000000000
--- a/infra/stacks/insight-service/package.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "name": "insight-service-stack",
- "version": "0.0.0",
- "private": true,
- "license": "MIT",
- "main": "index.ts"
-}
\ No newline at end of file
diff --git a/infra/stacks/insight-service/service.ts b/infra/stacks/insight-service/service.ts
deleted file mode 100644
index 3f4845d07f..0000000000
--- a/infra/stacks/insight-service/service.ts
+++ /dev/null
@@ -1,313 +0,0 @@
-import * as aws from '@pulumi/aws';
-import * as awsx from '@pulumi/awsx';
-import * as pulumi from '@pulumi/pulumi';
-import {
- DATADOG_API_KEY,
- datadogAgentContainer,
- fargateLogRouterSidecarContainer,
- serviceLoadBalancer,
-} from '../../packages/resources';
-import { EcrImage } from '../../packages/service';
-import { BASE_DOMAIN, stack } from '../../packages/shared';
-
-const BASE_NAME = 'insight-service';
-const BASE_PATH = '../../../rust/cloud-storage';
-
-export const USER_INSIGHT_DOMAIN_NAME = `insight-service${
- stack === 'prod' ? '' : `-${stack}`
-}.${BASE_DOMAIN}`;
-
-type InsightServiceArgs = {
- ecsClusterArn: pulumi.Input<string>;
- vpc: {
- vpcId: pulumi.Output<string> | string;
- publicSubnetIds: pulumi.Output<string[]> | string[];
- privateSubnetIds: pulumi.Output<string[]> | string[];
- };
- platform: { family: string; architecture: 'amd64' | 'arm64' };
- queueArn: pulumi.Input<string>;
- envVars: { name: string; value: pulumi.Input<string> }[];
- tags: Record<string, string>;
- secretKeyArns: pulumi.Output<string>[] | string[];
- port: number;
-};
-
-export class InsightService extends pulumi.ComponentResource {
- public role: aws.iam.Role;
- public service: awsx.ecs.FargateService;
- public domain: string;
- public lb: aws.lb.LoadBalancer;
- public listener: aws.lb.Listener;
- public targetGroup: aws.lb.TargetGroup;
-
- constructor(
- name: string,
- {
- ecsClusterArn,
- vpc,
- platform,
- queueArn,
- envVars,
- tags,
- secretKeyArns,
- port,
- }: InsightServiceArgs,
- opts?: pulumi.ComponentResourceOptions
- ) {
- super('my:components:UserInsightService', name, {}, opts);
-
- const image = new EcrImage(
- `${BASE_NAME}-image-${stack}`,
- {
- repositoryId: `${BASE_NAME}-ecr-${stack}`,
- repositoryName: `${BASE_NAME}-${stack}`,
- imageId: `${BASE_NAME}-image-${stack}`,
- imagePath: BASE_PATH,
- dockerfile: 'Dockerfile',
- platform,
- buildArgs: {
- SERVICE_NAME: 'insight_service',
- },
- tags,
- },
- { parent: this }
- );
-
- const serviceSg = new aws.ec2.SecurityGroup(
- `${BASE_NAME}-sg-${stack}`,
- {
- name: `${BASE_NAME}-sg-${stack}`,
- vpcId: vpc.vpcId,
- description: `${BASE_NAME} service security group`,
- tags,
- },
- { parent: this }
- );
-
- const queuePolicy = new aws.iam.Policy(
- `${BASE_NAME}-sqs-policy-${stack}`,
- {
- policy: {
- Version: '2012-10-17',
- Statement: [
- {
- Action: [
- 'sqs:ReceiveMessage',
- 'sqs:DeleteMessage',
- 'sqs:GetQueueAttributes',
- ],
- Resource: [queueArn],
- Effect: 'Allow',
- },
- ],
- },
- tags,
- },
- { parent: this }
- );
-
- const serviceAlbSg = new aws.ec2.SecurityGroup(
- `${BASE_NAME}-alb-sg-${stack}`,
- {
- name: `${BASE_NAME}-alb-sg-${stack}`,
- description: `${BASE_NAME} application load balancer security group`,
- vpcId: vpc.vpcId,
- tags: tags,
- },
- { parent: this }
- );
-
- new aws.vpc.SecurityGroupEgressRule(
- `${BASE_NAME}-out-service`,
- {
- description: 'Allow traffic to the service security group',
- securityGroupId: serviceAlbSg.id,
- referencedSecurityGroupId: serviceSg.id,
- fromPort: port,
- ipProtocol: 'tcp',
- toPort: port,
- tags,
- },
- { parent: this }
- );
-
- new aws.vpc.SecurityGroupIngressRule(
- `${BASE_NAME}-alb-in`,
- {
- securityGroupId: serviceSg.id,
- description: 'Allow inbound traffic from the services ALB',
- referencedSecurityGroupId: serviceAlbSg.id,
- fromPort: port,
- toPort: port,
- ipProtocol: 'tcp',
- tags: tags,
- },
- { parent: this }
- );
-
- new aws.vpc.SecurityGroupEgressRule(
- `${BASE_NAME}-all-out`,
- {
- securityGroupId: serviceSg.id,
- description: 'Allow all outbound',
- cidrIpv4: '0.0.0.0/0',
- ipProtocol: '-1',
- tags: tags,
- },
- { parent: this }
- );
-
- new aws.vpc.SecurityGroupIngressRule(
- `${BASE_NAME}-https`,
- {
- securityGroupId: serviceAlbSg.id,
- description: 'Allow inbound HTTPS traffic',
- cidrIpv4: '0.0.0.0/0',
- fromPort: 443,
- ipProtocol: 'tcp',
- toPort: 443,
- tags: tags,
- },
- { parent: this }
- );
-
- const { targetGroup, lb, listener } = serviceLoadBalancer(this, {
- serviceName: BASE_NAME,
- serviceContainerPort: port,
- healthCheckPath: '/health',
- vpc,
- albSecurityGroupId: serviceAlbSg.id,
- isPrivate: false,
- tags,
- idleTimeout: 3600,
- });
-
- this.targetGroup = targetGroup;
- this.lb = lb;
- this.listener = listener;
-
- const secretPolicy = new aws.iam.Policy(
- `${BASE_NAME}-secrets-policy-${stack}`,
- {
- name: `${BASE_NAME}-secrets-manager-policy-${stack}`,
- policy: {
- Version: '2012-10-17',
- Statement: [
- {
- Action: [
- 'secretsmanager:GetSecretValue',
- 'secretsmanager:DescribeSecret',
- ],
- Resource: secretKeyArns,
- Effect: 'Allow',
- },
- ],
- },
- tags,
- },
- { parent: this }
- );
-
- this.role = new aws.iam.Role(
- `${BASE_NAME}-task-role`,
- {
- name: `${BASE_NAME}-role-${stack}`,
- assumeRolePolicy: {
- Version: '2012-10-17',
- Statement: [
- {
- Action: 'sts:AssumeRole',
- Principal: {
- Service: 'ecs-tasks.amazonaws.com',
- },
- Effect: 'Allow',
- Sid: '',
- },
- ],
- },
- managedPolicyArns: [queuePolicy.arn, secretPolicy.arn],
- tags,
- },
- { parent: this }
- );
-
- this.service = new awsx.ecs.FargateService(
- `${BASE_NAME}`,
- {
- cluster: ecsClusterArn,
- tags,
- networkConfiguration: {
- subnets: vpc.privateSubnetIds,
- securityGroups: [serviceSg.id],
- },
- desiredCount: 1,
- taskDefinitionArgs: {
- taskRole: {
- roleArn: this.role.arn,
- },
- containers: {
- log_router: fargateLogRouterSidecarContainer,
- datadog_agent: datadogAgentContainer,
- service: {
- name: BASE_NAME,
- image: image.image.imageUri,
- stopTimeout: 10, // 10 seconds to force kill the task
- cpu: 256,
- memory: 512,
- environment: envVars,
- essential: true,
- portMappings: [
- {
- containerPort: port,
- hostPort: port,
- appProtocol: 'http',
- targetGroup,
- name: `${BASE_NAME}-tcp-${stack}`,
- },
- ],
- logConfiguration: {
- logDriver: 'awsfirelens',
- options: {
- Name: 'datadog',
- Host: 'http-intake.logs.us5.datadoghq.com',
- apikey: DATADOG_API_KEY,
- dd_service: `${BASE_NAME}-${stack}`,
- dd_source: 'fargate',
- dd_tags: `project:unfurl-service, env:${stack}`,
- provider: 'ecs',
- },
- },
- },
- },
- runtimePlatform: {
- operatingSystemFamily: platform.family.toUpperCase(),
- cpuArchitecture:
- platform.architecture === 'amd64' ? 'X86_64' : 'ARM64',
- },
- },
- },
- { parent: this }
- );
-
- const zone = aws.route53.getZoneOutput({ name: BASE_DOMAIN });
-
- new aws.route53.Record(
- `${BASE_NAME}-domain-record`,
- {
- name: `${USER_INSIGHT_DOMAIN_NAME}`,
- type: 'A',
- zoneId: zone.zoneId,
- aliases: [
- {
- evaluateTargetHealth: false,
- name: lb.dnsName,
- zoneId: lb.zoneId,
- },
- ],
- },
- { parent: this }
- );
-
- this.domain = `https://${USER_INSIGHT_DOMAIN_NAME}`;
- }
-}
diff --git a/infra/stacks/insight-service/tsconfig.json b/infra/stacks/insight-service/tsconfig.json
deleted file mode 100644
index 01bddbfc42..0000000000
--- a/infra/stacks/insight-service/tsconfig.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "extends": "../../tsconfig.json",
-}
\ No newline at end of file
diff --git a/js/app/packages/app/component/settings/AiMemory/AiMemory.tsx b/js/app/packages/app/component/settings/AiMemory/AiMemory.tsx
deleted file mode 100644
index c6375f730f..0000000000
--- a/js/app/packages/app/component/settings/AiMemory/AiMemory.tsx
+++ /dev/null
@@ -1,85 +0,0 @@
-import { LoadingSpinner } from '@core/component/LoadingSpinner';
-import { isErr } from '@core/util/maybeResult';
-import { insightClient } from '@service-insight/client';
-import { Match, onMount, Switch } from 'solid-js';
-import { MemoryList } from './component/MemoryList';
-import {
- insightLoadError,
- insights as insightsSignal,
- loadError,
- memories as memoriesSignal,
- PAGE_SIZE,
-} from './signal';
-
-async function fetchMemories() {
- const [, setLoadError] = loadError;
- const [, setMemories] = memoriesSignal;
- const [, setInsightLoadError] = insightLoadError;
- const [, setInsights] = insightsSignal;
-
- const insights = await insightClient.getUserInsight({
- limit: PAGE_SIZE * 5,
- generated: true,
- offset: 0,
- });
-
- if (isErr(insights)) {
- const [err] = insights;
- setInsightLoadError(err[0].code);
- } else {
- const [, insightData] = insights;
- setInsights(insightData);
- }
-
- const memories = await insightClient.getUserInsight({
- limit: PAGE_SIZE * 5,
- generated: false,
- offset: 0,
- });
-
- if (isErr(memories)) {
- const [err] = memories;
- setLoadError(err[0].code);
- } else {
- const [, insightData] = memories;
- setMemories(insightData);
- }
-}
-
-export function AiMemory() {
- const [memories] = memoriesSignal;
- const [insights] = insightsSignal;
- const [error] = loadError;
-
- onMount(() => fetchMemories());
-
- return (
- <div class="absolute inset-0 overflow-y-auto" style="scrollbar-width: none;">
- <div class="p-2">
- <div class="w-full h-full flex flex-col">
- <Switch>
- <Match when={insights()}>
- {(memories) => (
- <MemoryList
- memories={memories().insights}
- total={memories().total}
- editable={false}
- />
- )}
- </Match>
- <Match when={!memories && !error()}>
- <div class="w-full h-full flex items-center justify-center font-medium">
- <LoadingSpinner />
- </div>
- </Match>
- <Match when={error()}>
- <div class="h-full w-full font-medium flex items-center justify-center">
- Error loading memory
- </div>
- </Match>
- </Switch>
- </div>
- </div>
- </div>
- );
-}
diff --git a/js/app/packages/app/component/settings/AiMemory/component/CreateMemory.tsx b/js/app/packages/app/component/settings/AiMemory/component/CreateMemory.tsx
deleted file mode 100644
index 2379e8bd56..0000000000
--- a/js/app/packages/app/component/settings/AiMemory/component/CreateMemory.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';
-import clickOutside from '@core/directive/clickOutside';
-import CheckIcon from '@icon/bold/check-bold.svg';
-import XIcon from '@icon/regular/x.svg';
-import { createSignal, onCleanup, onMount } from 'solid-js';
-import { creatingMemory, useCreateUserMemory } from '../signal';
-
-//@ts-ignore
-clickOutside & false;
-
-export function CreateMemory() {
- const [, setCreating] = creatingMemory;
- const createMemory = useCreateUserMemory();
- let editRef: HTMLDivElement | undefined;
-
- function keyHandler(e: KeyboardEvent) {
- if (
- e.metaKey &&
- e.key === 'Enter' &&
- editRef?.textContent &&
- editRef.textContent.length > 0
- ) {
- createMemory(editRef.textContent);
- setCreating(false);
- }
- if (e.key === 'Escape') setCreating(false);
- }
-
- onMount(() => {
- if (editRef) editRef.focus();
- });
-
- const memoryExamples = [
- "I'm a student studying computer science",
- 'I live in NYC',
- "I'm learning Javascript and C",
- 'My birthday is in July',
- 'I prefer short and direct communication',
- 'Always provide code examples',
- ];
-
- const [value, setValue] = createSignal<null | string>('');
- const [activeExample, setActiveExample] = createSignal(0);
- const [visible, setVisible] = createSignal(true);
-
- const interval = setInterval(() => {
- setVisible(false); // fade out
- setTimeout(() => {
- setActiveExample((p) => (p + 1) % memoryExamples.length);
- setVisible(true); // fade in new text
- }, 300);
- }, 1900);
-
- onCleanup(() => clearInterval(interval));
-
- return (
- <div
- class="p-1 flex flex-row w-full items-center text-sm gap-x-1 justify-end relative border-1 border-accent rounded-md"
- use:clickOutside={() => setCreating(false)}
- >
- <div
- ref={editRef}
- contenteditable="plaintext-only"
- onKeyDown={keyHandler}
- onInput={(_) => {
- if (editRef) setValue(editRef?.textContent);
- }}
- class="flex-1"
- contentEditable="plaintext-only"
- />
- <div
- class={` ${visible() ? 'opacity-50' : 'opacity-0'}
- absolute left-2
- transition-opacity duration-300 ease-in-out select-none ${value() ? 'hidden' : ''}
- `}
- >
- {memoryExamples[activeExample()]}
- </div>
- <DeprecatedTextButton
- icon={XIcon}
- text="Cancel"
- theme="clear"
- onClick={() => setCreating(false)}
- />
- <DeprecatedTextButton
- icon={CheckIcon}
- text="Create"
- theme="accent"
- onClick={() => {
- if (
- editRef &&
- editRef?.textContent &&
- editRef.textContent.length > 0
- ) {
- createMemory(editRef.textContent);
- setCreating(false);
- }
- }}
- />
- </div>
- );
-}
diff --git a/js/app/packages/app/component/settings/AiMemory/component/MemoryList.tsx b/js/app/packages/app/component/settings/AiMemory/component/MemoryList.tsx
deleted file mode 100644
index a856c736ff..0000000000
--- a/js/app/packages/app/component/settings/AiMemory/component/MemoryList.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import type { UserInsightRecord } from '@service-insight/generated/schemas/userInsightRecord';
-import { For, Show } from 'solid-js';
-import { SmartInsight } from './SmartInsights';
-
-export type MemoryListProps = {
- memories: UserInsightRecord[];
- total: number;
- editable: boolean;
- class?: string;
-};
-
-export function MemoryList(props: MemoryListProps) {
- return (
- <div
- class={`w-full flex flex-col ${props.class ?? ''}`}
- >
- <div>
- <Show when={props.memories.length > 0}>
- <For each={props.memories} fallback={<div />}>
- {(memory) => {
- if (!memory.generated) {
- // return <UserMemory memory={memory} />;
- } else {
- return <SmartInsight insight={memory} />;
- }
- }}
- </For>
- </Show>
- </div>
- </div>
- );
-}
diff --git a/js/app/packages/app/component/settings/AiMemory/component/SmartInsights.tsx b/js/app/packages/app/component/settings/AiMemory/component/SmartInsights.tsx
deleted file mode 100644
index aa0a8393a3..0000000000
--- a/js/app/packages/app/component/settings/AiMemory/component/SmartInsights.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';
-import { EDITABLE_SMART_INSIGHTS } from '@core/constant/featureFlags';
-import { formatDate } from '@core/util/date';
-import Flag from '@icon/regular/flag-pennant.svg';
-import Pencil from '@icon/regular/pencil-simple.svg';
-import type { UserInsightRecord } from '@service-insight/generated/schemas/userInsightRecord';
-import { createMemo, Show } from 'solid-js';
-
-export type SmartInsightProps = {
- insight: UserInsightRecord;
-};
-
-export function SmartInsight(props: SmartInsightProps) {
- const prettyDate = createMemo(() => formatDate(props.insight.updatedAt));
-
- return (
- <div class="text-sm py-1">
- <div class="flex flex-row justify-between gap-x-2 items-center">
- <div class="flex items-center flex-1">{props.insight.content}</div>
- <div class="flex flex-row">
- <div class="text-xs items-center px-1 flex text-ink-extra-muted">
- <div class="px-1">{prettyDate()}</div>
- </div>
- <Show when={EDITABLE_SMART_INSIGHTS}>
- <DeprecatedTextButton
- onClick={() => {}}
- icon={Flag}
- text="Mark Wrong"
- theme="red"
- />
- <DeprecatedTextButton
- onClick={() => {}}
- icon={Pencil}
- text="Suggest Improvement"
- theme="accent"
- />
- </Show>
- </div>
- </div>
- </div>
- );
-}
diff --git a/js/app/packages/app/component/settings/AiMemory/component/UserMemory.tsx b/js/app/packages/app/component/settings/AiMemory/component/UserMemory.tsx
deleted file mode 100644
index fd95167997..0000000000
--- a/js/app/packages/app/component/settings/AiMemory/component/UserMemory.tsx
+++ /dev/null
@@ -1,175 +0,0 @@
-import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';
-import clickOutside from '@core/directive/clickOutside';
-import { formatDate } from '@core/util/date';
-import CheckIcon from '@icon/regular/check.svg';
-import XIcon from '@icon/regular/x.svg';
-import type { UserInsightRecord } from '@service-insight/generated/schemas/userInsightRecord';
-import { createCallback } from '@solid-primitives/rootless';
-import { createMemo, createSignal, Match, onMount, Switch } from 'solid-js';
-import { deleteMemory, updateUserMemory } from '../signal';
-
-//@ts-ignore
-clickOutside && false;
-
-export type UserMemoryProps = {
- memory: UserInsightRecord;
-};
-
-export function UserMemory(props: UserMemoryProps) {
- let ref: HTMLDivElement | undefined;
- const prettyDate = createMemo(() => formatDate(props.memory.updatedAt));
- const [isEditing, setIsEditing] = createSignal(false);
- const [isDeleting, setIsDeleting] = createSignal(false);
-
- const onSave = createCallback((text: string) => {
- updateUserMemory(props.memory.id as string, text);
- setIsEditing(false);
- });
-
- const onCancel = () => {
- setIsEditing(false);
- };
-
- return (
- <div
- class="text-sm py-1"
- ref={ref}
- use:clickOutside={() => {
- setIsDeleting(false);
- setIsEditing(false);
- }}
- >
- <Switch>
- <Match when={isEditing()}>
- <EditMemory
- onCancel={onCancel}
- onSave={onSave}
- text={props.memory.content}
- />
- </Match>
- <Match when={isDeleting()}>
- <div class="flex items-center justify-center align-center flex-col w-full h-full">
- Are you sure you want to delete this memory?
- <div class="flex flex-row gap-x-1">
- <DeprecatedTextButton
- onClick={() => setIsDeleting(false)}
- icon={XIcon}
- theme="clear"
- text="Cancel"
- />
-
- <DeprecatedTextButton
- onClick={createCallback(() =>
- deleteMemory(props.memory.id as string)
- )}
- icon={CheckIcon}
- theme="red"
- text="Delete"
- />
- </div>
- </div>
- </Match>
- <Match when={!isEditing()}>
- <div class="flex flex-row justify-between gap-x-2 items-center divide-x divide-1 divide-black/10">
- <div class="line-clamp-5 flex-1 flex flex-row justify-between">
- {props.memory.content}
- <div class="text-xs text-ink-extra-muted pr-2 p-1">
- Created {prettyDate()}
- </div>
- </div>
- <div class="flex flex-col items-center">
- <div class="flex flex-row gap-x-1 h-full items-center">
- <div
- class="text-failure text-xs hover:bg-hover hover-transition-bg py-1 px-2 rounded-sm"
- onClick={(e) => {
- e.preventDefault();
- setIsDeleting(true);
- }}
- >
- Delete
- </div>
- <div
- class="text-accent-ink text-xs hover:bg-hover hover-transition-bg py-1 px-2 rounded-sm"
- onClick={(e) => {
- e.preventDefault();
- setIsEditing(true);
- }}
- >
- Edit
- </div>
- </div>
- </div>
- </div>
- </Match>
- </Switch>
- </div>
- );
-}
-
-type EditMemoryProps = {
- onSave: (text: string) => void;
- onCancel: () => void;
- text: string;
- class?: string;
-};
-
-function EditMemory(props: EditMemoryProps) {
- let editableRef: HTMLDivElement | undefined;
-
- function keyHandler(e: KeyboardEvent) {
- if (
- e.metaKey &&
- e.key === 'Enter' &&
- editableRef?.textContent &&
- editableRef.textContent.length > 0
- )
- props.onSave(editableRef.textContent);
- if (e.key === 'Escape') props.onCancel();
- }
-
- function focusEditable() {
- if (editableRef) {
- editableRef.focus();
- const selection = document.getSelection();
- selection?.removeAllRanges();
- const range = document.createRange();
- range.setStart(
- editableRef.childNodes[0],
- editableRef.textContent?.length ?? 0
- );
- selection?.addRange(range);
- }
- }
-
- onMount(focusEditable);
-
- return (
- <div
- class={`w-full flex text-sm justify-between items-center ${props.class ?? ''} rounded-md border-accent border-1 p-1`}
- >
- <div
- ref={editableRef}
- contenteditable="plaintext-only"
- onKeyDown={keyHandler}
- >
- {props.text}
- </div>
- <div class="justify-end gap-x-1 flex flex-row items-center">
- <DeprecatedTextButton
- onClick={props.onCancel}
- icon={XIcon}
- text="Cancel"
- theme="clear"
- />
- <DeprecatedTextButton
- onClick={() => {
- if (editableRef?.textContent) props.onSave(editableRef.textContent);
- }}
- icon={CheckIcon}
- text="Save"
- theme="accent"
- />
- </div>
- </div>
- );
-}
diff --git a/js/app/packages/app/component/settings/AiMemory/signal.ts b/js/app/packages/app/component/settings/AiMemory/signal.ts
deleted file mode 100644
index ec07094c8b..0000000000
--- a/js/app/packages/app/component/settings/AiMemory/signal.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { isOk } from '@core/util/maybeResult';
-import { useUserId } from '@service-gql/client';
-import { insightClient } from '@service-insight/client';
-import type { GetUserInsightsResponse } from '@service-insight/generated/schemas/getUserInsightsResponse';
-import type { UserInsightRecord } from '@service-insight/generated/schemas/userInsightRecord';
-import { createCallback } from '@solid-primitives/rootless';
-import { createSignal } from 'solid-js';
-
-// get current unix time in seconds
-const nowSeconds = () => Date.now() / 1000;
-
-export async function updateUserMemory(id: string, text: string) {
- let updated = false;
- const [_, setMemories] = memories;
- const now = nowSeconds();
- setMemories((p) => {
- if (!p) return p;
- const insights: UserInsightRecord[] = p.insights.map((mem) => {
- if (mem.id === id && mem.generated === false) {
- updated = true;
- return {
- ...mem,
- content: text,
- updatedAt: now,
- };
- } else {
- return mem;
- }
- });
- return {
- insights,
- total: p.total,
- };
- });
- // TODO error
- if (updated)
- await insightClient.updateUserInsight({ content: text, insight_id: id });
-}
-
-export async function deleteMemory(id: string) {
- const [_, setMemories] = memories;
- setMemories((p) => {
- if (!p) return p;
- const insights = p.insights.filter((i) => i.id !== id);
- return {
- insights,
- total: p.total - 1,
- };
- });
-
- // TODO toast on error
- await insightClient.deleteUserInsights({ ids: [id] });
-}
-
-export function useCreateUserMemory() {
- const userId = useUserId();
- const [, setMemories] = memories;
-
- return createCallback(async (text: string) => {
- const memory = await insightClient.createUserInsight({
- insights: [text],
- });
- // TODO ERROR
- if (isOk(memory)) {
- const [, { ids }] = memory;
- const id = ids[0];
- if (!id) return;
- const now = nowSeconds();
-
- const newMemory: UserInsightRecord = {
- content: text,
- createdAt: now,
- updatedAt: now,
- generated: false,
- source: 'user_created',
- userId: userId() ?? '',
- };
- setMemories((p) => {
- return {
- insights: [newMemory, ...(p ? p.insights : [])],
- total: p?.total ? p.total + 1 : 1,
- };
- });
- }
- });
-}
-
-export const memories = createSignal<GetUserInsightsResponse>();
-export const insights = createSignal<GetUserInsightsResponse>();
-export const creatingMemory = createSignal<boolean>(false);
-export const loadError = createSignal<string>();
-export const insightLoadError = createSignal<string>();
-export const PAGE_SIZE = 5;
diff --git a/js/app/packages/core/component/AI/constant/memories.ts b/js/app/packages/core/component/AI/constant/memories.ts
deleted file mode 100644
index fec619b6e2..0000000000
--- a/js/app/packages/core/component/AI/constant/memories.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { isErr } from '@core/util/maybeResult';
-import { insightClient } from '@service-insight/client';
-import { QueryClient, useQuery } from '@tanstack/solid-query';
-
-const queryClient = new QueryClient();
-
-export function useFormatMemoriesQuery() {
- const query = useQuery(
- () => ({
- queryKey: ['formatMemoriesId'],
- queryFn: formatMemories,
- staleTime: Infinity,
- throwOnError: false,
- retry: false,
- retryOnMount: false,
- }),
- () => queryClient
- );
-
- return query;
-}
-
-async function formatMemories(): Promise<string> {
- const generatedInsightsRes = await insightClient.getUserInsight({
- generated: true,
- });
- if (isErr(generatedInsightsRes)) {
- throw new Error('getting memory');
- }
- let [, generatedInsights] = generatedInsightsRes;
-
- const smartInsights = generatedInsights.insights
- .map((mem) => mem.content)
- .join(`\n`);
-
- return `\nThese are user preferences generated from usage. Adapt your responses to fit the user:\n${smartInsights}`;
-}
diff --git a/js/app/packages/core/constant/servers.ts b/js/app/packages/core/constant/servers.ts
index 00a8c99eb4..8db33acc26 100644
--- a/js/app/packages/core/constant/servers.ts
+++ b/js/app/packages/core/constant/servers.ts
@@ -15,7 +15,6 @@ const serverHostLocal: Servers = {
'unfurl-service': 'http://localhost:8080',
contacts: 'http://localhost:8092',
'email-service': 'http://localhost:8094',
- 'insight-service': `http://localhost:8080`,
'search-service': 'http://localhost:8091',
'properties-service': `http://localhost:8095`,
} as const;
@@ -38,7 +37,6 @@ const serverHostRemote = {
'unfurl-service': `https://unfurl-service${devServerSuffix}.macro.com`,
contacts: `https://contacts${devServerSuffix}.macro.com`,
'email-service': `https://email-service${devServerSuffix}.macro.com`,
- 'insight-service': `https://insight-service${devServerSuffix}.macro.com`,
'search-service': `https://search-service${devServerSuffix}.macro.com`,
'properties-service': `https://properties-service${devServerSuffix}.macro.com`,
} as const;
diff --git a/js/app/packages/service-clients/orval.config.ts b/js/app/packages/service-clients/orval.config.ts
index 88863b11c7..3df95d3e13 100644
--- a/js/app/packages/service-clients/orval.config.ts
+++ b/js/app/packages/service-clients/orval.config.ts
@@ -61,16 +61,7 @@ export default defineConfig({
target: './service-email/openapi.json',
},
},
- insightsService: {
- output: {
- client: 'fetch',
- target: './service-insight/generated/client.ts',
- schemas: './service-insight/generated/schemas',
- },
- input: {
- target: './service-insight/openapi.json',
- },
- },
+
notificationService: {
output: {
client: 'fetch',
diff --git a/js/app/packages/service-clients/service-insight/client.ts b/js/app/packages/service-clients/service-insight/client.ts
deleted file mode 100644
index 3ac608e6b5..0000000000
--- a/js/app/packages/service-clients/service-insight/client.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import { SERVER_HOSTS } from '@core/constant/servers';
-import { cache } from '@core/util/cache';
-import {
- type FetchWithTokenErrorCode,
- fetchWithToken,
-} from '@core/util/fetchWithToken';
-import {
- type MaybeError,
- type MaybeResult,
- mapOk,
- type ObjectLike,
-} from '@core/util/maybeResult';
-import type { SafeFetchInit } from '@core/util/safeFetch';
-import type { CreateInsightsRequest } from './generated/schemas/createInsightsRequest';
-import type { GetUserInsightsResponse } from './generated/schemas/getUserInsightsResponse';
-import type { HandleGetUserInsightsParams } from './generated/schemas/handleGetUserInsightsParams';
-import type { IdList } from './generated/schemas/idList';
-import type { UpdateInsightRequest } from './generated/schemas/updateInsightRequest';
-import type { UserInsightRecord } from './generated/schemas/userInsightRecord';
-
-const insightHost = SERVER_HOSTS['insight-service'];
-
-const USER_INSIGHTS_CACHE_EXPIRY_MINS = 180; // 3 hours
-
-export function insightFetch(
- url: string,
- init?: SafeFetchInit
-): Promise<MaybeError<FetchWithTokenErrorCode>>;
-export function insightFetch<T extends ObjectLike>(
- url: string,
- init?: SafeFetchInit
-): Promise<MaybeResult<FetchWithTokenErrorCode, T>>;
-export function insightFetch<T extends ObjectLike = never>(
- url: string,
- init?: SafeFetchInit
-):
- | Promise<MaybeResult<FetchWithTokenErrorCode, T>>
- | Promise<MaybeError<FetchWithTokenErrorCode>> {
- return fetchWithToken<T>(`${insightHost}${url}`, init);
-}
-
-export const insightClient = {
- async createUserInsight(args: CreateInsightsRequest) {
- const result = await insightFetch<IdList>('/user_insight', {
- method: 'POST',
- body: JSON.stringify(args),
- });
-
- insightClient.getUserInsight.invalidate({ limit: 100, offset: 0 });
- return result;
- },
- getUserInsight: cache(
- async function getUserInsight(args: HandleGetUserInsightsParams) {
- let queryString = Object.entries(args)
- .map(([k, v]) => {
- return `${k}=${v}`;
- })
- .join('&');
-
- return mapOk(
- await insightFetch<GetUserInsightsResponse>(
- `/user_insight?${queryString}`
- ),
- (data) => {
- if (!data.insights || data.insights.length === 0) {
- insightClient.getUserInsight.invalidate(args);
- }
- return data;
- }
- );
- },
- { minutes: USER_INSIGHTS_CACHE_EXPIRY_MINS }
- ),
- async updateUserInsight(args: UpdateInsightRequest) {
- const result = await insightFetch<UserInsightRecord>(`/user_insight`, {
- method: 'PATCH',
- body: JSON.stringify(args),
- });
-
- insightClient.getUserInsight.invalidate({ limit: 100, offset: 0 });
- return result;
- },
- async deleteUserInsights(args: IdList) {
- const result = await insightFetch<IdList>(`/user_insight`, {
- method: 'DELETE',
- body: JSON.stringify(args),
- });
-
- return result;
- },
-};
diff --git a/js/app/packages/service-clients/service-insight/generated/client.ts b/js/app/packages/service-clients/service-insight/generated/client.ts
deleted file mode 100644
index 2c06549eed..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/client.ts
+++ /dev/null
@@ -1,259 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-import type {
- CreateInsightsRequest,
- GetUserInsightsResponse,
- HandleGetUserInsightsParams,
- IdList,
- InsightProcessingResponse,
- UpdateInsightRequest,
- UserInsightRecord
-} from './schemas';
-
-/**
- * get user insights
- */
-export type handleGetUserInsightsResponse200 = {
- data: GetUserInsightsResponse
- status: 200
-}
-
-export type handleGetUserInsightsResponse202 = {
- data: InsightProcessingResponse
- status: 202
-}
-
-export type handleGetUserInsightsResponse401 = {
- data: string
- status: 401
-}
-
-export type handleGetUserInsightsResponse500 = {
- data: string
- status: 500
-}
-
-export type handleGetUserInsightsResponseSuccess = (handleGetUserInsightsResponse200 | handleGetUserInsightsResponse202) & {
- headers: Headers;
-};
-export type handleGetUserInsightsResponseError = (handleGetUserInsightsResponse401 | handleGetUserInsightsResponse500) & {
- headers: Headers;
-};
-
-export type handleGetUserInsightsResponse = (handleGetUserInsightsResponseSuccess | handleGetUserInsightsResponseError)
-
-export const getHandleGetUserInsightsUrl = (params?: HandleGetUserInsightsParams,) => {
- const normalizedParams = new URLSearchParams();
-
- Object.entries(params || {}).forEach(([key, value]) => {
-
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : value.toString())
- }
- });
-
- const stringifiedParams = normalizedParams.toString();
-
- return stringifiedParams.length > 0 ? `/user_insight?${stringifiedParams}` : `/user_insight`
-}
-
-export const handleGetUserInsights = async (params?: HandleGetUserInsightsParams, options?: RequestInit): Promise<handleGetUserInsightsResponse> => {
-
- const res = await fetch(getHandleGetUserInsightsUrl(params),
- {
- ...options,
- method: 'GET'
-
-
- }
-)
-
- const body = [204, 205, 304].includes(res.status) ? null : await res.text();
-
- const data: handleGetUserInsightsResponse['data'] = body ? JSON.parse(body) : {}
- return { data, status: res.status, headers: res.headers } as handleGetUserInsightsResponse
-}
-
-
-
-/**
- * update_user_insight
- */
-export type handleCreateInsightsResponse200 = {
- data: IdList
- status: 200
-}
-
-export type handleCreateInsightsResponse401 = {
- data: string
- status: 401
-}
-
-export type handleCreateInsightsResponse404 = {
- data: string
- status: 404
-}
-
-export type handleCreateInsightsResponse500 = {
- data: string
- status: 500
-}
-
-export type handleCreateInsightsResponseSuccess = (handleCreateInsightsResponse200) & {
- headers: Headers;
-};
-export type handleCreateInsightsResponseError = (handleCreateInsightsResponse401 | handleCreateInsightsResponse404 | handleCreateInsightsResponse500) & {
- headers: Headers;
-};
-
-export type handleCreateInsightsResponse = (handleCreateInsightsResponseSuccess | handleCreateInsightsResponseError)
-
-export const getHandleCreateInsightsUrl = () => {
-
-
-
-
- return `/user_insight`
-}
-
-export const handleCreateInsights = async (createInsightsRequest: CreateInsightsRequest, options?: RequestInit): Promise<handleCreateInsightsResponse> => {
-
- const res = await fetch(getHandleCreateInsightsUrl(),
- {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(
- createInsightsRequest,)
- }
-)
-
- const body = [204, 205, 304].includes(res.status) ? null : await res.text();
-
- const data: handleCreateInsightsResponse['data'] = body ? JSON.parse(body) : {}
- return { data, status: res.status, headers: res.headers } as handleCreateInsightsResponse
-}
-
-
-
-/**
- * update_user_insight
- */
-export type handleDeleteUserInsightsResponse200 = {
- data: IdList
- status: 200
-}
-
-export type handleDeleteUserInsightsResponse401 = {
- data: string
- status: 401
-}
-
-export type handleDeleteUserInsightsResponse404 = {
- data: string
- status: 404
-}
-
-export type handleDeleteUserInsightsResponse500 = {
- data: string
- status: 500
-}
-
-export type handleDeleteUserInsightsResponseSuccess = (handleDeleteUserInsightsResponse200) & {
- headers: Headers;
-};
-export type handleDeleteUserInsightsResponseError = (handleDeleteUserInsightsResponse401 | handleDeleteUserInsightsResponse404 | handleDeleteUserInsightsResponse500) & {
- headers: Headers;
-};
-
-export type handleDeleteUserInsightsResponse = (handleDeleteUserInsightsResponseSuccess | handleDeleteUserInsightsResponseError)
-
-export const getHandleDeleteUserInsightsUrl = () => {
-
-
-
-
- return `/user_insight`
-}
-
-export const handleDeleteUserInsights = async (idList: IdList, options?: RequestInit): Promise<handleDeleteUserInsightsResponse> => {
-
- const res = await fetch(getHandleDeleteUserInsightsUrl(),
- {
- ...options,
- method: 'DELETE',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(
- idList,)
- }
-)
-
- const body = [204, 205, 304].includes(res.status) ? null : await res.text();
-
- const data: handleDeleteUserInsightsResponse['data'] = body ? JSON.parse(body) : {}
- return { data, status: res.status, headers: res.headers } as handleDeleteUserInsightsResponse
-}
-
-
-
-/**
- * update_user_insight
- */
-export type handleUpdateUserInsightResponse200 = {
- data: UserInsightRecord
- status: 200
-}
-
-export type handleUpdateUserInsightResponse401 = {
- data: string
- status: 401
-}
-
-export type handleUpdateUserInsightResponse404 = {
- data: string
- status: 404
-}
-
-export type handleUpdateUserInsightResponse500 = {
- data: string
- status: 500
-}
-
-export type handleUpdateUserInsightResponseSuccess = (handleUpdateUserInsightResponse200) & {
- headers: Headers;
-};
-export type handleUpdateUserInsightResponseError = (handleUpdateUserInsightResponse401 | handleUpdateUserInsightResponse404 | handleUpdateUserInsightResponse500) & {
- headers: Headers;
-};
-
-export type handleUpdateUserInsightResponse = (handleUpdateUserInsightResponseSuccess | handleUpdateUserInsightResponseError)
-
-export const getHandleUpdateUserInsightUrl = () => {
-
-
-
-
- return `/user_insight`
-}
-
-export const handleUpdateUserInsight = async (updateInsightRequest: UpdateInsightRequest, options?: RequestInit): Promise<handleUpdateUserInsightResponse> => {
-
- const res = await fetch(getHandleUpdateUserInsightUrl(),
- {
- ...options,
- method: 'PATCH',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(
- updateInsightRequest,)
- }
-)
-
- const body = [204, 205, 304].includes(res.status) ? null : await res.text();
-
- const data: handleUpdateUserInsightResponse['data'] = body ? JSON.parse(body) : {}
- return { data, status: res.status, headers: res.headers } as handleUpdateUserInsightResponse
-}
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/createInsightsRequest.ts b/js/app/packages/service-clients/service-insight/generated/schemas/createInsightsRequest.ts
deleted file mode 100644
index 177bcc8012..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/createInsightsRequest.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-
-export interface CreateInsightsRequest {
- insights: string[];
-}
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/emailSourceLocation.ts b/js/app/packages/service-clients/service-insight/generated/schemas/emailSourceLocation.ts
deleted file mode 100644
index 270460f123..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/emailSourceLocation.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-import type { EmailSourceLocationEmailAddresses } from './emailSourceLocationEmailAddresses';
-
-export interface EmailSourceLocation {
- emailAddresses?: EmailSourceLocationEmailAddresses;
- messageIds: string[];
- threadIds: string[];
-}
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/emailSourceLocationEmailAddresses.ts b/js/app/packages/service-clients/service-insight/generated/schemas/emailSourceLocationEmailAddresses.ts
deleted file mode 100644
index d7e3ebadc7..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/emailSourceLocationEmailAddresses.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-
-export type EmailSourceLocationEmailAddresses = string[] | null;
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/getUserInsightsParams.ts b/js/app/packages/service-clients/service-insight/generated/schemas/getUserInsightsParams.ts
deleted file mode 100644
index e1b808d7e6..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/getUserInsightsParams.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-import type { GetUserInsightsParamsGenerated } from './getUserInsightsParamsGenerated';
-import type { GetUserInsightsParamsLimit } from './getUserInsightsParamsLimit';
-import type { GetUserInsightsParamsOffset } from './getUserInsightsParamsOffset';
-
-export interface GetUserInsightsParams {
- generated?: GetUserInsightsParamsGenerated;
- /** @minimum 0 */
- limit?: GetUserInsightsParamsLimit;
- /** @minimum 0 */
- offset?: GetUserInsightsParamsOffset;
-}
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/getUserInsightsParamsGenerated.ts b/js/app/packages/service-clients/service-insight/generated/schemas/getUserInsightsParamsGenerated.ts
deleted file mode 100644
index 56142efc06..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/getUserInsightsParamsGenerated.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-
-export type GetUserInsightsParamsGenerated = boolean | null;
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/getUserInsightsParamsLimit.ts b/js/app/packages/service-clients/service-insight/generated/schemas/getUserInsightsParamsLimit.ts
deleted file mode 100644
index bd0a369b47..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/getUserInsightsParamsLimit.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * @minimum 0
- */
-export type GetUserInsightsParamsLimit = number | null;
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/getUserInsightsParamsOffset.ts b/js/app/packages/service-clients/service-insight/generated/schemas/getUserInsightsParamsOffset.ts
deleted file mode 100644
index 937d975d43..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/getUserInsightsParamsOffset.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * @minimum 0
- */
-export type GetUserInsightsParamsOffset = number | null;
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/getUserInsightsResponse.ts b/js/app/packages/service-clients/service-insight/generated/schemas/getUserInsightsResponse.ts
deleted file mode 100644
index 21d19079cb..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/getUserInsightsResponse.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-import type { UserInsightRecord } from './userInsightRecord';
-
-export interface GetUserInsightsResponse {
- insights: UserInsightRecord[];
- total: number;
-}
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/handleGetUserInsightsParams.ts b/js/app/packages/service-clients/service-insight/generated/schemas/handleGetUserInsightsParams.ts
deleted file mode 100644
index 2feda0115f..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/handleGetUserInsightsParams.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-
-export type HandleGetUserInsightsParams = {
-/**
- * @minimum 0
- */
-limit?: number | null;
-/**
- * @minimum 0
- */
-offset?: number | null;
-generated?: boolean | null;
-};
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/idList.ts b/js/app/packages/service-clients/service-insight/generated/schemas/idList.ts
deleted file mode 100644
index ff39f9a4e2..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/idList.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-
-export interface IdList {
- ids: string[];
-}
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/index.ts b/js/app/packages/service-clients/service-insight/generated/schemas/index.ts
deleted file mode 100644
index b49ba642f1..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/index.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-
-export * from './createInsightsRequest';
-export * from './emailSourceLocation';
-export * from './emailSourceLocationEmailAddresses';
-export * from './getUserInsightsParams';
-export * from './getUserInsightsParamsGenerated';
-export * from './getUserInsightsParamsLimit';
-export * from './getUserInsightsParamsOffset';
-export * from './getUserInsightsResponse';
-export * from './handleGetUserInsightsParams';
-export * from './idList';
-export * from './insightProcessingResponse';
-export * from './insightProcessingResponseEstimatedWaitMinutes';
-export * from './insightType';
-export * from './sourceLocation';
-export * from './updateInsightRequest';
-export * from './userInsightRecord';
-export * from './userInsightRecordConfidence';
-export * from './userInsightRecordId';
-export * from './userInsightRecordInsightType';
-export * from './userInsightRecordRelevanceKeywords';
-export * from './userInsightRecordSourceLocation';
-export * from './userInsightRecordSpanEnd';
-export * from './userInsightRecordSpanStart';
\ No newline at end of file
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/insightProcessingResponse.ts b/js/app/packages/service-clients/service-insight/generated/schemas/insightProcessingResponse.ts
deleted file mode 100644
index 52c9b80ebe..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/insightProcessingResponse.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-import type { InsightProcessingResponseEstimatedWaitMinutes } from './insightProcessingResponseEstimatedWaitMinutes';
-
-export interface InsightProcessingResponse {
- /** @minimum 0 */
- estimated_wait_minutes?: InsightProcessingResponseEstimatedWaitMinutes;
- message: string;
- status: string;
-}
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/insightProcessingResponseEstimatedWaitMinutes.ts b/js/app/packages/service-clients/service-insight/generated/schemas/insightProcessingResponseEstimatedWaitMinutes.ts
deleted file mode 100644
index 86e0736114..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/insightProcessingResponseEstimatedWaitMinutes.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * @minimum 0
- */
-export type InsightProcessingResponseEstimatedWaitMinutes = number | null;
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/insightType.ts b/js/app/packages/service-clients/service-insight/generated/schemas/insightType.ts
deleted file mode 100644
index 16876b7a13..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/insightType.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-
-export type InsightType = typeof InsightType[keyof typeof InsightType];
-
-
-// eslint-disable-next-line @typescript-eslint/no-redeclare
-export const InsightType = {
- actionable: 'actionable',
- informational: 'informational',
- warning: 'warning',
- trend: 'trend',
-} as const;
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/sourceLocation.ts b/js/app/packages/service-clients/service-insight/generated/schemas/sourceLocation.ts
deleted file mode 100644
index c4b51db15f..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/sourceLocation.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-import type { EmailSourceLocation } from './emailSourceLocation';
-
-export type SourceLocation = EmailSourceLocation;
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/updateInsightRequest.ts b/js/app/packages/service-clients/service-insight/generated/schemas/updateInsightRequest.ts
deleted file mode 100644
index 3ec2a1ef28..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/updateInsightRequest.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-
-export interface UpdateInsightRequest {
- content: string;
- insight_id: string;
-}
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecord.ts b/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecord.ts
deleted file mode 100644
index daf114f574..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecord.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-import type { UserInsightRecordConfidence } from './userInsightRecordConfidence';
-import type { UserInsightRecordId } from './userInsightRecordId';
-import type { UserInsightRecordInsightType } from './userInsightRecordInsightType';
-import type { UserInsightRecordRelevanceKeywords } from './userInsightRecordRelevanceKeywords';
-import type { UserInsightRecordSourceLocation } from './userInsightRecordSourceLocation';
-import type { UserInsightRecordSpanEnd } from './userInsightRecordSpanEnd';
-import type { UserInsightRecordSpanStart } from './userInsightRecordSpanStart';
-
-export interface UserInsightRecord {
- confidence?: UserInsightRecordConfidence;
- content: string;
- createdAt: number;
- generated: boolean;
- id?: UserInsightRecordId;
- insightType?: UserInsightRecordInsightType;
- relevanceKeywords?: UserInsightRecordRelevanceKeywords;
- source: string;
- sourceLocation?: UserInsightRecordSourceLocation;
- spanEnd?: UserInsightRecordSpanEnd;
- spanStart?: UserInsightRecordSpanStart;
- updatedAt: number;
- userId: string;
-}
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordConfidence.ts b/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordConfidence.ts
deleted file mode 100644
index d84867b865..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordConfidence.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-
-export type UserInsightRecordConfidence = number | null;
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordId.ts b/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordId.ts
deleted file mode 100644
index 4bdc540f03..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordId.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-
-export type UserInsightRecordId = string | null;
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordInsightType.ts b/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordInsightType.ts
deleted file mode 100644
index 682583a37b..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordInsightType.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-import type { InsightType } from './insightType';
-
-export type UserInsightRecordInsightType = null | InsightType;
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordRelevanceKeywords.ts b/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordRelevanceKeywords.ts
deleted file mode 100644
index d50905def7..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordRelevanceKeywords.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-
-export type UserInsightRecordRelevanceKeywords = string[] | null;
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordSourceLocation.ts b/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordSourceLocation.ts
deleted file mode 100644
index e9f348526e..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordSourceLocation.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-import type { SourceLocation } from './sourceLocation';
-
-export type UserInsightRecordSourceLocation = null | SourceLocation;
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordSpanEnd.ts b/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordSpanEnd.ts
deleted file mode 100644
index bbf6016d53..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordSpanEnd.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-
-export type UserInsightRecordSpanEnd = string | null;
diff --git a/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordSpanStart.ts b/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordSpanStart.ts
deleted file mode 100644
index 5a5e7ca9c4..0000000000
--- a/js/app/packages/service-clients/service-insight/generated/schemas/userInsightRecordSpanStart.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * insight_service
- * OpenAPI spec version: 0.1.0
- */
-
-export type UserInsightRecordSpanStart = string | null;
diff --git a/js/app/packages/service-clients/service-insight/openapi.json b/js/app/packages/service-clients/service-insight/openapi.json
deleted file mode 100644
index 3880baa030..0000000000
--- a/js/app/packages/service-clients/service-insight/openapi.json
+++ /dev/null
@@ -1,309 +0,0 @@
-{
- "openapi": "3.1.0",
- "info": {
- "title": "insight_service",
- "description": "",
- "termsOfService": "https://macro.com/terms",
- "license": { "name": "" },
- "version": "0.1.0"
- },
- "paths": {
- "/user_insight": {
- "get": {
- "tags": ["user_insight"],
- "description": "get user insights",
- "operationId": "handle_get_user_insights",
- "parameters": [
- {
- "name": "limit",
- "in": "query",
- "required": false,
- "schema": {
- "type": ["integer", "null"],
- "format": "int32",
- "minimum": 0
- }
- },
- {
- "name": "offset",
- "in": "query",
- "required": false,
- "schema": {
- "type": ["integer", "null"],
- "format": "int32",
- "minimum": 0
- }
- },
- {
- "name": "generated",
- "in": "query",
- "required": false,
- "schema": { "type": ["boolean", "null"] }
- }
- ],
- "responses": {
- "200": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/GetUserInsightsResponse"
- }
- }
- }
- },
- "202": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/InsightProcessingResponse"
- }
- }
- }
- },
- "401": {
- "description": "",
- "content": { "text/plain": { "schema": { "type": "string" } } }
- },
- "500": {
- "description": "",
- "content": { "text/plain": { "schema": { "type": "string" } } }
- }
- }
- },
- "post": {
- "tags": ["user_insight"],
- "description": "update_user_insight",
- "operationId": "handle_create_insights",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": { "$ref": "#/components/schemas/CreateInsightsRequest" }
- }
- },
- "required": true
- },
- "responses": {
- "200": {
- "description": "",
- "content": {
- "application/json": {
- "schema": { "$ref": "#/components/schemas/IdList" }
- }
- }
- },
- "401": {
- "description": "",
- "content": { "text/plain": { "schema": { "type": "string" } } }
- },
- "404": {
- "description": "",
- "content": { "text/plain": { "schema": { "type": "string" } } }
- },
- "500": {
- "description": "",
- "content": { "text/plain": { "schema": { "type": "string" } } }
- }
- }
- },
- "delete": {
- "tags": ["user_insight"],
- "description": "update_user_insight",
- "operationId": "handle_delete_user_insights",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": { "$ref": "#/components/schemas/IdList" }
- }
- },
- "required": true
- },
- "responses": {
- "200": {
- "description": "",
- "content": {
- "application/json": {
- "schema": { "$ref": "#/components/schemas/IdList" }
- }
- }
- },
- "401": {
- "description": "",
- "content": { "text/plain": { "schema": { "type": "string" } } }
- },
- "404": {
- "description": "",
- "content": { "text/plain": { "schema": { "type": "string" } } }
- },
- "500": {
- "description": "",
- "content": { "text/plain": { "schema": { "type": "string" } } }
- }
- }
- },
- "patch": {
- "tags": ["user_insight"],
- "description": "update_user_insight",
- "operationId": "handle_update_user_insight",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": { "$ref": "#/components/schemas/UpdateInsightRequest" }
- }
- },
- "required": true
- },
- "responses": {
- "200": {
- "description": "",
- "content": {
- "application/json": {
- "schema": { "$ref": "#/components/schemas/UserInsightRecord" }
- }
- }
- },
- "401": {
- "description": "",
- "content": { "text/plain": { "schema": { "type": "string" } } }
- },
- "404": {
- "description": "",
- "content": { "text/plain": { "schema": { "type": "string" } } }
- },
- "500": {
- "description": "",
- "content": { "text/plain": { "schema": { "type": "string" } } }
- }
- }
- }
- }
- },
- "components": {
- "schemas": {
- "CreateInsightsRequest": {
- "type": "object",
- "required": ["insights"],
- "properties": {
- "insights": { "type": "array", "items": { "type": "string" } }
- }
- },
- "EmailSourceLocation": {
- "type": "object",
- "required": ["threadIds", "messageIds"],
- "properties": {
- "emailAddresses": {
- "type": ["array", "null"],
- "items": { "type": "string" }
- },
- "messageIds": { "type": "array", "items": { "type": "string" } },
- "threadIds": { "type": "array", "items": { "type": "string" } }
- }
- },
- "GetUserInsightsParams": {
- "type": "object",
- "properties": {
- "generated": { "type": ["boolean", "null"] },
- "limit": {
- "type": ["integer", "null"],
- "format": "int32",
- "minimum": 0
- },
- "offset": {
- "type": ["integer", "null"],
- "format": "int32",
- "minimum": 0
- }
- }
- },
- "GetUserInsightsResponse": {
- "type": "object",
- "required": ["insights", "total"],
- "properties": {
- "insights": {
- "type": "array",
- "items": { "$ref": "#/components/schemas/UserInsightRecord" }
- },
- "total": { "type": "integer", "format": "int64" }
- }
- },
- "IdList": {
- "type": "object",
- "required": ["ids"],
- "properties": {
- "ids": { "type": "array", "items": { "type": "string" } }
- }
- },
- "InsightProcessingResponse": {
- "type": "object",
- "required": ["status", "message"],
- "properties": {
- "estimated_wait_minutes": {
- "type": ["integer", "null"],
- "format": "int32",
- "minimum": 0
- },
- "message": { "type": "string" },
- "status": { "type": "string" }
- }
- },
- "InsightType": {
- "type": "string",
- "enum": ["actionable", "informational", "warning", "trend"]
- },
- "SourceLocation": {
- "oneOf": [{ "$ref": "#/components/schemas/EmailSourceLocation" }]
- },
- "UpdateInsightRequest": {
- "type": "object",
- "required": ["insight_id", "content"],
- "properties": {
- "content": { "type": "string" },
- "insight_id": { "type": "string" }
- }
- },
- "UserInsightRecord": {
- "type": "object",
- "required": [
- "userId",
- "content",
- "generated",
- "createdAt",
- "updatedAt",
- "source"
- ],
- "properties": {
- "confidence": { "type": ["integer", "null"], "format": "int32" },
- "content": { "type": "string" },
- "createdAt": { "type": "integer", "format": "int64" },
- "generated": { "type": "boolean" },
- "id": { "type": ["string", "null"] },
- "insightType": {
- "oneOf": [
- { "type": "null" },
- { "$ref": "#/components/schemas/InsightType" }
- ]
- },
- "relevanceKeywords": {
- "type": ["array", "null"],
- "items": { "type": "string" }
- },
- "source": { "type": "string" },
- "sourceLocation": {
- "oneOf": [
- { "type": "null" },
- { "$ref": "#/components/schemas/SourceLocation" }
- ]
- },
- "spanEnd": { "type": ["string", "null"], "format": "date-time" },
- "spanStart": { "type": ["string", "null"], "format": "date-time" },
- "updatedAt": { "type": "integer", "format": "int64" },
- "userId": { "type": "string" }
- }
- }
- }
- },
- "tags": [
- { "name": "macro insight service", "description": "Insight Service" }
- ]
-}
diff --git a/js/app/scripts/services.ts b/js/app/scripts/services.ts
index fcf4d780ec..4353bd7c5b 100644
--- a/js/app/scripts/services.ts
+++ b/js/app/scripts/services.ts
@@ -88,14 +88,6 @@ export const services: Service[] = [
output: "../packages/service-clients/service-email/",
orvalKey: "emailService",
},
- {
- name: "insight-service",
- dev: "https://insight-service-dev.macro.com/api-doc/openapi.json",
- prod: "https://insight-service.macro.com/api-doc/openapi.json",
- local: "http://localhost:8080/api-doc/openapi.json",
- output: "../packages/service-clients/service-insight/",
- orvalKey: "insightsService",
- },
{
name: "search-service",
dev: "https://search-service-dev.macro.com/api-doc/openapi.json",
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 98a78932f9..3f082c6d36 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -93,7 +93,6 @@ dependencies = [
"cool_asserts",
"email",
"email_service_client",
- "insight_service_client",
"lazy_static",
"macro_db_client",
"model",
@@ -2674,7 +2673,6 @@ dependencies = [
"email_service_client",
"futures",
"http-body-util",
- "insight_service_client",
"lazy_static",
"lexical_client",
"log",
@@ -3177,7 +3175,6 @@ dependencies = [
"html-escape",
"http-body-util",
"infer 0.19.0",
- "insight_service_client",
"lol_html",
"macro_auth",
"macro_cors",
@@ -4541,74 +4538,6 @@ dependencies = [
"generic-array",
]
-[[package]]
-name = "insight_service"
-version = "0.1.0"
-dependencies = [
- "ai",
- "ai_format",
- "anyhow",
- "async-stream",
- "async-trait",
- "aws-config",
- "aws-sdk-secretsmanager",
- "aws-sdk-sqs",
- "axum",
- "chrono",
- "clap",
- "document_cognition_service_client",
- "document_storage_service_client",
- "email_service_client",
- "futures",
- "lexical_client",
- "macro_auth",
- "macro_cors",
- "macro_db_client",
- "macro_entrypoint",
- "macro_env",
- "macro_middleware",
- "model",
- "models_dcs",
- "models_email",
- "reqwest",
- "schemars",
- "scribe",
- "secretsmanager_client",
- "serde",
- "serde_json",
- "sha2",
- "sqlx",
- "sqs_worker",
- "strum",
- "strum_macros",
- "sync_service_client",
- "tokio",
- "tower-http",
- "tracing",
- "utoipa",
- "utoipa-swagger-ui",
- "uuid",
-]
-
-[[package]]
-name = "insight_service_client"
-version = "0.1.0"
-dependencies = [
- "ai_format",
- "anyhow",
- "async-trait",
- "aws-sdk-sqs",
- "chrono",
- "model",
- "serde",
- "sqlx",
- "sqs_client",
- "strum",
- "strum_macros",
- "tokio",
- "tracing",
-]
-
[[package]]
name = "instant"
version = "0.1.13"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index b6d7274229..b67a72baac 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -38,8 +38,6 @@ members = [
"experiment_service",
"frecency",
"gmail_client",
- "insight_service",
- "insight_service_client",
"integration_tests/*",
"lambda_client",
"lexical_client",
diff --git a/rust/cloud-storage/ai/src/types/model/metadata.rs b/rust/cloud-storage/ai/src/types/model/metadata.rs
index 69448fa505..93ebe1d855 100644
--- a/rust/cloud-storage/ai/src/types/model/metadata.rs
+++ b/rust/cloud-storage/ai/src/types/model/metadata.rs
@@ -85,9 +85,6 @@ impl ModelWithMetadataAndProvider for Model {
Model::OpenAIGPT4oSearchPreview => ModelMetadata {
context_window: 128_000,
},
- Model::OpenAIGgpt4oMiniSearchPreview => ModelMetadata {
- context_window: 128_000,
- },
}
}
@@ -100,7 +97,6 @@ impl ModelWithMetadataAndProvider for Model {
Model::OpenAIo1 => Provider::OpenAI,
Model::OpenAIGPT4oMini => Provider::OpenAI,
Model::OpenAIGPT4oSearchPreview => Provider::OpenAI,
- Model::OpenAIGgpt4oMiniSearchPreview => Provider::OpenAI,
Model::OpenAIo3 => Provider::OpenAI,
// Google models /
Model::Gemini25Pro => Provider::Google,
diff --git a/rust/cloud-storage/ai/src/types/model/mod.rs b/rust/cloud-storage/ai/src/types/model/mod.rs
index 5e9b32d060..da8613b680 100644
--- a/rust/cloud-storage/ai/src/types/model/mod.rs
+++ b/rust/cloud-storage/ai/src/types/model/mod.rs
@@ -62,11 +62,6 @@ pub enum Model {
#[serde(rename = "gpt-4o-search-preview")]
OpenAIGPT4oSearchPreview,
- #[strum(serialize = "gpt-4o-mini-search-preview")]
- #[serde(rename = "gpt-4o-mini-search-preview")]
- // NB typo OpenAI**G**gpt
- OpenAIGgpt4oMiniSearchPreview,
-
#[strum(serialize = "o3")]
#[serde(rename = "o3")]
OpenAIo3,
@@ -111,7 +106,6 @@ pub mod constants {
pub const OPEN_AI_GPT_4O_MINI: &str = "gpt-4o-mini";
pub const OPEN_AI_O1: &str = "o1";
pub const OPEN_AI_GPT_4O_SEARCH_PREVIEW: &str = "gpt-4o-search-preview";
- pub const OPEN_AI_GPT_4O_MINI_SEARCH_PREVIEW: &str = "gpt-4o-mini-search-preview";
pub const OPEN_AI_O3: &str = "o3";
pub const CLAUDE_35_SONNET: &str = "claude-3.5-sonnet";
pub const CLAUDE_37_SONNET: &str = "claude-3.7-sonnet";
@@ -144,7 +138,6 @@ impl Model {
Model::OpenAIGPT4oMini => (OPEN_AI, OPEN_AI_GPT_4O_MINI),
Model::OpenAIo1 => (OPEN_AI, OPEN_AI_O1),
Model::OpenAIGPT4oSearchPreview => (OPEN_AI, OPEN_AI_GPT_4O_SEARCH_PREVIEW),
- Model::OpenAIGgpt4oMiniSearchPreview => (OPEN_AI, OPEN_AI_GPT_4O_MINI_SEARCH_PREVIEW),
Model::OpenAIo3 => (OPEN_AI, OPEN_AI_O3),
Model::Claude35Sonnet => (ANTHROPIC, CLAUDE_35_SONNET),
Model::Claude37Sonnet => (ANTHROPIC, CLAUDE_37_SONNET),
@@ -166,7 +159,6 @@ impl Model {
OPEN_AI_GPT_4O_MINI => Model::OpenAIGPT4oMini,
OPEN_AI_O1 => Model::OpenAIo1,
OPEN_AI_GPT_4O_SEARCH_PREVIEW => Model::OpenAIGPT4oSearchPreview,
- OPEN_AI_GPT_4O_MINI_SEARCH_PREVIEW => Model::OpenAIGgpt4oMiniSearchPreview,
OPEN_AI_O3 => Model::OpenAIo3,
CLAUDE_35_SONNET => Model::Claude35Sonnet,
CLAUDE_37_SONNET => Model::Claude37Sonnet,
diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.toml
index bf3cd931c2..978ce8f782 100644
--- a/rust/cloud-storage/ai_tools/Cargo.toml
+++ b/rust/cloud-storage/ai_tools/Cargo.toml
@@ -11,7 +11,6 @@ async-trait.workspace = true
chrono.workspace = true
email = { path = "../email", features = ["ai_schema", "axum"] }
email_service_client = { path = "../email_service_client" }
-insight_service_client = { path = "../insight_service_client" }
lazy_static.workspace = true
macro_db_client = { path = "../macro_db_client" }
model = { path = "../model" }
diff --git a/rust/cloud-storage/ai_tools/src/read.rs b/rust/cloud-storage/ai_tools/src/read.rs
index 9f33e65c59..8112d15464 100644
--- a/rust/cloud-storage/ai_tools/src/read.rs
+++ b/rust/cloud-storage/ai_tools/src/read.rs
@@ -400,7 +400,7 @@ impl Read {
.get_chat_history_for_messages(message_ids, Some(&request_context.jwt_token))
.await
.map_err(|e| ToolCallError {
- description: format!("failed to fetch chat message: {}", e),
+ description: format!("failed to fetch chat messages: {}", e),
internal_error: e,
})?;
diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.toml
index 478acfe709..f5f7b375a4 100644
--- a/rust/cloud-storage/document_cognition_service/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml
@@ -40,7 +40,6 @@ doppleganger = { workspace = true }
email_service_client = { path = "../email_service_client" }
futures = { workspace = true }
http-body-util = { workspace = true }
-insight_service_client = { path = "../insight_service_client" }
lazy_static = { workspace = true }
lexical_client = { path = "../lexical_client" }
log = { workspace = true }
diff --git a/rust/cloud-storage/document_cognition_service/schemas/tools.json b/rust/cloud-storage/document_cognition_service/schemas/tools.json
index a9cfc9d996..a65a0d49f3 100644
--- a/rust/cloud-storage/document_cognition_service/schemas/tools.json
+++ b/rust/cloud-storage/document_cognition_service/schemas/tools.json
@@ -1,465 +1,268 @@
{
"schemas": [
{
- "name": "ListEmails",
+ "name": "ListDocuments",
"inputSchema": {
"additionalProperties": false,
- "description": "List the emails the user has access to. Use this tool to discover and browse emails before using the Read tool to access their content. Prefer using the search tool to search on a specific matching string within the content or the name of the entity.",
+ "description": "List documents the user has access to with optional filtering and pagination. Only applies to documents, not emails, AI conversations, chat/slack threads, projects aka folders. This tool returns document metadata including access levels and supports filtering by file type, minimum access level, and pagination. Use this tool to discover and browse documents before using the Read tool to access their content. Prefer using the search tool to search on a specific matching string within the content or the name of the entity.",
"properties": {
- "cursor": {
+ "exhaustiveSearch": {
"additionalProperties": false,
- "default": null,
- "description": "A preview response will tell you what the next cursor id is.\n If expected emails are not in the current response and it gives you a cursor id, use this field to list the next page of emails. If no cursor id is provided you've reached the end",
+ "default": false,
+ "description": "Exhaustive search to get all results. Defaults to false. Set to true when you need all matching documents, ignoring pagination limits.",
+ "type": "boolean"
+ },
+ "fileTypes": {
+ "additionalProperties": false,
+ "description": "Document file types to include. Examples: ['pdf'], ['md', 'txt']. Leave empty to include all document types.",
+ "items": {
+ "additionalProperties": false,
+ "type": "string"
+ },
+ "type": [
+ "array",
+ "null"
+ ]
+ },
+ "minAccessLevel": {
+ "additionalProperties": false,
+ "description": "Minimum access level required. Defaults to 'view' if not specified.",
+ "enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner",
+ null
+ ],
"type": [
"string",
"null"
]
},
- "limit": {
+ "pageOffset": {
"additionalProperties": false,
- "default": 20,
- "description": "limit the max emails returned. This defaults to 20 and has a maximum of 500",
+ "default": 0,
+ "description": "Page offset for pagination. Default is 0. Use higher values to get subsequent pages of results.",
"format": "int64",
"type": "integer"
},
- "sortMethod": {
- "additionalProperties": false,
- "default": "viewed_at",
- "description": "Sort response by one of: viewed_at | updated_at | created_at | viewed_updated. Prefer viewed_at unless the otherwise specified",
- "enum": [
- "viewed_at",
- "updated_at",
- "created_at",
- "viewed_updated"
- ],
- "type": "string"
- },
- "view": {
+ "pageSize": {
"additionalProperties": false,
- "default": {
- "standardLabel": null,
- "userLabel": null
- },
- "description": "Choose the view to list emails from. One of either standard label or user label must be specified, otherwise defaults to important.",
- "properties": {
- "standardLabel": {
- "additionalProperties": false,
- "description": "Prefer important or all. Leave empty if using a user label",
- "enum": [
- "Inbox",
- "Sent",
- "Drafts",
- "Starred",
- "All",
- "Important",
- "Other",
- null
- ],
- "type": [
- "string",
- "null"
- ]
- },
- "userLabel": {
- "additionalProperties": false,
- "description": "Choose a custom user label to filter by (optional). Standard label will take precedence over user label if both are specified.",
- "type": [
- "string",
- "null"
- ]
- }
- },
- "required": [
- "standardLabel",
- "userLabel"
- ],
- "type": "object"
+ "default": 50,
+ "description": "Number of results per page. Max is 100, default is 50. Use smaller values for focused results.",
+ "format": "int64",
+ "type": "integer"
}
},
"required": [
- "cursor",
- "limit",
- "sortMethod",
- "view"
+ "exhaustiveSearch",
+ "fileTypes",
+ "minAccessLevel",
+ "pageOffset",
+ "pageSize"
],
- "title": "ListEmails",
+ "title": "ListDocuments",
"type": "object"
},
"outputSchema": {
"properties": {
- "items": {
+ "results": {
+ "description": "The list results (truncated to `results_returned` limit if applicable)",
"items": {
"properties": {
- "attachments": {
- "items": {
- "properties": {
- "contentId": {
- "type": [
- "string",
- "null"
- ]
- },
- "createdAt": {
- "format": "int64",
- "type": "integer"
- },
- "filename": {
- "type": [
- "string",
- "null"
- ]
- },
- "id": {
- "format": "uuid",
- "type": "string"
- },
- "messageId": {
- "format": "uuid",
- "type": "string"
- },
- "mimeType": {
- "type": [
- "string",
- "null"
- ]
- },
- "providerAttachmentId": {
- "type": [
- "string",
- "null"
- ]
- },
- "sizeBytes": {
- "format": "int64",
- "type": [
- "integer",
- "null"
- ]
- }
- },
- "required": [
- "id",
- "messageId",
- "createdAt"
- ],
- "type": "object"
- },
- "type": "array"
- },
- "contacts": {
- "items": {
- "properties": {
- "emailAddress": {
- "type": [
- "string",
- "null"
- ]
- },
- "id": {
- "format": "uuid",
- "type": "string"
- },
- "linkId": {
- "format": "uuid",
- "type": "string"
- },
- "name": {
- "type": [
- "string",
- "null"
- ]
- },
- "sfsPhotoUrl": {
- "type": [
- "string",
- "null"
- ]
- }
- },
- "required": [
- "id",
- "linkId"
- ],
- "type": "object"
- },
- "type": "array"
+ "access_level": {
+ "description": "The user's access level to this document",
+ "enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ],
+ "type": "string"
},
- "createdAt": {
- "format": "int64",
- "type": "integer"
+ "created_at": {
+ "description": "When the document was created",
+ "format": "date-time",
+ "type": "string"
},
- "frecencyScore": {
- "format": "double",
+ "deleted_at": {
+ "description": "When the document was deleted (null if not deleted)",
+ "format": "date-time",
"type": [
- "number",
+ "string",
"null"
]
},
- "id": {
- "format": "uuid",
+ "document_id": {
+ "description": "The document id",
"type": "string"
},
- "inboxVisible": {
- "type": "boolean"
+ "document_name": {
+ "description": "The document name",
+ "type": "string"
},
- "isDraft": {
- "type": "boolean"
+ "file_type": {
+ "description": "The file type of the document",
+ "type": [
+ "string",
+ "null"
+ ]
},
- "isImportant": {
- "type": "boolean"
+ "owner": {
+ "description": "The owner of the document",
+ "type": "string"
},
- "isRead": {
- "type": "boolean"
+ "project_id": {
+ "description": "The project id containing the document",
+ "type": [
+ "string",
+ "null"
+ ]
},
- "labels": {
- "items": {
- "properties": {
- "createdAt": {
- "format": "date-time",
- "type": "string"
- },
- "id": {
- "format": "uuid",
- "type": "string"
- },
- "labelListVisibility": {
- "enum": [
- "LabelShow",
- "LabelShowIfUnread",
- "LabelHide"
- ],
- "type": "string"
- },
- "linkId": {
- "format": "uuid",
- "type": "string"
- },
- "messageListVisibility": {
- "enum": [
- "Show",
- "Hide"
- ],
- "type": "string"
- },
- "name": {
- "type": "string"
- },
- "providerLabelId": {
- "type": "string"
- },
- "type": {
- "enum": [
- "System",
- "User"
- ],
- "type": "string"
- }
- },
- "required": [
- "id",
- "linkId",
- "providerLabelId",
- "name",
- "createdAt",
- "messageListVisibility",
- "labelListVisibility",
- "type"
- ],
- "type": "object"
- },
- "type": "array"
- },
- "macroAttachments": {
- "items": {
- "properties": {
- "dbId": {
- "format": "uuid",
- "type": "string"
- },
- "itemId": {
- "format": "uuid",
- "type": "string"
- },
- "itemType": {
- "type": "string"
- },
- "messageId": {
- "format": "uuid",
- "type": "string"
- }
- },
- "required": [
- "dbId",
- "messageId",
- "itemId",
- "itemType"
- ],
- "type": "object"
- },
- "type": "array"
- },
- "metadata": {
- "properties": {
- "calendar_invite": {
- "description": "if any email contains a calendar invite",
- "type": "boolean"
- },
- "generic_sender": {
- "description": "if any sender in the thread is a generic email",
- "type": "boolean"
- },
- "known_sender": {
- "description": "if user has previously emailed any sender in the thread",
- "type": "boolean"
- },
- "tabular": {
- "description": "if any email contains a <table> html tag",
- "type": "boolean"
- }
- },
- "required": [
- "known_sender",
- "tabular",
- "calendar_invite",
- "generic_sender"
- ],
- "type": "object"
- },
- "name": {
- "type": [
- "string",
- "null"
- ]
- },
- "ownerId": {
+ "updated_at": {
+ "description": "When the document was last updated",
+ "format": "date-time",
"type": "string"
- },
- "providerId": {
- "type": [
- "string",
- "null"
- ]
- },
- "senderEmail": {
- "type": [
- "string",
- "null"
- ]
- },
- "senderName": {
- "type": [
- "string",
- "null"
- ]
- },
- "senderPhotoUrl": {
- "type": [
- "string",
- "null"
- ]
- },
- "snippet": {
- "type": [
- "string",
- "null"
- ]
- },
- "sortTs": {
- "format": "int64",
- "type": "integer"
- },
- "updatedAt": {
- "format": "int64",
- "type": "integer"
- },
- "viewedAt": {
- "format": "int64",
- "type": [
- "integer",
- "null"
- ]
}
},
"required": [
- "id",
- "ownerId",
- "inboxVisible",
- "isRead",
- "isDraft",
- "isImportant",
- "sortTs",
- "createdAt",
- "updatedAt",
- "attachments",
- "macroAttachments",
- "contacts",
- "labels",
- "metadata"
+ "document_id",
+ "document_name",
+ "owner",
+ "created_at",
+ "updated_at",
+ "access_level"
],
"type": "object"
},
"type": "array"
},
- "next_cursor": {
- "type": [
- "string",
- "null"
- ]
+ "resultsReturned": {
+ "description": "The number of results returned",
+ "format": "uint",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "totalResults": {
+ "description": "Total number of results found",
+ "format": "uint",
+ "minimum": 0,
+ "type": "integer"
}
},
"required": [
- "items"
+ "results",
+ "totalResults",
+ "resultsReturned"
],
- "title": "ApiPaginatedThreadCursor",
+ "title": "ListDocumentsResponse",
"type": "object"
}
},
{
- "name": "UnifiedSearch",
+ "name": "MarkdownRewrite",
"inputSchema": {
"additionalProperties": false,
- "description": "Universal search across all content types (documents, emails, AI conversations, chat/slack threads/channels, projects aka folders). This tool will return broad metadata from successful results and/or content matches. Use the Read tool next to read the results from those matches. Only ever refer to documents by name or with a document mention. Never state the id of the document in plaintext. User's are presented with the results of this tool as a UI element so there is no need to enumerate the information found from this tool.",
+ "description": "Instruct an agent to edit a markdown file identified by an id.\n This tool should be used when the user include a markdown file in context and requests a revision or edit to that file",
"properties": {
- "exhaustiveSearch": {
- "additionalProperties": false,
- "default": true,
- "description": "Exhaustive search across all results matching the query. Defaults to true. Use false when the user only requires a limitied subset of results to answer the question",
- "type": "boolean"
- },
- "pageOffset": {
- "additionalProperties": false,
- "default": 0,
- "description": "Page offset. Default is 0. Use a higher offset to page through results intelligently. Set exhaustive_search to true to get all results.",
- "format": "int64",
- "type": "integer"
- },
- "pageSize": {
+ "instructions": {
"additionalProperties": false,
- "default": 10,
- "description": "Search count per search type (i.e. applies separately to each of documents, emails, ai_conversations, chats, projects). Max is 100. Default is 10. Does not apply when exhaustive_search is set to true.",
- "format": "int64",
- "type": "integer"
+ "description": "Instructions for the revision agent to follow to edit the markdown. These instructions will be provided by the user.",
+ "type": "string"
},
- "request": {
+ "markdown_file_id": {
"additionalProperties": false,
- "description": "Aggregated search request, see individual fields for details",
- "properties": {
- "filters": {
- "additionalProperties": false,
- "description": "Search filters for various kinds of items. Set the entire filters property as `null` if you do not have specific filters for a given type, e.g. bcc for email filters.",
- "properties": {
- "channel": {
- "additionalProperties": false,
- "description": "Channel filters. `null` to not filter channels searched over.",
- "properties": {
- "channel_ids": {
- "additionalProperties": false,
- "description": "Channel IDs to search within. Examples: ['general']. Empty to search all accessible channels.",
- "items": {
- "additionalProperties": false,
- "type": "string"
- },
- "type": "array"
+ "description": "The markdown file id to target for editing. This file id will be in your context and labeled as a markdown (md) document",
+ "type": "string"
+ }
+ },
+ "required": [
+ "instructions",
+ "markdown_file_id"
+ ],
+ "title": "MarkdownRewrite",
+ "type": "object"
+ },
+ "outputSchema": {
+ "additionalProperties": false,
+ "properties": {
+ "diffs": {
+ "items": {
+ "additionalProperties": false,
+ "properties": {
+ "markdown_text": {
+ "type": "string"
+ },
+ "node_key": {
+ "type": "string"
+ },
+ "operation": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "operation",
+ "node_key",
+ "markdown_text"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "diffs"
+ ],
+ "title": "AIDiffResponse",
+ "type": "object"
+ }
+ },
+ {
+ "name": "UnifiedSearch",
+ "inputSchema": {
+ "additionalProperties": false,
+ "description": "Universal search across all content types (documents, emails, AI conversations, chat/slack threads/channels, projects aka folders). This tool will return broad metadata from successful results and/or content matches. Use the Read tool next to read the results from those matches. Only ever refer to documents by name or with a document mention. Never state the id of the document in plaintext. User's are presented with the results of this tool as a UI element so there is no need to enumerate the information found from this tool.",
+ "properties": {
+ "exhaustiveSearch": {
+ "additionalProperties": false,
+ "default": true,
+ "description": "Exhaustive search across all results matching the query. Defaults to true. Use false when the user only requires a limitied subset of results to answer the question",
+ "type": "boolean"
+ },
+ "pageOffset": {
+ "additionalProperties": false,
+ "default": 0,
+ "description": "Page offset. Default is 0. Use a higher offset to page through results intelligently. Set exhaustive_search to true to get all results.",
+ "format": "int64",
+ "type": "integer"
+ },
+ "pageSize": {
+ "additionalProperties": false,
+ "default": 10,
+ "description": "Search count per search type (i.e. applies separately to each of documents, emails, ai_conversations, chats, projects). Max is 100. Default is 10. Does not apply when exhaustive_search is set to true.",
+ "format": "int64",
+ "type": "integer"
+ },
+ "request": {
+ "additionalProperties": false,
+ "description": "Aggregated search request, see individual fields for details",
+ "properties": {
+ "filters": {
+ "additionalProperties": false,
+ "description": "Search filters for various kinds of items. Set the entire filters property as `null` if you do not have specific filters for a given type, e.g. bcc for email filters.",
+ "properties": {
+ "channel": {
+ "additionalProperties": false,
+ "description": "Channel filters. `null` to not filter channels searched over.",
+ "properties": {
+ "channel_ids": {
+ "additionalProperties": false,
+ "description": "Channel IDs to search within. Examples: ['general']. Empty to search all accessible channels.",
+ "items": {
+ "additionalProperties": false,
+ "type": "string"
+ },
+ "type": "array"
},
"mentions": {
"additionalProperties": false,
@@ -1739,474 +1542,195 @@
}
},
{
- "name": "ListDocuments",
+ "name": "Read",
"inputSchema": {
"additionalProperties": false,
- "description": "List documents the user has access to with optional filtering and pagination. Only applies to documents, not emails, AI conversations, chat/slack threads, projects aka folders. This tool returns document metadata including access levels and supports filtering by file type, minimum access level, and pagination. Use this tool to discover and browse documents before using the Read tool to access their content. Prefer using the search tool to search on a specific matching string within the content or the name of the entity.",
+ "description": "Read content by ID(s). Supports reading documents, channels, chats, and emails by their respective IDs. Use this tool when you need to retrieve the full content of a specific item(s).\n Channel transcripts only include 300 messages. Use 'messages_since' to see messages in a different time window.",
"properties": {
- "exhaustiveSearch": {
+ "contentType": {
"additionalProperties": false,
- "default": false,
- "description": "Exhaustive search to get all results. Defaults to false. Set to true when you need all matching documents, ignoring pagination limits.",
- "type": "boolean"
+ "description": "The type of content to read. Choose based on the type of content you want to retrieve.",
+ "enum": [
+ "document",
+ "channel",
+ "channel-message",
+ "chat-thread",
+ "chat-message",
+ "email-thread",
+ "email-message",
+ "project"
+ ],
+ "type": "string"
},
- "fileTypes": {
+ "ids": {
"additionalProperties": false,
- "description": "Document file types to include. Examples: ['pdf'], ['md', 'txt']. Leave empty to include all document types.",
+ "description": "ID(s) of the content to read. IMPORTANT: document, channel-message, chat-message, and email-message content types support MULTIPLE ids! For all other content types (channel, chat-thread, email-thread) provide a single id.",
"items": {
"additionalProperties": false,
"type": "string"
},
- "type": [
- "array",
- "null"
- ]
+ "type": "array"
},
- "minAccessLevel": {
+ "messagesSince": {
"additionalProperties": false,
- "description": "Minimum access level required. Defaults to 'view' if not specified.",
- "enum": [
- "view",
- "comment",
- "edit",
- "owner",
- null
- ],
+ "description": "A local datetime of the earliest message to include in a channel transcript ex: 2025-11-25 12:00:09 EST, only applicable to channels",
+ "format": "date-time",
"type": [
"string",
"null"
]
- },
- "pageOffset": {
- "additionalProperties": false,
- "default": 0,
- "description": "Page offset for pagination. Default is 0. Use higher values to get subsequent pages of results.",
- "format": "int64",
- "type": "integer"
- },
- "pageSize": {
- "additionalProperties": false,
- "default": 50,
- "description": "Number of results per page. Max is 100, default is 50. Use smaller values for focused results.",
- "format": "int64",
- "type": "integer"
}
},
"required": [
- "exhaustiveSearch",
- "fileTypes",
- "minAccessLevel",
- "pageOffset",
- "pageSize"
+ "contentType",
+ "ids",
+ "messagesSince"
],
- "title": "ListDocuments",
+ "title": "Read",
"type": "object"
},
"outputSchema": {
"properties": {
- "results": {
- "description": "The list results (truncated to `results_returned` limit if applicable)",
- "items": {
- "properties": {
- "access_level": {
- "description": "The user's access level to this document",
- "enum": [
- "view",
- "comment",
- "edit",
- "owner"
- ],
- "type": "string"
+ "content": {
+ "oneOf": [
+ {
+ "properties": {
+ "documents": {
+ "items": {
+ "properties": {
+ "content": {
+ "type": "string"
+ },
+ "documentId": {
+ "type": "string"
+ },
+ "metadata": {
+ "properties": {
+ "deleted": {
+ "type": "boolean"
+ },
+ "documentName": {
+ "type": "string"
+ },
+ "fileType": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "owner": {
+ "type": "string"
+ },
+ "projectId": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "documentName",
+ "owner",
+ "deleted"
+ ],
+ "type": "object"
+ }
+ },
+ "required": [
+ "documentId",
+ "content",
+ "metadata"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "type": {
+ "const": "documents",
+ "type": "string"
+ }
},
- "created_at": {
- "description": "When the document was created",
- "format": "date-time",
- "type": "string"
+ "required": [
+ "type",
+ "documents"
+ ],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "channel_id": {
+ "type": "string"
+ },
+ "channel_name": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "transcript": {
+ "type": "string"
+ },
+ "type": {
+ "const": "channel",
+ "type": "string"
+ }
},
- "deleted_at": {
- "description": "When the document was deleted (null if not deleted)",
- "format": "date-time",
- "type": [
- "string",
- "null"
- ]
- },
- "document_id": {
- "description": "The document id",
- "type": "string"
- },
- "document_name": {
- "description": "The document name",
- "type": "string"
- },
- "file_type": {
- "description": "The file type of the document",
- "type": [
- "string",
- "null"
- ]
- },
- "owner": {
- "description": "The owner of the document",
- "type": "string"
- },
- "project_id": {
- "description": "The project id containing the document",
- "type": [
- "string",
- "null"
- ]
- },
- "updated_at": {
- "description": "When the document was last updated",
- "format": "date-time",
- "type": "string"
- }
- },
- "required": [
- "document_id",
- "document_name",
- "owner",
- "created_at",
- "updated_at",
- "access_level"
- ],
- "type": "object"
- },
- "type": "array"
- },
- "resultsReturned": {
- "description": "The number of results returned",
- "format": "uint",
- "minimum": 0,
- "type": "integer"
- },
- "totalResults": {
- "description": "Total number of results found",
- "format": "uint",
- "minimum": 0,
- "type": "integer"
- }
- },
- "required": [
- "results",
- "totalResults",
- "resultsReturned"
- ],
- "title": "ListDocumentsResponse",
- "type": "object"
- }
- },
- {
- "name": "MarkdownRewrite",
- "inputSchema": {
- "additionalProperties": false,
- "description": "Instruct an agent to edit a markdown file identified by an id.\n This tool should be used when the user include a markdown file in context and requests a revision or edit to that file",
- "properties": {
- "instructions": {
- "additionalProperties": false,
- "description": "Instructions for the revision agent to follow to edit the markdown. These instructions will be provided by the user.",
- "type": "string"
- },
- "markdown_file_id": {
- "additionalProperties": false,
- "description": "The markdown file id to target for editing. This file id will be in your context and labeled as a markdown (md) document",
- "type": "string"
- }
- },
- "required": [
- "instructions",
- "markdown_file_id"
- ],
- "title": "MarkdownRewrite",
- "type": "object"
- },
- "outputSchema": {
- "additionalProperties": false,
- "properties": {
- "diffs": {
- "items": {
- "additionalProperties": false,
- "properties": {
- "markdown_text": {
- "type": "string"
- },
- "node_key": {
- "type": "string"
- },
- "operation": {
- "type": "string"
- }
+ "required": [
+ "type",
+ "channel_id",
+ "transcript"
+ ],
+ "type": "object"
},
- "required": [
- "operation",
- "node_key",
- "markdown_text"
- ],
- "type": "object"
- },
- "type": "array"
- }
- },
- "required": [
- "diffs"
- ],
- "title": "AIDiffResponse",
- "type": "object"
- }
- },
- {
- "name": "Read",
- "inputSchema": {
- "additionalProperties": false,
- "description": "Read content by ID(s). Supports reading documents, channels, chats, and emails by their respective IDs. Use this tool when you need to retrieve the full content of a specific item(s).\n Channel transcripts only include 300 messages. Use 'messages_since' to see messages in a different time window.",
- "properties": {
- "contentType": {
- "additionalProperties": false,
- "description": "The type of content to read. Choose based on the type of content you want to retrieve.",
- "enum": [
- "document",
- "channel",
- "channel-message",
- "chat-thread",
- "chat-message",
- "email-thread",
- "email-message",
- "project"
- ],
- "type": "string"
- },
- "ids": {
- "additionalProperties": false,
- "description": "ID(s) of the content to read. IMPORTANT: document, channel-message, chat-message, and email-message content types support MULTIPLE ids! For all other content types (channel, chat-thread, email-thread) provide a single id.",
- "items": {
- "additionalProperties": false,
- "type": "string"
- },
- "type": "array"
- },
- "messagesSince": {
- "additionalProperties": false,
- "description": "A local datetime of the earliest message to include in a channel transcript ex: 2025-11-25 12:00:09 EST, only applicable to channels",
- "format": "date-time",
- "type": [
- "string",
- "null"
- ]
- }
- },
- "required": [
- "contentType",
- "ids",
- "messagesSince"
- ],
- "title": "Read",
- "type": "object"
- },
- "outputSchema": {
- "properties": {
- "content": {
- "oneOf": [
{
"properties": {
- "documents": {
+ "conversation": {
"items": {
"properties": {
- "content": {
- "type": "string"
- },
- "documentId": {
+ "chat_id": {
"type": "string"
},
- "metadata": {
- "properties": {
- "deleted": {
- "type": "boolean"
- },
- "documentName": {
- "type": "string"
- },
- "fileType": {
- "type": [
- "string",
- "null"
- ]
- },
- "owner": {
- "type": "string"
+ "messages": {
+ "items": {
+ "properties": {
+ "attachmentIds": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "content": {
+ "type": "string"
+ },
+ "date": {
+ "format": "date-time",
+ "type": "string"
+ }
},
- "projectId": {
- "type": [
- "string",
- "null"
- ]
- }
+ "required": [
+ "content",
+ "date",
+ "attachmentIds"
+ ],
+ "type": "object"
},
- "required": [
- "documentName",
- "owner",
- "deleted"
- ],
- "type": "object"
+ "type": "array"
+ },
+ "title": {
+ "type": "string"
}
},
"required": [
- "documentId",
- "content",
- "metadata"
+ "chat_id",
+ "title",
+ "messages"
],
"type": "object"
},
"type": "array"
},
"type": {
- "const": "documents",
- "type": "string"
- }
- },
- "required": [
- "type",
- "documents"
- ],
- "type": "object"
- },
- {
- "properties": {
- "channel_id": {
- "type": "string"
- },
- "channel_name": {
- "type": [
- "string",
- "null"
- ]
- },
- "transcript": {
- "type": "string"
- },
- "type": {
- "const": "channel",
- "type": "string"
- }
- },
- "required": [
- "type",
- "channel_id",
- "transcript"
- ],
- "type": "object"
- },
- {
- "properties": {
- "conversation": {
- "items": {
- "properties": {
- "chat_id": {
- "type": "string"
- },
- "messages": {
- "items": {
- "properties": {
- "attachment_summaries": {
- "items": {
- "oneOf": [
- {
- "additionalProperties": false,
- "properties": {
- "Summary": {
- "properties": {
- "created_at": {
- "format": "date-time",
- "type": [
- "string",
- "null"
- ]
- },
- "document_id": {
- "type": "string"
- },
- "id": {
- "type": [
- "string",
- "null"
- ]
- },
- "summary": {
- "type": "string"
- },
- "version_id": {
- "type": "string"
- }
- },
- "required": [
- "document_id",
- "summary",
- "version_id"
- ],
- "type": "object"
- }
- },
- "required": [
- "Summary"
- ],
- "type": "object"
- },
- {
- "additionalProperties": false,
- "properties": {
- "NoSummary": {
- "properties": {
- "document_id": {
- "type": "string"
- }
- },
- "required": [
- "document_id"
- ],
- "type": "object"
- }
- },
- "required": [
- "NoSummary"
- ],
- "type": "object"
- }
- ]
- },
- "type": "array"
- },
- "content": {
- "type": "string"
- },
- "date": {
- "format": "date-time",
- "type": "string"
- }
- },
- "required": [
- "content",
- "date",
- "attachment_summaries"
- ],
- "type": "object"
- },
- "type": "array"
- },
- "title": {
- "type": "string"
- }
- },
- "required": [
- "chat_id",
- "title",
- "messages"
- ],
- "type": "object"
- },
- "type": "array"
- },
- "type": {
- "const": "chat",
+ "const": "chat",
"type": "string"
}
},
@@ -2315,6 +1839,420 @@
"type": "object"
}
},
+ {
+ "name": "ListEmails",
+ "inputSchema": {
+ "additionalProperties": false,
+ "description": "List the emails the user has access to. Use this tool to discover and browse emails before using the Read tool to access their content. Prefer using the search tool to search on a specific matching string within the content or the name of the entity.",
+ "properties": {
+ "cursor": {
+ "additionalProperties": false,
+ "default": null,
+ "description": "A preview response will tell you what the next cursor id is.\n If expected emails are not in the current response and it gives you a cursor id, use this field to list the next page of emails. If no cursor id is provided you've reached the end",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "limit": {
+ "additionalProperties": false,
+ "default": 20,
+ "description": "limit the max emails returned. This defaults to 20 and has a maximum of 500",
+ "format": "int64",
+ "type": "integer"
+ },
+ "sortMethod": {
+ "additionalProperties": false,
+ "default": "viewed_at",
+ "description": "Sort response by one of: viewed_at | updated_at | created_at | viewed_updated. Prefer viewed_at unless the otherwise specified",
+ "enum": [
+ "viewed_at",
+ "updated_at",
+ "created_at",
+ "viewed_updated"
+ ],
+ "type": "string"
+ },
+ "view": {
+ "additionalProperties": false,
+ "default": {
+ "standardLabel": null,
+ "userLabel": null
+ },
+ "description": "Choose the view to list emails from. One of either standard label or user label must be specified, otherwise defaults to important.",
+ "properties": {
+ "standardLabel": {
+ "additionalProperties": false,
+ "description": "Prefer important or all. Leave empty if using a user label",
+ "enum": [
+ "Inbox",
+ "Sent",
+ "Drafts",
+ "Starred",
+ "All",
+ "Important",
+ "Other",
+ null
+ ],
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "userLabel": {
+ "additionalProperties": false,
+ "description": "Choose a custom user label to filter by (optional). Standard label will take precedence over user label if both are specified.",
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "standardLabel",
+ "userLabel"
+ ],
+ "type": "object"
+ }
+ },
+ "required": [
+ "cursor",
+ "limit",
+ "sortMethod",
+ "view"
+ ],
+ "title": "ListEmails",
+ "type": "object"
+ },
+ "outputSchema": {
+ "properties": {
+ "items": {
+ "items": {
+ "properties": {
+ "attachments": {
+ "items": {
+ "properties": {
+ "contentId": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "createdAt": {
+ "format": "int64",
+ "type": "integer"
+ },
+ "filename": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "id": {
+ "format": "uuid",
+ "type": "string"
+ },
+ "messageId": {
+ "format": "uuid",
+ "type": "string"
+ },
+ "mimeType": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "providerAttachmentId": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "sizeBytes": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "id",
+ "messageId",
+ "createdAt"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "contacts": {
+ "items": {
+ "properties": {
+ "emailAddress": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "id": {
+ "format": "uuid",
+ "type": "string"
+ },
+ "linkId": {
+ "format": "uuid",
+ "type": "string"
+ },
+ "name": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "sfsPhotoUrl": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "id",
+ "linkId"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "createdAt": {
+ "format": "int64",
+ "type": "integer"
+ },
+ "frecencyScore": {
+ "format": "double",
+ "type": [
+ "number",
+ "null"
+ ]
+ },
+ "id": {
+ "format": "uuid",
+ "type": "string"
+ },
+ "inboxVisible": {
+ "type": "boolean"
+ },
+ "isDraft": {
+ "type": "boolean"
+ },
+ "isImportant": {
+ "type": "boolean"
+ },
+ "isRead": {
+ "type": "boolean"
+ },
+ "labels": {
+ "items": {
+ "properties": {
+ "createdAt": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "id": {
+ "format": "uuid",
+ "type": "string"
+ },
+ "labelListVisibility": {
+ "enum": [
+ "LabelShow",
+ "LabelShowIfUnread",
+ "LabelHide"
+ ],
+ "type": "string"
+ },
+ "linkId": {
+ "format": "uuid",
+ "type": "string"
+ },
+ "messageListVisibility": {
+ "enum": [
+ "Show",
+ "Hide"
+ ],
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "providerLabelId": {
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "System",
+ "User"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "linkId",
+ "providerLabelId",
+ "name",
+ "createdAt",
+ "messageListVisibility",
+ "labelListVisibility",
+ "type"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "macroAttachments": {
+ "items": {
+ "properties": {
+ "dbId": {
+ "format": "uuid",
+ "type": "string"
+ },
+ "itemId": {
+ "format": "uuid",
+ "type": "string"
+ },
+ "itemType": {
+ "type": "string"
+ },
+ "messageId": {
+ "format": "uuid",
+ "type": "string"
+ }
+ },
+ "required": [
+ "dbId",
+ "messageId",
+ "itemId",
+ "itemType"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "metadata": {
+ "properties": {
+ "calendar_invite": {
+ "description": "if any email contains a calendar invite",
+ "type": "boolean"
+ },
+ "generic_sender": {
+ "description": "if any sender in the thread is a generic email",
+ "type": "boolean"
+ },
+ "known_sender": {
+ "description": "if user has previously emailed any sender in the thread",
+ "type": "boolean"
+ },
+ "tabular": {
+ "description": "if any email contains a <table> html tag",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "known_sender",
+ "tabular",
+ "calendar_invite",
+ "generic_sender"
+ ],
+ "type": "object"
+ },
+ "name": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "ownerId": {
+ "type": "string"
+ },
+ "providerId": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "senderEmail": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "senderName": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "senderPhotoUrl": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "snippet": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "sortTs": {
+ "format": "int64",
+ "type": "integer"
+ },
+ "updatedAt": {
+ "format": "int64",
+ "type": "integer"
+ },
+ "viewedAt": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "id",
+ "ownerId",
+ "inboxVisible",
+ "isRead",
+ "isDraft",
+ "isImportant",
+ "sortTs",
+ "createdAt",
+ "updatedAt",
+ "attachments",
+ "macroAttachments",
+ "contacts",
+ "labels",
+ "metadata"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "next_cursor": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "items"
+ ],
+ "title": "ApiPaginatedThreadCursor",
+ "type": "object"
+ }
+ },
{
"name": "web_search",
"inputSchema": {
diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/chat_history.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/chat_history.rs
index 812e2851b0..71b3d76079 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/chats/chat_history.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/chats/chat_history.rs
@@ -1,13 +1,12 @@
-use axum::extract::{Extension, Path, State};
+use axum::extract::{Path, State};
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_db_client::insight::chat_insight_context::get_chat_history;
+use macro_db_client::chat_history::get_chat_history;
use macro_middleware::cloud_storage::ensure_access::chat::ChatAccessLevelExtractor;
use model::chat::ChatHistory;
-use model::user::UserContext;
use models_permissions::share_permission::access_level::ViewAccessLevel;
use sqlx::PgPool;
@@ -24,19 +23,14 @@ use sqlx::PgPool;
(status = 500, body = String, description = "Internal server error")
)
)]
-#[tracing::instrument(skip(db, user_context), fields(user_id=?user_context.user_id, chat_id=?chat_id))]
+#[tracing::instrument(skip(db), fields(chat_id=?chat_id))]
pub async fn get_chat_history_handler(
_access: ChatAccessLevelExtractor<ViewAccessLevel>,
State(db): State<PgPool>,
- Extension(user_context): Extension<UserContext>,
Path(chat_id): Path<String>,
) -> Result<Json<ChatHistory>, Response> {
- // Note: Access control is handled by middleware for external routes
- // Internal routes trust the caller has proper access
-
let chat_history = get_chat_history(&db, &chat_id).await.map_err(|err| {
tracing::error!(
- user_id = ?user_context.user_id,
chat_id = %chat_id,
error = %err,
"Failed to get chat history"
diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/chat_history_batch_messages.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/chat_history_batch_messages.rs
index 6b38d86ec6..c3577d7015 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/chats/chat_history_batch_messages.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/chats/chat_history_batch_messages.rs
@@ -5,7 +5,7 @@ use axum::{
response::{IntoResponse, Response},
};
use macro_db_client::{
- chat::get_chat_ids_for_messages, insight::chat_insight_context::get_chat_history_for_messages,
+ chat::get_chat_ids_for_messages, chat_history::get_chat_history_for_messages,
share_permission::access_level::chat::get_highest_access_level_for_chats,
};
use model::chat::ChatHistory;
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context.rs b/rust/cloud-storage/document_cognition_service/src/api/context.rs
index 75a19f534a..cac66e4436 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context.rs
@@ -1,7 +1,6 @@
use crate::config::Config;
use axum::extract::FromRef;
use document_storage_service_client::DocumentStorageServiceClient;
-use insight_service_client::InsightContextProvider;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
use scribe::{
@@ -23,7 +22,6 @@ pub struct ApiContext {
pub document_storage_client: Arc<DocumentStorageServiceClient>,
pub macro_notify_client: Arc<macro_notify::MacroNotify>,
pub comms_service_client: Arc<comms_service_client::CommsServiceClient>,
- pub context_provider_client: Arc<InsightContextProvider>,
pub search_service_client: Arc<SearchServiceClient>,
pub scribe: Arc<DcsScribe>,
pub metering_client: Arc<metering_service_client::Client>,
@@ -42,7 +40,6 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
use document_cognition_service_client::DocumentCognitionServiceClient;
use document_storage_service_client::DocumentStorageServiceClient;
use email_service_client::{EmailServiceClient, EmailServiceClientExternal};
- use insight_service_client::InsightContextProvider;
use lexical_client::LexicalClient;
use macro_notify::MacroNotifyClient;
use metering_service_client::Client as MeteringClient;
@@ -69,7 +66,6 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
"dummy_auth_key".into(),
"http://localhost".into(),
));
- let context_provider_client = InsightContextProvider::create(sqs_client.clone(), "dummy");
let search_service_client =
SearchServiceClient::new("dummy_auth_key".into(), "http://localhost".into());
let lexical_client = Arc::new(LexicalClient::new(
@@ -119,7 +115,6 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
document_storage_client,
macro_notify_client: Arc::new(macro_notify_client),
comms_service_client,
- context_provider_client: Arc::new(context_provider_client),
search_service_client: Arc::new(search_service_client),
scribe: Arc::new(content_client),
metering_client: Arc::new(metering_client),
diff --git a/rust/cloud-storage/document_cognition_service/src/api/internal/chat_history.rs b/rust/cloud-storage/document_cognition_service/src/api/internal/chat_history.rs
index a428deaf85..c29a402358 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/internal/chat_history.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/internal/chat_history.rs
@@ -1,17 +1,35 @@
-use axum::Json;
use axum::extract::{Path, State};
-use macro_db_client::insight::chat_insight_context::get_chat_history;
+use axum::{
+ Json,
+ http::StatusCode,
+ response::{IntoResponse, Response},
+};
+use macro_db_client::chat_history::get_chat_history;
use model::chat::ChatHistory;
use sqlx::PgPool;
-#[tracing::instrument(skip(db))]
+/// Internal endpoint to retrieve chat history for a specific chat ID
+#[tracing::instrument(skip(db), fields(chat_id=?chat_id))]
pub async fn get_chat_history_handler(
State(db): State<PgPool>,
Path(chat_id): Path<String>,
-) -> Result<Json<ChatHistory>, axum::http::StatusCode> {
- let chat_history = get_chat_history(&db, &chat_id).await.map_err(|e| {
- tracing::error!(error = %e, chat_id = %chat_id, "Failed to get chat history");
- axum::http::StatusCode::INTERNAL_SERVER_ERROR
+) -> Result<Json<ChatHistory>, Response> {
+ let chat_history = get_chat_history(&db, &chat_id).await.map_err(|err| {
+ tracing::error!(
+ chat_id = %chat_id,
+ error = %err,
+ "Failed to get chat history"
+ );
+ let error_message = if err.to_string().contains("no rows returned") {
+ "Chat history not found"
+ } else {
+ "Failed to retrieve chat history"
+ };
+ (
+ StatusCode::NOT_FOUND,
+ Json(serde_json::json!({"error": error_message})),
+ )
+ .into_response()
})?;
Ok(Json(chat_history))
diff --git a/rust/cloud-storage/document_cognition_service/src/api/internal/chat_history_batch_messages.rs b/rust/cloud-storage/document_cognition_service/src/api/internal/chat_history_batch_messages.rs
index b33f9df04b..38c95fa402 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/internal/chat_history_batch_messages.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/internal/chat_history_batch_messages.rs
@@ -1,24 +1,38 @@
-use axum::Json;
use axum::extract::State;
-use macro_db_client::insight::chat_insight_context::get_chat_history_for_messages;
+use axum::{
+ Json,
+ http::StatusCode,
+ response::{IntoResponse, Response},
+};
+use macro_db_client::chat_history::get_chat_history_for_messages;
use model::chat::ChatHistory;
use models_dcs::api::ChatHistoryBatchMessagesRequest;
use sqlx::PgPool;
+/// Internal endpoint to retrieve chat history for multiple message IDs
#[tracing::instrument(skip(db))]
pub async fn get_chat_history_batch_messages_handler(
State(db): State<PgPool>,
Json(request): Json<ChatHistoryBatchMessagesRequest>,
-) -> Result<Json<ChatHistory>, axum::http::StatusCode> {
+) -> Result<Json<ChatHistory>, Response> {
let chat_history = get_chat_history_for_messages(&db, &request.message_ids)
.await
- .map_err(|e| {
+ .map_err(|err| {
tracing::error!(
- error = %e,
- message_ids = ?request.message_ids,
+ error = %err,
+ message_count = request.message_ids.len(),
"Failed to get chat history for messages"
);
- axum::http::StatusCode::INTERNAL_SERVER_ERROR
+ let error_message = if err.to_string().contains("no rows returned") {
+ "Chat history not found"
+ } else {
+ "Failed to retrieve chat history"
+ };
+ (
+ StatusCode::NOT_FOUND,
+ Json(serde_json::json!({"error": error_message})),
+ )
+ .into_response()
})?;
Ok(Json(chat_history))
diff --git a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
index d528863eab..e233df1232 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
@@ -58,9 +58,8 @@ use model::{
chat::{
AttachmentMetadata, AttachmentType, Chat, ChatAttachment, ChatAttachmentWithName,
ChatHistory, ChatMessage, ChatMessageWithAttachments, ConversationRecord,
- MessageWithAttachmentSummary, NewChatMessage, NewMessageAttachment, Summary,
+ MessageWithAttachments, NewChatMessage, NewMessageAttachment,
},
- insight_context::document::DocumentSummary,
macros::{Macro, MacroResponse, MacrosResponse},
response::{GenericErrorResponse, StringIDResponse},
version::DocumentCognitionServiceApiVersion,
@@ -131,8 +130,7 @@ use utoipa::OpenApi;
ChatAttachmentWithName,
ChatHistory,
ConversationRecord,
- MessageWithAttachmentSummary,
- Summary,
+ MessageWithAttachments,
ChatMessage,
ChatMessageWithAttachments,
ChatResponse,
@@ -141,7 +139,6 @@ use utoipa::OpenApi;
// Chat History
ChatHistoryBatchMessagesRequest,
- DocumentSummary,
// Citation
DocumentTextPart,
diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs
index c48d1c3560..92a90b9b16 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs
@@ -313,7 +313,7 @@ pub async fn handle_send_chat_message(
FALLBACK_MODEL
};
- let user_message_id =
+ let _user_message_id =
store_incoming_message(ctx.clone(), user_id, &chat, model, &incoming_message)
.await
.map_err(|err| {
@@ -418,8 +418,5 @@ pub async fn handle_send_chat_message(
}
}
}
- ctx.context_provider_client
- .provide_context(user_id, &user_message_id)
- .await;
Ok(())
}
diff --git a/rust/cloud-storage/document_cognition_service/src/config.rs b/rust/cloud-storage/document_cognition_service/src/config.rs
index 973de53fe9..2c4b6fe195 100644
--- a/rust/cloud-storage/document_cognition_service/src/config.rs
+++ b/rust/cloud-storage/document_cognition_service/src/config.rs
@@ -31,8 +31,6 @@ pub struct Config {
pub notification_queue: String,
/// comms service url
pub comms_service_url: String,
- /// the sqs to to send chat context to
- pub insight_context_queue: String,
pub search_event_queue: String,
pub sync_service_url: String,
pub sync_service_auth_key: String,
@@ -81,9 +79,6 @@ impl Config {
let comms_service_url =
std::env::var("COMMS_SERVICE_URL").context("COMMS_SERVICE_URL must be provided")?;
- let insight_context_queue = std::env::var("INSIGHT_CONTEXT_QUEUE")
- .context("INSIGHT_CONTEXT_QUEUE must be provided")?;
-
let search_event_queue =
std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE must be provided")?;
@@ -130,7 +125,6 @@ impl Config {
chat_delete_queue,
notification_queue,
comms_service_url,
- insight_context_queue,
search_event_queue,
sync_service_auth_key,
sync_service_url,
@@ -157,7 +151,6 @@ impl Config {
chat_delete_queue: Default::default(),
notification_queue: Default::default(),
comms_service_url: Default::default(),
- insight_context_queue: Default::default(),
search_event_queue: Default::default(),
sync_service_url: Default::default(),
sync_service_auth_key: Default::default(),
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index a5e023ead2..574d88bd65 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -5,7 +5,6 @@ use config::{Config, Environment};
use document_cognition_service_client::DocumentCognitionServiceClient;
use document_storage_service_client::DocumentStorageServiceClient;
use email_service_client::{EmailServiceClient, EmailServiceClientExternal};
-use insight_service_client::InsightContextProvider;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
@@ -78,7 +77,6 @@ async fn main() -> anyhow::Result<()> {
let sqs_client = sqs_client::SQS::new(queue_aws_client)
.document_text_extractor_queue(&config.document_text_extractor_queue)
.chat_delete_queue(&config.chat_delete_queue)
- .insight_context_queue(&config.insight_context_queue)
.search_event_queue(&config.search_event_queue);
let secretsmanager_client =
@@ -189,10 +187,6 @@ async fn main() -> anyhow::Result<()> {
.with_email_client(email_service_client)
.with_static_file_client(static_file_service_client.clone()),
),
- context_provider_client: Arc::new(InsightContextProvider::create(
- sqs_client.clone(),
- "chat",
- )),
sqs_client: Arc::new(sqs_client),
document_storage_client: Arc::new(document_storage_client),
macro_notify_client: Arc::new(macro_notify_client),
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index 461cbdda34..7bbd7e95e3 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -69,7 +69,6 @@ gmail_client = { path = "../gmail_client" }
html-escape = "0.2"
http-body-util = { workspace = true }
infer = "0.19.0"
-insight_service_client = { path = "../insight_service_client" }
lol_html = "2.4.0"
macro_auth = { path = "../macro_auth" }
macro_cors = { path = "../macro_cors" }
@@ -110,7 +109,6 @@ sqs_client = { path = "../sqs_client", default-features = false, features = [
"contacts",
"email",
"gmail",
- "insight_context",
"search",
] }
sqs_worker = { path = "../sqs_worker" }
diff --git a/rust/cloud-storage/email_service/justfile b/rust/cloud-storage/email_service/justfile
index a606e79996..5364a12f28 100644
--- a/rust/cloud-storage/email_service/justfile
+++ b/rust/cloud-storage/email_service/justfile
@@ -37,9 +37,6 @@ create-queues:
--queue-name backfill-queue --attributes VisibilityTimeout=61
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs create-queue \
--queue-name search-queue
- AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs create-queue \
- --queue-name insight-service-queue-dev.fifo \
- --attributes FifoQueue=true,ContentBasedDeduplication=true
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs create-queue \
--queue-name sfs-uploader-queue --attributes VisibilityTimeout=60
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs create-queue \
@@ -58,8 +55,6 @@ purge-queues:
--queue-url http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/my-test-scheduled-queue.fifo
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs purge-queue \
--queue-url http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/search-queue
- AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs purge-queue \
- --queue-url http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/insight-service-queue-dev.fifo
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs purge-queue \
--queue-url http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/sfs-uploader-queue
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs purge-queue \
diff --git a/rust/cloud-storage/email_service/src/api/email/sync/disable.rs b/rust/cloud-storage/email_service/src/api/email/sync/disable.rs
index 1c477635d8..eb7da4e042 100644
--- a/rust/cloud-storage/email_service/src/api/email/sync/disable.rs
+++ b/rust/cloud-storage/email_service/src/api/email/sync/disable.rs
@@ -4,10 +4,6 @@ use axum::Extension;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
-use insight_service_client::InsightContextProvider;
-use model::insight_context::email_insights::{
- EMAIL_INSIGHT_PROVIDER_SOURCE_NAME, EmailInfo, GenerateEmailInsightContext, LinkDeletedPayload,
-};
use model::response::{EmptyResponse, ErrorResponse};
use model::user::UserContext;
use models_email::email::service::link::Link;
@@ -131,25 +127,6 @@ pub async fn disable_handler(
})
.ok();
- // send message to insights queue
-
- let email_info = EmailInfo::LinkDeleted(LinkDeletedPayload {
- link_id: link_context_cloned.id.to_string(),
- email_address: link_context_cloned.email_address.0.as_ref().to_string(),
- });
-
- let insights_message = GenerateEmailInsightContext {
- macro_user_id: link_context_cloned.macro_id.to_string(),
- info: email_info,
- };
-
- let provider = InsightContextProvider::create(
- ctx.sqs_client.as_ref().clone(),
- EMAIL_INSIGHT_PROVIDER_SOURCE_NAME,
- );
-
- provider.provide_email_context(insights_message).await.ok();
-
if let Err(e) = email_db_client::links::delete::delete_link_by_id(&db, link_id).await {
tracing::error!(error=?e, link_id=?link_id, "Failed to delete link in background task");
} else {
diff --git a/rust/cloud-storage/email_service/src/api/internal/backfill.rs b/rust/cloud-storage/email_service/src/api/internal/backfill.rs
deleted file mode 100644
index 96fa2204a0..0000000000
--- a/rust/cloud-storage/email_service/src/api/internal/backfill.rs
+++ /dev/null
@@ -1,30 +0,0 @@
-use crate::api::ApiContext;
-
-use axum::{
- extract::State,
- http::StatusCode,
- response::{IntoResponse, Json, Response},
-};
-use email_service::util::backfill::backfill_insights::backfill_email_insights;
-use model::insight_context::email_insights::BackfillEmailInsightsFilter;
-
-/// Internal endpoint to backfill insights from emails
-#[tracing::instrument(skip_all)]
-pub async fn backfill_insights_handler(
- State(ctx): State<ApiContext>,
- Json(req_body): Json<BackfillEmailInsightsFilter>,
-) -> Result<Response, Response> {
- let sqs_client = ctx.sqs_client.as_ref().clone();
- let db = ctx.db.clone();
- match backfill_email_insights(sqs_client, &db, req_body).await {
- Ok(response) => Ok((StatusCode::OK, Json(response)).into_response()),
- Err(e) => {
- tracing::error!(error=?e, "backfill insights failed");
- Err((
- StatusCode::INTERNAL_SERVER_ERROR,
- "backfill insights failed",
- )
- .into_response())
- }
- }
-}
diff --git a/rust/cloud-storage/email_service/src/api/internal/mod.rs b/rust/cloud-storage/email_service/src/api/internal/mod.rs
index ebb4b683a0..3f1eb37eab 100644
--- a/rust/cloud-storage/email_service/src/api/internal/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/internal/mod.rs
@@ -3,7 +3,6 @@ use axum::routing::{delete, get, post};
use crate::api::ApiContext;
-mod backfill;
mod delete_user;
mod get_message_by_id;
mod get_message_senders;
@@ -38,10 +37,6 @@ pub fn router() -> Router<ApiContext> {
.route("/backfill/provider/gmail", post(gmail::create::handler))
.route("/backfill/provider/gmail", delete(gmail::cancel::handler))
.route("/backfill/provider/gmail/:id", get(gmail::get::handler))
- .route(
- "/backfill/insights",
- post(backfill::backfill_insights_handler),
- )
.route("/delete_user/:id", delete(delete_user::handler))
.route("/threads/:id/owner", get(get_thread_owner::handler))
}
diff --git a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
index 20125790f8..3e2beb2e41 100644
--- a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
+++ b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
@@ -90,7 +90,6 @@ async fn main() -> anyhow::Result<()> {
.gmail_inbox_sync_queue(&config.gmail_inbox_sync_queue)
.gmail_inbox_sync_retry_queue(&config.gmail_inbox_sync_retry_queue)
.search_event_queue(&config.search_event_queue)
- .insight_context_queue(&config.insight_context_queue)
.email_backfill_queue(&config.backfill_queue)
.email_scheduled_queue(&config.email_scheduled_queue)
.sfs_uploader_queue(&config.sfs_uploader_queue)
diff --git a/rust/cloud-storage/email_service/src/config.rs b/rust/cloud-storage/email_service/src/config.rs
index 28cf71c62d..64ed32cf27 100644
--- a/rust/cloud-storage/email_service/src/config.rs
+++ b/rust/cloud-storage/email_service/src/config.rs
@@ -32,9 +32,6 @@ pub struct Config {
/// The SQS queue name for search event
pub search_event_queue: String,
- /// Insight context queue
- pub insight_context_queue: String,
-
/// The GCP queue name that has the subscription that hits our webhook endpoint
pub gmail_gcp_queue: String,
@@ -155,9 +152,6 @@ impl Config {
let search_event_queue =
std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE must be provided")?;
- let insight_context_queue = std::env::var("INSIGHT_CONTEXT_QUEUE")
- .context("INSIGHT_CONTEXT_QUEUE must be provided")?;
-
let gmail_gcp_queue =
std::env::var("GMAIL_GCP_QUEUE").context("GMAIL_GCP_QUEUE must be provided")?;
@@ -279,7 +273,6 @@ impl Config {
gmail_inbox_sync_queue,
gmail_inbox_sync_retry_queue,
search_event_queue,
- insight_context_queue,
gmail_gcp_queue,
notification_queue,
backfill_queue,
diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rs
index 38f60712e4..37a076e3d4 100644
--- a/rust/cloud-storage/email_service/src/main.rs
+++ b/rust/cloud-storage/email_service/src/main.rs
@@ -83,7 +83,6 @@ async fn main() -> anyhow::Result<()> {
.gmail_inbox_sync_queue(&config.gmail_inbox_sync_queue)
.gmail_inbox_sync_retry_queue(&config.gmail_inbox_sync_retry_queue)
.search_event_queue(&config.search_event_queue)
- .insight_context_queue(&config.insight_context_queue)
.email_backfill_queue(&config.backfill_queue)
.email_scheduled_queue(&config.email_scheduled_queue)
.sfs_uploader_queue(&config.sfs_uploader_queue)
diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs
index 8c5962a0d2..1de5fb9517 100644
--- a/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs
@@ -1,7 +1,5 @@
use crate::pubsub::context::PubSubContext;
-use crate::util::backfill::backfill_insights::backfill_email_insights;
use model::contacts::ConnectionsMessage;
-use model::insight_context::email_insights::BackfillEmailInsightsFilter;
use models_email::db::address::EmailRecipientType;
use models_email::service::attachment::{
AttachmentUploadArgs, AttachmentUploadDestination, AttachmentUploadMetadata,
@@ -94,25 +92,6 @@ async fn handle_job_completed(
})
})?;
- tracing::info!("Backfilling email insights for user {}", link.macro_id);
- let backfill_email_insights_filter = BackfillEmailInsightsFilter {
- user_ids: Some(vec![link.macro_id.to_string()]),
- user_thread_limit: None,
- };
-
- backfill_email_insights(
- ctx.sqs_client.clone(),
- &ctx.db,
- backfill_email_insights_filter,
- )
- .await
- .map_err(|e| {
- ProcessingError::NonRetryable(DetailedError {
- reason: FailureReason::DatabaseQueryFailed,
- source: e.context("Failed to backfill email insights"),
- })
- })?;
-
handle_attachment_upload(ctx, link, job_id).await?;
handle_contacts_sync(ctx, link).await?;
diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs
index 5c0448d3d0..505b90a890 100644
--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs
@@ -5,16 +5,10 @@ use crate::pubsub::inbox_sync::process::check_gmail_rate_limit_inbox_sync;
use crate::pubsub::util::cg_refresh_email;
use crate::util::process_pre_insert::{process_message_pre_insert, process_threads_pre_insert};
use crate::util::upload_attachment::{UploadAttachmentContext, upload_attachment};
-use anyhow::Context;
use email_db_client::threads;
use email_utils::dedupe_emails;
-use insight_service_client::InsightContextProvider;
use macro_user_id::user_id::MacroUserIdStr;
use model::contacts::ConnectionsMessage;
-use model::insight_context::email_insights::{
- EMAIL_INSIGHT_PROVIDER_SOURCE_NAME, EmailInfo, GenerateEmailInsightContext, NewMessagePayload,
- NewMessagesPayload,
-};
use model_entity::EntityType;
use model_notifications::{NewEmailMetadata, NotificationEvent, NotificationQueueMessage};
use models_email::db::address::EmailRecipientType;
@@ -365,52 +359,6 @@ async fn handle_contacts_sync(
Ok(())
}
-/// Sends new message context to the insight service
-async fn generate_email_insights_for_new_message(
- ctx: &PubSubContext,
- link: &service::link::Link,
- message_id: Uuid,
- thread_id: Uuid,
-) -> anyhow::Result<()> {
- // Fetch the thread and ensure it's an outbound thread (has latest_outbound)
- let thread =
- email_db_client::threads::get::get_thread_by_id_and_link_id(&ctx.db, thread_id, link.id)
- .await
- .context("Failed to fetch thread for new message")?;
-
- let Some(thread) = thread else {
- tracing::warn!(%thread_id, link_id = %link.id, "Thread not found; skipping insight generation");
- return Ok(());
- };
-
- if thread.latest_outbound_message_ts.is_none() {
- return Ok(());
- }
-
- let macro_user_id = link.macro_id.to_string();
-
- let context = GenerateEmailInsightContext {
- macro_user_id: macro_user_id.clone(),
- info: EmailInfo::NewMessages(NewMessagesPayload {
- messages: vec![NewMessagePayload {
- thread_id,
- message_id,
- user_email: link.email_address.0.as_ref().to_string(),
- }],
- batch_id: Uuid::new_v4().to_string(),
- }),
- };
-
- let provider =
- InsightContextProvider::create(ctx.sqs_client.clone(), EMAIL_INSIGHT_PROVIDER_SOURCE_NAME);
-
- if let Err(err) = provider.provide_email_context(context.clone()).await {
- tracing::error!(?context, error = %err, "Failed to provide email context to insight service");
- }
-
- Ok(())
-}
-
/// Process and insert email threads by handling attachments and images
#[tracing::instrument(skip(ctx, gmail_access_token))]
async fn fetch_and_insert_thread(
@@ -517,10 +465,6 @@ async fn notify_for_new_message(
// notify user of new messages
send_notifications(ctx, link, new_message_provider_id).await?;
- generate_email_insights_for_new_message(ctx, link, message_db_id, thread_id)
- .await
- .ok();
-
Ok(())
}
diff --git a/rust/cloud-storage/email_service/src/util/backfill/backfill_insights.rs b/rust/cloud-storage/email_service/src/util/backfill/backfill_insights.rs
deleted file mode 100644
index 39cd3db896..0000000000
--- a/rust/cloud-storage/email_service/src/util/backfill/backfill_insights.rs
+++ /dev/null
@@ -1,754 +0,0 @@
-use email_db_client::links::get::fetch_link_by_macro_id;
-use email_db_client::threads::get::get_threads_by_user_with_outbound;
-use insight_service_client::InsightContextProvider;
-use model::insight_context::email_insights::{
- BackfillBatchPayload, BackfillEmailInsightsFilter, EMAIL_INSIGHT_BATCH_SIZE,
- EMAIL_INSIGHT_PROVIDER_SOURCE_NAME, EmailInfo, GenerateEmailInsightContext,
-};
-use models_email::email::service::thread::UserThreadsPage;
-use serde::{Deserialize, Serialize};
-use sqlx::{Pool, Postgres};
-use sqs_client::SQS;
-use uuid::Uuid;
-
-#[derive(Debug, Serialize, Deserialize)]
-pub struct BackfillJobResponse {
- pub job_ids: Vec<String>,
-}
-
-#[tracing::instrument(skip(sqs_client, db))]
-pub async fn backfill_email_insights(
- sqs_client: SQS,
- db: &Pool<Postgres>,
- req: BackfillEmailInsightsFilter,
-) -> anyhow::Result<BackfillJobResponse> {
- tracing::info!("backfill email insights");
-
- let user_ids = if let Some(ref ids) = req.user_ids {
- ids.clone()
- } else {
- anyhow::bail!("user_ids required for now");
- };
- let user_thread_limit = req.user_thread_limit;
-
- // Generate unique job IDs for each user (insight service will create the actual job records)
- let mut job_ids = Vec::new();
- for user_id in &user_ids {
- let job_id = Uuid::new_v4().to_string();
- tracing::info!("Generated job ID {} for user {}", job_id, user_id);
- job_ids.push(job_id);
- }
-
- let provider =
- InsightContextProvider::create(sqs_client.clone(), EMAIL_INSIGHT_PROVIDER_SOURCE_NAME);
-
- tracing::debug!("received user ids: {:?}", user_ids);
-
- // Fetch all user emails for each user
- let mut user_emails_map = std::collections::HashMap::new();
- for user_id in &user_ids {
- let link = fetch_link_by_macro_id(db, user_id)
- .await
- .inspect_err(|e| {
- tracing::error!(error=?e, "Failed to fetch links for user");
- })?
- .ok_or_else(|| {
- tracing::error!(user_id=%user_id, "No link found for user");
- anyhow::anyhow!("No link found for user {}", user_id)
- })?;
- tracing::debug!(
- "user {} has email account {} linked",
- user_id,
- link.email_address.0.as_ref()
- );
- user_emails_map.insert(
- user_id.clone(),
- vec![link.email_address.0.as_ref().to_string()],
- );
- }
-
- let mut user_offsets: std::collections::HashMap<String, i64> =
- user_ids.iter().map(|u| (u.clone(), 0)).collect();
- let mut user_processed: std::collections::HashMap<String, i64> =
- user_ids.iter().map(|u| (u.clone(), 0)).collect();
- let user_job_ids: std::collections::HashMap<String, String> = user_ids
- .iter()
- .zip(job_ids.iter())
- .map(|(u, j)| (u.clone(), j.clone()))
- .collect();
-
- tracing::debug!("processing users: {:?}", user_offsets);
-
- while !user_offsets.is_empty() {
- let mut finished_users = Vec::new();
- for (user_id, offset) in user_offsets.iter_mut() {
- tracing::debug!("processing user {} at offset {}", user_id, offset);
- let Some(processed) = user_processed.get_mut(user_id) else {
- tracing::warn!("user {} not found in processed map", user_id);
- continue;
- };
- let Some(job_id) = user_job_ids.get(user_id) else {
- tracing::warn!("user {} not found in job ids map", user_id);
- continue;
- };
- if let Some(limit) = user_thread_limit
- && *processed >= limit
- {
- tracing::debug!("user {} has reached thread limit {}", user_id, limit);
- finished_users.push(user_id.clone());
- continue;
- }
- let page: UserThreadsPage =
- get_threads_by_user_with_outbound(db, user_id, EMAIL_INSIGHT_BATCH_SIZE, *offset)
- .await
- .inspect_err(|e| {
- tracing::error!(error=?e, "Failed to fetch threads for user");
- })?;
- tracing::debug!("user {} threads page {:?}", user_id, page);
- if page.threads.is_empty() {
- finished_users.push(user_id.clone());
- continue;
- }
- let threads: Vec<String> = if let Some(limit) = user_thread_limit {
- let remaining = limit - *processed;
- if remaining < page.threads.len() as i64 {
- page.threads
- .iter()
- .take(remaining as usize)
- .map(|t| t.thread_id.to_string())
- .collect()
- } else {
- page.threads
- .iter()
- .map(|t| t.thread_id.to_string())
- .collect()
- }
- } else {
- page.threads
- .iter()
- .map(|t| t.thread_id.to_string())
- .collect()
- };
-
- let thread_count = threads.len() as i64;
- *processed += thread_count;
- tracing::debug!("user {} processed threads {}", user_id, processed);
-
- let is_complete =
- page.is_complete || user_thread_limit.is_some_and(|limit| *processed >= limit);
-
- let Some(user_emails) = user_emails_map.get(user_id).cloned() else {
- tracing::warn!("user {} not found in emails map", user_id);
- continue;
- };
-
- // Generate unique batch ID for insight service tracking
- let batch_id = Uuid::new_v4().to_string();
-
- let payload = BackfillBatchPayload {
- thread_ids: threads,
- batch_size: thread_count,
- is_complete,
- user_emails,
- job_id: job_id.clone(),
- batch_id: batch_id.clone(),
- };
- let context = GenerateEmailInsightContext {
- macro_user_id: user_id.clone(),
- info: EmailInfo::Backfill(payload),
- };
- tracing::debug!("generated email context {:?}", context);
-
- // Send to SQS - fail the entire request if SQS fails
- if let Err(e) = provider.provide_email_context(context).await {
- tracing::error!(error=?e, user_id=%user_id, job_id=%job_id, batch_id=%batch_id, "Failed to send batch to SQS");
- anyhow::bail!("Failed to queue backfill batch");
- }
-
- if is_complete {
- finished_users.push(user_id.clone());
- } else {
- *offset += EMAIL_INSIGHT_BATCH_SIZE;
- }
- }
- for user_id in finished_users {
- user_offsets.remove(&user_id);
- user_processed.remove(&user_id);
- }
- }
-
- let response = BackfillJobResponse { job_ids };
-
- Ok(response)
-}
-
-#[cfg(test)]
-mod backfill_tests {
- use super::*;
- use model::insight_context::email_insights::GenerateEmailInsightContext;
- use models_email::email::service::thread::{ThreadUserInfo, UserThreadsPage};
- use std::sync::{Arc, Mutex};
- use uuid::Uuid;
-
- struct MockProvider {
- pub batches: Arc<Mutex<Vec<GenerateEmailInsightContext>>>,
- pub should_fail: bool,
- }
-
- impl MockProvider {
- pub fn new() -> Self {
- Self {
- batches: Arc::new(Mutex::new(vec![])),
- should_fail: false,
- }
- }
-
- pub fn with_failure() -> Self {
- Self {
- batches: Arc::new(Mutex::new(vec![])),
- should_fail: true,
- }
- }
-
- pub async fn provide_email_context(
- &self,
- context: GenerateEmailInsightContext,
- ) -> anyhow::Result<()> {
- if self.should_fail {
- anyhow::bail!("SQS send failed");
- }
- self.batches.lock().unwrap().push(context);
- Ok(())
- }
- }
-
- // Test data builders
- fn create_test_threads(count: usize, start_id: u128) -> Vec<ThreadUserInfo> {
- (0..count)
- .map(|i| ThreadUserInfo {
- thread_id: Uuid::from_u128(start_id + i as u128),
- })
- .collect()
- }
-
- // Mock get_threads_by_user_with_outbound with configurable behavior
- async fn mock_get_threads_by_user_with_outbound(
- user_id: &str,
- batch_size: i64,
- offset: i64,
- ) -> anyhow::Result<UserThreadsPage> {
- let total = match user_id {
- "macro|[email protected]" => 5,
- "macro|[email protected]" => 3,
- "macro|[email protected]" => 0,
- _ => 2,
- };
-
- let start = offset;
- let end = (offset + batch_size).min(total);
- let threads = create_test_threads((end - start) as usize, start as u128 + 1);
- let is_complete = end >= total;
-
- Ok(UserThreadsPage {
- threads,
- is_complete,
- })
- }
-
- #[tokio::test]
- async fn test_backfill_email_insights_request_validation() {
- // Test successful request structure
- let req = BackfillEmailInsightsFilter {
- user_ids: Some(vec![
- "macro|[email protected]".to_string(),
- "macro|[email protected]".to_string(),
- ]),
- user_thread_limit: Some(3),
- };
-
- let user_ids = req.user_ids.as_ref().unwrap();
- assert_eq!(user_ids.len(), 2);
- assert_eq!(user_ids[0], "macro|[email protected]");
- assert_eq!(user_ids[1], "macro|[email protected]");
- assert_eq!(req.user_thread_limit, Some(3));
-
- // Test job ID generation uniqueness
- let mut job_ids = Vec::new();
- for _user_id in user_ids {
- let job_id = Uuid::new_v4().to_string();
- job_ids.push(job_id);
- }
-
- assert_eq!(job_ids.len(), 2);
- assert_ne!(job_ids[0], job_ids[1]);
- }
-
- #[tokio::test]
- async fn test_backfill_email_insights_no_user_ids() {
- let req = BackfillEmailInsightsFilter {
- user_ids: None,
- user_thread_limit: None,
- };
-
- // Request should be invalid without user IDs
- assert!(req.user_ids.is_none());
- }
-
- #[tokio::test]
- async fn test_backfill_email_insights_empty_user_list() {
- let req = BackfillEmailInsightsFilter {
- user_ids: Some(vec![]),
- user_thread_limit: Some(10),
- };
-
- let user_ids = req.user_ids.as_ref().unwrap();
- assert!(user_ids.is_empty());
- }
-
- #[tokio::test]
- async fn test_backfill_with_thread_limit() {
- // Test that thread limit is respected
- let user_id = "macro|[email protected]";
- let limit = 3i64;
- let batch_size = 2i64;
-
- let mut processed = 0i64;
- let mut offset = 0i64;
- let mut batches = Vec::new();
-
- while processed < limit {
- let page = mock_get_threads_by_user_with_outbound(user_id, batch_size, offset)
- .await
- .unwrap();
-
- if page.threads.is_empty() {
- break;
- }
-
- let remaining = limit - processed;
- let threads_to_take = if remaining < page.threads.len() as i64 {
- remaining as usize
- } else {
- page.threads.len()
- };
-
- let threads: Vec<String> = page
- .threads
- .iter()
- .take(threads_to_take)
- .map(|t| t.thread_id.to_string())
- .collect();
-
- processed += threads.len() as i64;
- batches.push(threads);
-
- if processed >= limit || page.is_complete {
- break;
- }
-
- offset += batch_size;
- }
-
- assert_eq!(processed, limit);
- assert_eq!(batches.len(), 2); // 2 threads, then 1 thread
- assert_eq!(batches[0].len(), 2);
- assert_eq!(batches[1].len(), 1);
- }
-
- #[tokio::test]
- async fn test_backfill_empty_user() {
- // Test user with no threads
- let user_id = "macro|[email protected]";
- let batch_size = 10i64;
-
- let page = mock_get_threads_by_user_with_outbound(user_id, batch_size, 0)
- .await
- .unwrap();
-
- assert!(page.threads.is_empty());
- assert!(page.is_complete);
- }
-
- #[tokio::test]
- async fn test_provider_error_handling() {
- let provider = MockProvider::with_failure();
- let context = GenerateEmailInsightContext {
- macro_user_id: "test_user".to_string(),
- info: EmailInfo::Backfill(BackfillBatchPayload {
- thread_ids: vec!["thread1".to_string()],
- batch_size: 1,
- is_complete: true,
- user_emails: vec!["[email protected]".to_string()],
- job_id: "test_job".to_string(),
- batch_id: "test_batch".to_string(),
- }),
- };
-
- let result = provider.provide_email_context(context).await;
- assert!(result.is_err());
- assert!(result.unwrap_err().to_string().contains("SQS send failed"));
- }
-
- #[tokio::test]
- async fn test_batch_payload_creation() {
- let thread_ids = vec!["thread1".to_string(), "thread2".to_string()];
- let user_emails = vec!["[email protected]".to_string()];
- let job_id = "test_job_123".to_string();
- let batch_id = Uuid::new_v4().to_string();
-
- let payload = BackfillBatchPayload {
- thread_ids: thread_ids.clone(),
- batch_size: thread_ids.len() as i64,
- is_complete: false,
- user_emails: user_emails.clone(),
- job_id: job_id.clone(),
- batch_id: batch_id.clone(),
- };
-
- assert_eq!(payload.thread_ids, thread_ids);
- assert_eq!(payload.batch_size, 2);
- assert!(!payload.is_complete);
- assert_eq!(payload.user_emails, user_emails);
- assert_eq!(payload.job_id, job_id);
- assert_eq!(payload.batch_id, batch_id);
- }
-
- #[tokio::test]
- async fn test_backfill_batching_and_limit() {
- let user_ids = vec![
- "macro|[email protected]".to_string(),
- "macro|[email protected]".to_string(),
- ];
- let user_thread_limit = Some(4); // Should only process up to 4 threads per user
- let batch_size = 2;
-
- let provider = MockProvider::new();
- let mut user_offsets: std::collections::HashMap<String, i64> =
- user_ids.iter().map(|u| (u.clone(), 0)).collect();
- let mut user_processed: std::collections::HashMap<String, i64> =
- user_ids.iter().map(|u| (u.clone(), 0)).collect();
- while !user_offsets.is_empty() {
- let mut finished_users = Vec::new();
- for (user_id, offset) in user_offsets.iter_mut() {
- let processed = user_processed.get_mut(user_id).unwrap();
- if let Some(limit) = user_thread_limit {
- if *processed >= limit {
- finished_users.push(user_id.clone());
- continue;
- }
- }
- let page = mock_get_threads_by_user_with_outbound(user_id, batch_size, *offset)
- .await
- .unwrap();
- if page.threads.is_empty() {
- finished_users.push(user_id.clone());
- continue;
- }
- let threads: Vec<String> = if let Some(limit) = user_thread_limit {
- let remaining = limit - *processed;
- if remaining < page.threads.len() as i64 {
- page.threads
- .iter()
- .take(remaining as usize)
- .map(|t| t.thread_id.to_string())
- .collect()
- } else {
- page.threads
- .iter()
- .map(|t| t.thread_id.to_string())
- .collect()
- }
- } else {
- page.threads
- .iter()
- .map(|t| t.thread_id.to_string())
- .collect()
- };
- *processed += threads.len() as i64;
- let is_complete = page.is_complete
- || (user_thread_limit.is_some() && *processed >= user_thread_limit.unwrap());
- let payload = BackfillBatchPayload {
- thread_ids: threads,
- batch_size,
- is_complete,
- user_emails: vec![],
- job_id: "test_job_id".to_string(),
- batch_id: "test_batch_id".to_string(),
- };
- let context = GenerateEmailInsightContext {
- macro_user_id: user_id.clone(),
- info: EmailInfo::Backfill(payload),
- };
- let _ = provider.provide_email_context(context).await;
- if is_complete {
- finished_users.push(user_id.clone());
- } else {
- *offset += batch_size;
- }
- }
- for user_id in finished_users {
- user_offsets.remove(&user_id);
- user_processed.remove(&user_id);
- }
- }
- // Assert: provider.batches contains the expected number of batches and threads per user
- let batches = provider.batches.lock().unwrap();
- // user1: 5 threads, but limit is 4, so 2 batches of 2
- // user2: 3 threads, but limit is 3, so 2 batches: 2 and 1
- let user1_batches: Vec<_> = batches
- .iter()
- .filter(|b| b.macro_user_id == "macro|[email protected]")
- .collect();
- let user2_batches: Vec<_> = batches
- .iter()
- .filter(|b| b.macro_user_id == "macro|[email protected]")
- .collect();
- assert_eq!(user1_batches.len(), 2);
- assert_eq!(user2_batches.len(), 2);
- assert_eq!(
- user1_batches[0]
- .info
- .as_backfill()
- .unwrap()
- .thread_ids
- .len(),
- 2
- );
- assert_eq!(
- user1_batches[1]
- .info
- .as_backfill()
- .unwrap()
- .thread_ids
- .len(),
- 2
- );
- assert_eq!(
- user2_batches[0]
- .info
- .as_backfill()
- .unwrap()
- .thread_ids
- .len(),
- 2
- );
- assert_eq!(
- user2_batches[1]
- .info
- .as_backfill()
- .unwrap()
- .thread_ids
- .len(),
- 1
- );
- // Check is_complete flag
- assert!(!user1_batches[0].info.as_backfill().unwrap().is_complete);
- assert!(user1_batches[1].info.as_backfill().unwrap().is_complete);
- assert!(!user2_batches[0].info.as_backfill().unwrap().is_complete);
- assert!(user2_batches[1].info.as_backfill().unwrap().is_complete);
- }
-
- // Helper to extract BackfillBatchPayload from EmailInfo
- trait AsBackfill {
- fn as_backfill(&self) -> Option<&BackfillBatchPayload>;
- }
- impl AsBackfill for EmailInfo {
- fn as_backfill(&self) -> Option<&BackfillBatchPayload> {
- if let EmailInfo::Backfill(payload) = self {
- Some(payload)
- } else {
- None
- }
- }
- }
-
- #[tokio::test]
- async fn test_backfill_handler_simplified() {
- // Test the simplified job ID generation logic
-
- let user_ids = vec!["test_user_1".to_string(), "test_user_2".to_string()];
-
- // Simulate the simplified job creation part of the handler
- let mut job_ids = Vec::new();
- for _user_id in &user_ids {
- // Generate unique job ID for insight service tracking
- let job_id = Uuid::new_v4().to_string();
- job_ids.push(job_id);
- }
-
- assert_eq!(job_ids.len(), 2);
- assert_ne!(job_ids[0], job_ids[1]);
-
- // Verify UUIDs are valid format
- for job_id in &job_ids {
- assert!(Uuid::parse_str(job_id).is_ok());
- }
- }
-
- #[test]
- fn test_backfill_response_structure() {
- let job_ids = vec!["test_job_123".to_string(), "test_job_456".to_string()];
- let response = BackfillJobResponse {
- job_ids: job_ids.clone(),
- };
-
- // Test serialization
- let json = serde_json::to_string(&response).expect("Should serialize");
- let expected = r#"{"job_ids":["test_job_123","test_job_456"]}"#;
- assert_eq!(json, expected);
-
- // Test deserialization
- let deserialized: BackfillJobResponse =
- serde_json::from_str(&json).expect("Should deserialize");
- assert_eq!(deserialized.job_ids, job_ids);
- }
-
- #[test]
- fn test_backfill_response_empty() {
- let response = BackfillJobResponse { job_ids: vec![] };
-
- let json = serde_json::to_string(&response).expect("Should serialize");
- let expected = r#"{"job_ids":[]}"#;
- assert_eq!(json, expected);
- }
-
- #[tokio::test]
- async fn test_uuid_generation_uniqueness() {
- // Test that generated UUIDs are unique across multiple calls
- let mut uuids = std::collections::HashSet::new();
-
- for _ in 0..1000 {
- let uuid = Uuid::new_v4().to_string();
- assert!(
- Uuid::parse_str(&uuid).is_ok(),
- "UUID should be valid format"
- );
- assert!(uuids.insert(uuid), "UUID should be unique");
- }
-
- assert_eq!(uuids.len(), 1000);
- }
-
- #[tokio::test]
- async fn test_offset_calculation() {
- // Test offset calculations with different batch sizes
- let test_cases = vec![
- (10, 3, vec![0, 3, 6, 9]), // 10 items, batch size 3
- (5, 2, vec![0, 2, 4]), // 5 items, batch size 2
- (7, 5, vec![0, 5]), // 7 items, batch size 5
- ];
-
- for (total_items, batch_size, expected_offsets) in test_cases {
- let mut offsets = Vec::new();
- let mut offset = 0i64;
-
- while offset < total_items {
- offsets.push(offset);
- offset += batch_size;
- }
-
- assert_eq!(
- offsets, expected_offsets,
- "Offsets should match for total={}, batch_size={}",
- total_items, batch_size
- );
- }
- }
-
- #[tokio::test]
- async fn test_thread_limiting_edge_cases() {
- // Test various edge cases for thread limiting
- struct TestCase {
- total_threads: i64,
- limit: Option<i64>,
- batch_size: i64,
- expected_processed: i64,
- expected_batches: usize,
- }
-
- let test_cases = vec![
- TestCase {
- total_threads: 10,
- limit: Some(5),
- batch_size: 2,
- expected_processed: 5,
- expected_batches: 3, // 2, 2, 1
- },
- TestCase {
- total_threads: 3,
- limit: Some(10),
- batch_size: 2,
- expected_processed: 3,
- expected_batches: 2, // 2, 1
- },
- TestCase {
- total_threads: 5,
- limit: None,
- batch_size: 3,
- expected_processed: 5,
- expected_batches: 2, // 3, 2
- },
- ];
-
- for case in test_cases {
- let mut processed = 0i64;
- let mut offset = 0i64;
- let mut batch_count = 0;
-
- while processed < case.total_threads
- && case.limit.map_or(true, |limit| processed < limit)
- {
- let start = offset;
- let end = (offset + case.batch_size).min(case.total_threads);
- let threads_in_batch = end - start;
-
- if threads_in_batch == 0 {
- break;
- }
-
- let remaining = case.limit.map_or(threads_in_batch, |limit| {
- (limit - processed).min(threads_in_batch)
- });
-
- processed += remaining;
- batch_count += 1;
- offset += case.batch_size;
-
- if case.limit.map_or(false, |limit| processed >= limit) {
- break;
- }
- }
-
- assert_eq!(
- processed, case.expected_processed,
- "Processed count mismatch for case: total={}, limit={:?}, batch_size={}",
- case.total_threads, case.limit, case.batch_size
- );
- assert_eq!(
- batch_count, case.expected_batches,
- "Batch count mismatch for case: total={}, limit={:?}, batch_size={}",
- case.total_threads, case.limit, case.batch_size
- );
- }
- }
-
- #[test]
- fn test_email_info_pattern_matching() {
- // Test the AsBackfill trait implementation
- let payload = BackfillBatchPayload {
- thread_ids: vec!["thread1".to_string()],
- batch_size: 1,
- is_complete: true,
- user_emails: vec!["[email protected]".to_string()],
- job_id: "job1".to_string(),
- batch_id: "batch1".to_string(),
- };
-
- let email_info = EmailInfo::Backfill(payload);
- let extracted = email_info.as_backfill();
-
- assert!(extracted.is_some());
- assert_eq!(extracted.unwrap().thread_ids.len(), 1);
- assert_eq!(extracted.unwrap().job_id, "job1");
- }
-}
diff --git a/rust/cloud-storage/email_service/src/util/backfill/mod.rs b/rust/cloud-storage/email_service/src/util/backfill/mod.rs
deleted file mode 100644
index 0c59012b04..0000000000
--- a/rust/cloud-storage/email_service/src/util/backfill/mod.rs
+++ /dev/null
@@ -1 +0,0 @@
-pub mod backfill_insights;
diff --git a/rust/cloud-storage/email_service/src/util/mod.rs b/rust/cloud-storage/email_service/src/util/mod.rs
index 5cb8f6e08c..3e3aff2840 100644
--- a/rust/cloud-storage/email_service/src/util/mod.rs
+++ b/rust/cloud-storage/email_service/src/util/mod.rs
@@ -1,4 +1,3 @@
-pub mod backfill;
pub mod gmail;
pub mod process_pre_insert;
pub mod redis;
diff --git a/rust/cloud-storage/email_service_client/src/backfill.rs b/rust/cloud-storage/email_service_client/src/backfill.rs
deleted file mode 100644
index 4631433eda..0000000000
--- a/rust/cloud-storage/email_service_client/src/backfill.rs
+++ /dev/null
@@ -1,82 +0,0 @@
-use super::EmailServiceClient;
-use anyhow::Result;
-use model::insight_context::email_insights::BackfillEmailInsightsFilter;
-use serde::{Deserialize, Serialize};
-
-#[derive(Debug, Deserialize, Serialize)]
-pub struct BackfillJobResponse {
- // One job id per user backfill job
- pub job_ids: Vec<String>,
-}
-
-impl EmailServiceClient {
- /// backfills insights for emails according to the filter (if any)
- /// Returns the job IDs that can be used to track progress (one per user)
- #[tracing::instrument(skip(self))]
- pub async fn backfill_insights(
- &self,
- input: BackfillEmailInsightsFilter,
- ) -> Result<Vec<String>> {
- let res = self
- .client
- .post(format!("{}/internal/backfill/insights", self.url))
- .json(&input)
- .send()
- .await?;
-
- let status_code = res.status();
-
- if status_code != reqwest::StatusCode::OK {
- let body: String = res.text().await?;
- tracing::error!(
- body=%body,
- status=%status_code,
- "unexpected response from email service"
- );
- return Err(anyhow::anyhow!(body));
- }
-
- let response: BackfillJobResponse = res.json().await?;
- tracing::info!(job_ids=?response.job_ids, "Started insights backfill jobs");
-
- Ok(response.job_ids)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- /// Example usage of the simplified backfill client
- #[tokio::test]
- #[ignore] // Requires running email service
- async fn example_backfill_simple() {
- let client =
- EmailServiceClient::new("http://localhost:3000".to_string(), "test_key".to_string());
-
- // Start a backfill job
- let filter = BackfillEmailInsightsFilter {
- user_ids: Some(vec!["user123".to_string()]),
- user_thread_limit: Some(100),
- };
-
- let job_ids = client.backfill_insights(filter).await.unwrap();
- println!("Started backfill jobs: {:?}", job_ids);
-
- // Job tracking is now handled by the insight service
- // Query the database directly to check job status
- }
-
- #[test]
- fn test_response_serialization() {
- // Test that our response types can be serialized/deserialized
- let response = BackfillJobResponse {
- job_ids: vec!["test-123".to_string(), "test-456".to_string()],
- };
-
- let json = serde_json::to_string(&response).unwrap();
- let deserialized: BackfillJobResponse = serde_json::from_str(&json).unwrap();
-
- assert_eq!(response.job_ids, deserialized.job_ids);
- }
-}
diff --git a/rust/cloud-storage/email_service_client/src/lib.rs b/rust/cloud-storage/email_service_client/src/lib.rs
index fbf3e6f84d..48a744e9f1 100644
--- a/rust/cloud-storage/email_service_client/src/lib.rs
+++ b/rust/cloud-storage/email_service_client/src/lib.rs
@@ -1,6 +1,5 @@
use constants::INTERNAL_AUTH_HEADER_KEY;
-pub mod backfill;
pub(crate) mod constants;
mod external;
diff --git a/rust/cloud-storage/insight_service/.gitignore b/rust/cloud-storage/insight_service/.gitignore
deleted file mode 100644
index cf31734591..0000000000
--- a/rust/cloud-storage/insight_service/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-.env
-migrations/**/*
diff --git a/rust/cloud-storage/insight_service/Cargo.toml b/rust/cloud-storage/insight_service/Cargo.toml
deleted file mode 100644
index 0ab86326dc..0000000000
--- a/rust/cloud-storage/insight_service/Cargo.toml
+++ /dev/null
@@ -1,50 +0,0 @@
-[package]
-edition = "2024"
-name = "insight_service"
-publish = false
-version = "0.1.0"
-
-[dependencies]
-ai = { path = "../ai" }
-ai_format = { path = "../ai_format" }
-anyhow = { workspace = true }
-async-stream = { workspace = true }
-async-trait.workspace = true
-aws-config.workspace = true
-aws-sdk-secretsmanager.workspace = true
-aws-sdk-sqs.workspace = true
-axum.workspace = true
-chrono = { workspace = true }
-clap.workspace = true
-document_cognition_service_client = { path = "../document_cognition_service_client" }
-document_storage_service_client = { path = "../document_storage_service_client" }
-email_service_client = { path = "../email_service_client" }
-futures.workspace = true
-lexical_client = { path = "../lexical_client" }
-macro_auth = { path = "../macro_auth" }
-macro_cors = { path = "../macro_cors" }
-macro_db_client = { path = "../macro_db_client" }
-macro_entrypoint = { path = "../macro_entrypoint" }
-macro_env = { path = "../macro_env" }
-macro_middleware = { path = "../macro_middleware" }
-model = { path = "../model" }
-models_dcs = { path = "../models_dcs" }
-models_email = { path = "../models_email" }
-reqwest = { workspace = true }
-schemars = { workspace = true }
-scribe = { path = "../scribe", features = ["dcs", "document", "email"] }
-secretsmanager_client = { path = "../secretsmanager_client" }
-serde.workspace = true
-serde_json.workspace = true
-sha2 = { workspace = true }
-sqlx = { workspace = true }
-sqs_worker = { path = "../sqs_worker" }
-strum = { workspace = true }
-strum_macros = { workspace = true }
-sync_service_client = { path = "../sync_service_client" }
-tokio = { workspace = true }
-tower-http.workspace = true
-tracing = { workspace = true }
-utoipa = { workspace = true }
-utoipa-swagger-ui = { workspace = true, features = ["axum"] }
-uuid = { workspace = true }
diff --git a/rust/cloud-storage/insight_service/Justfile b/rust/cloud-storage/insight_service/Justfile
deleted file mode 100644
index 890cb507f0..0000000000
--- a/rust/cloud-storage/insight_service/Justfile
+++ /dev/null
@@ -1,35 +0,0 @@
-mod ci '../ci.just'
-
-deploy-dev:
- just ci::deploy-dev insight-service
-
-run *args:
- cargo run --features macro_middleware/local_auth {{args}}
-
-api *args:
- cargo run --bin insight_service_api {{args}}
-
-create-localstack:
- docker run -d --name localstack -p 4566:4566 -e SERVICES=sqs localstack/localstack
-
-create-queue:
- AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs create-queue \
- --queue-name insight-context-queue.fifo \
- --attributes FifoQueue=true
-
-purge-queue:
- AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs purge-queue \
- --queue-url http://localhost:4566/000000000000/insight-context-queue.fifo
-
-send-chat-context JSON_FILE:
- AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs send-message \
- --queue-url http://localhost:4566/000000000000/insight-context-queue.fifo \
- --message-body file://{{JSON_FILE}} \
- --message-group-id chat \
- --message-deduplication-id $(uuidgen)
-
-prepare-test:
- rm -rf ./migrations && cp -r ../macro_db_client/migrations ./
-
-list-queues:
- awslocal sqs list-queues
diff --git a/rust/cloud-storage/insight_service/fixtures/chats.sql b/rust/cloud-storage/insight_service/fixtures/chats.sql
deleted file mode 100644
index a2704c49d2..0000000000
--- a/rust/cloud-storage/insight_service/fixtures/chats.sql
+++ /dev/null
@@ -1,44 +0,0 @@
-INSERT INTO public."Chat" ("id","name","userId", "createdAt", "updatedAt")
-(SELECT 'c1', 'test-chat', 'macro|[email protected]', '2019-10-16 01:01:00', '2019-10-16 01:01:00');
-
-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")
-(SELECT 'sp-chat1', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');
-
-INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")
-(SELECT 'c1', 'sp-chat1');
-
-INSERT INTO public."Chat" ("id","name","userId", "createdAt", "updatedAt")
-(SELECT 'c2', 'test-chat', 'macro|[email protected]', '2019-10-16 01:01:00', '2019-10-16 01:01:00');
-
-INSERT INTO public."SharePermission" ("id", "isPublic", "createdAt", "updatedAt")
-(SELECT 'sp-chat2', false, '2019-10-16 00:00:00', '2019-10-16 00:00:00');
-
-INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")
-(SELECT 'c2', 'sp-chat2');
-
-INSERT INTO public."Chat" ("id","name","userId", "createdAt", "updatedAt")
-(SELECT 'c3', 'test-chat', 'macro|[email protected]', '2019-10-16 01:01:00', '2019-10-16 01:01:00');
-
-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")
-(SELECT 'sp-chat3', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');
-
-INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")
-(SELECT 'c3', 'sp-chat3');
-
-INSERT INTO public."Chat" ("id","name","userId", "createdAt", "updatedAt")
-(SELECT 'c4', 'test-chat', 'macro|[email protected]', '2019-10-16 01:01:00','2019-10-16 01:01:00' );
-
-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")
-(SELECT 'sp-chat4', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');
-
-INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")
-(SELECT 'c4', 'sp-chat4');
-
-INSERT INTO public."Chat" ("id","name","userId", "createdAt", "updatedAt")
-(SELECT 'c5', 'test-chat', 'macro|[email protected]', '2019-10-16 01:01:00', '2019-10-16 01:01:00');
-
-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")
-(SELECT 'sp-chat5', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');
-
-INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")
-(SELECT 'c5', 'sp-chat5');
diff --git a/rust/cloud-storage/insight_service/fixtures/users.sql b/rust/cloud-storage/insight_service/fixtures/users.sql
deleted file mode 100644
index 0da21d9b17..0000000000
--- a/rust/cloud-storage/insight_service/fixtures/users.sql
+++ /dev/null
@@ -1,11 +0,0 @@
-INSERT INTO public."Organization" ("id","name")
-(SELECT 1, 'organization-one');
-
-INSERT INTO public."User" ("id","email","stripeCustomerId")
-(SELECT 'macro|[email protected]', '[email protected]','stripe_id');
-INSERT INTO public."User" ("id","email","stripeCustomerId", "hasOnboardingDocuments")
-(SELECT 'macro|[email protected]', '[email protected]','stripe_id2', TRUE);
-INSERT INTO public."User" ("id","email","stripeCustomerId", "organizationId")
-(SELECT 'macro|[email protected]', '[email protected]','stripe_id3', 1);
-INSERT INTO public."User" ("id","email","stripeCustomerId")
-(SELECT 'macro|[email protected]', '[email protected]','stripe_id5');
diff --git a/rust/cloud-storage/insight_service/src/api/api_context.rs b/rust/cloud-storage/insight_service/src/api/api_context.rs
deleted file mode 100644
index fcb848014e..0000000000
--- a/rust/cloud-storage/insight_service/src/api/api_context.rs
+++ /dev/null
@@ -1,28 +0,0 @@
-use crate::config::Config;
-use anyhow::Context;
-use axum::extract::FromRef;
-use macro_auth::middleware::decode_jwt::JwtValidationArgs;
-use sqlx::{PgPool, Pool};
-
-#[derive(Clone, FromRef)]
-pub struct ApiContext {
- pub macro_db: PgPool,
- jwt_args: JwtValidationArgs,
- config: Config,
-}
-
-impl ApiContext {
- pub async fn connect_from_config(
- config: Config,
- jwt_args: JwtValidationArgs,
- ) -> Result<ApiContext, anyhow::Error> {
- let macro_db_client = Pool::connect(&config.macro_db_url)
- .await
- .context("MACRODB Connection failed")?;
- Ok(ApiContext {
- macro_db: macro_db_client,
- jwt_args,
- config,
- })
- }
-}
diff --git a/rust/cloud-storage/insight_service/src/api/mod.rs b/rust/cloud-storage/insight_service/src/api/mod.rs
deleted file mode 100644
index 29973016c7..0000000000
--- a/rust/cloud-storage/insight_service/src/api/mod.rs
+++ /dev/null
@@ -1,11 +0,0 @@
-pub(in crate::api) mod api_context;
-pub mod swagger;
-pub(in crate::api) mod user_insight;
-
-pub use api_context::*;
-
-use axum::Router;
-
-pub fn router() -> Router<ApiContext> {
- Router::new().nest("/user_insight", user_insight::router())
-}
diff --git a/rust/cloud-storage/insight_service/src/api/swagger.rs b/rust/cloud-storage/insight_service/src/api/swagger.rs
deleted file mode 100644
index b05f1e5cec..0000000000
--- a/rust/cloud-storage/insight_service/src/api/swagger.rs
+++ /dev/null
@@ -1,25 +0,0 @@
-use super::user_insight;
-use super::user_insight::{
- CreateInsightsRequest, GetUserInsightsParams, GetUserInsightsResponse, IdList,
- UpdateInsightRequest,
-};
-
-use model::insight_context::UserInsightRecord;
-
-use utoipa::OpenApi;
-
-#[derive(OpenApi)]
-#[openapi(
- info(terms_of_service = "https://macro.com/terms",),
- paths(
- user_insight::handle_create_insights,
- user_insight::handle_delete_user_insights,
- user_insight::handle_get_user_insights,
- user_insight::handle_update_user_insight
- ),
- components(schemas(GetUserInsightsParams, UpdateInsightRequest, UserInsightRecord, GetUserInsightsResponse, IdList, CreateInsightsRequest)),
- tags(
- (name = "macro insight service", description = "Insight Service")
- )
-)]
-pub struct ApiDoc;
diff --git a/rust/cloud-storage/insight_service/src/api/user_insight.rs b/rust/cloud-storage/insight_service/src/api/user_insight.rs
deleted file mode 100644
index 466b3dda80..0000000000
--- a/rust/cloud-storage/insight_service/src/api/user_insight.rs
+++ /dev/null
@@ -1,418 +0,0 @@
-use super::api_context::ApiContext;
-use anyhow::Context;
-use axum::{
- Extension, Router,
- extract::{Json, Query, State},
- http::StatusCode,
- response::{IntoResponse, Response},
- routing::{delete, get, patch, post},
-};
-
-use macro_db_client::insight::user as user_insight;
-use macro_db_client::insight::user::BatchError;
-use model::insight_context::UserInsightRecord;
-use model::user::UserContext;
-use serde::{Deserialize, Serialize};
-use utoipa::ToSchema;
-
-#[derive(Debug, Serialize, Deserialize, Clone, ToSchema, utoipa::IntoParams)]
-pub struct GetUserInsightsParams {
- pub limit: Option<u32>,
- pub offset: Option<u32>,
- pub generated: Option<bool>,
-}
-
-#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
-pub struct GetUserInsightsResponse {
- pub insights: Vec<UserInsightRecord>,
- pub total: i64,
-}
-
-#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
-pub struct InsightProcessingResponse {
- pub status: String,
- pub message: String,
- pub estimated_wait_minutes: Option<u32>,
-}
-
-/// Helper function to handle immediate processing for users without cached batches
-/// or when cached batches need to be regenerated
-async fn process_user_immediate_and_respond(
- ctx: &ApiContext,
- user_id: &str,
- params: &GetUserInsightsParams,
-) -> Response {
- use crate::insight::batch_processor::InsightBatchProcessor;
- let processor = InsightBatchProcessor::new(ctx.macro_db.clone());
-
- match processor.process_user_immediate(user_id).await {
- Ok(_) => {
- // Processing succeeded, now try to get the batch
- tracing::debug!(
- "Successfully processed batch for user {}, fetching results",
- user_id
- );
-
- match user_insight::get_user_insight_batch(&ctx.macro_db, user_id).await {
- Ok(Some(batch)) => {
- match user_insight::get_insights_by_batch(
- &ctx.macro_db,
- user_id,
- &batch.insight_ids.unwrap_or_default(),
- )
- .await
- {
- Ok(insights) => {
- let offset = params.offset.unwrap_or(0) as usize;
- let limit = params.limit.unwrap_or(30) as usize;
- let total = insights.len() as i64;
- let paginated_insights: Vec<_> =
- insights.into_iter().skip(offset).take(limit).collect();
-
- Json(GetUserInsightsResponse {
- insights: paginated_insights,
- total,
- })
- .into_response()
- }
- Err(BatchError::IncompleteInsights { .. }) => {
- // Even the newly created batch is incomplete - delete it and return empty
- tracing::warn!(
- "Newly created batch is also incomplete for user {}, deleting and returning empty",
- user_id
- );
-
- if let Err(delete_err) =
- user_insight::delete_user_insight_batch(&ctx.macro_db, user_id)
- .await
- {
- tracing::error!(error=?delete_err, "Failed to delete newly created corrupted batch for user {}", user_id);
- }
-
- Json(GetUserInsightsResponse {
- insights: vec![],
- total: 0,
- })
- .into_response()
- }
- Err(e) => {
- tracing::error!(error=?e, "Failed to fetch insights from newly created batch");
- StatusCode::INTERNAL_SERVER_ERROR.into_response()
- }
- }
- }
- Ok(None) => {
- // Still no batch after processing - user probably has no insights
- Json(GetUserInsightsResponse {
- insights: vec![],
- total: 0,
- })
- .into_response()
- }
- Err(e) => {
- tracing::error!(error=?e, "Failed to fetch newly created batch");
- StatusCode::INTERNAL_SERVER_ERROR.into_response()
- }
- }
- }
- Err(e) => {
- tracing::error!(error=?e, "Failed to process user batch immediately");
- // Return 202 as fallback - batch processing failed but we can retry later
- (
- StatusCode::ACCEPTED,
- Json(InsightProcessingResponse {
- status: "processing".to_string(),
- message:
- "Your insights are being generated. Please check back in a few minutes."
- .to_string(),
- estimated_wait_minutes: Some(5),
- }),
- )
- .into_response()
- }
- }
-}
-
-#[utoipa::path(
- get,
- tag = "user_insight",
- description = "get user insights",
- path = "/user_insight",
- params(GetUserInsightsParams),
- responses(
- (status = 200, body=GetUserInsightsResponse),
- (status = 202, body=InsightProcessingResponse),
- (status = 500, body=String),
- (status = 401, body=String)
- )
-)]
-#[tracing::instrument(skip(ctx, user_ctx))]
-pub async fn handle_get_user_insights(
- State(ctx): State<ApiContext>,
- user_ctx: Extension<UserContext>,
- params: Query<GetUserInsightsParams>,
-) -> impl IntoResponse {
- // For non-generated insights (user memories), use the original logic
- if params.generated == Some(false) {
- return handle_get_user_memories(&ctx, user_ctx, params).await;
- }
-
- // For generated insights, use cached batches
- match user_insight::get_user_insight_batch(&ctx.macro_db, &user_ctx.user_id).await {
- Ok(Some(batch)) => {
- // We have a valid cached batch
- tracing::debug!("Found cached insight batch for user {}", user_ctx.user_id);
-
- match user_insight::get_insights_by_batch(
- &ctx.macro_db,
- &user_ctx.user_id,
- &batch.insight_ids.unwrap_or_default(),
- )
- .await
- {
- Ok(insights) => {
- // Apply offset and limit to cached results
- let offset = params.offset.unwrap_or(0) as usize;
- let limit = params.limit.unwrap_or(30) as usize;
- let total = insights.len() as i64;
- let paginated_insights: Vec<_> =
- insights.into_iter().skip(offset).take(limit).collect();
-
- Json(GetUserInsightsResponse {
- insights: paginated_insights,
- total,
- })
- .into_response()
- }
- Err(BatchError::IncompleteInsights { .. }) => {
- // Some insights were deleted - remove the corrupted batch and regenerate
- tracing::warn!(
- "Incomplete insights detected for user {}, removing batch and regenerating",
- user_ctx.user_id
- );
-
- if let Err(delete_err) =
- user_insight::delete_user_insight_batch(&ctx.macro_db, &user_ctx.user_id)
- .await
- {
- tracing::error!(error=?delete_err, "Failed to delete corrupted batch for user {}", user_ctx.user_id);
- }
-
- // Fall back to the same logic as Ok(None) - trigger immediate processing
- tracing::info!(
- "Triggering immediate processing for user {} after batch deletion",
- user_ctx.user_id
- );
-
- process_user_immediate_and_respond(&ctx, &user_ctx.user_id, &params).await
- }
- Err(e) => {
- tracing::error!(error=?e, "Failed to fetch insights from batch");
- StatusCode::INTERNAL_SERVER_ERROR.into_response()
- }
- }
- }
- Ok(None) => {
- // No cached batch exists - trigger immediate processing
- tracing::info!(
- "No cached batch found for user {}, triggering immediate processing",
- user_ctx.user_id
- );
-
- process_user_immediate_and_respond(&ctx, &user_ctx.user_id, &params).await
- }
- Err(e) => {
- tracing::error!(error=?e, "Failed to check for cached batch");
- StatusCode::INTERNAL_SERVER_ERROR.into_response()
- }
- }
-}
-
-// Handle user memories (non-generated insights) with original logic
-async fn handle_get_user_memories(
- ctx: &ApiContext,
- user_ctx: Extension<UserContext>,
- params: Query<GetUserInsightsParams>,
-) -> Response {
- let insights = user_insight::get_user_insights(
- &ctx.macro_db,
- &user_ctx.user_id,
- params.generated,
- params.limit.unwrap_or(30),
- params.offset.unwrap_or(0),
- )
- .await
- .context("failed to retrieve insights")
- .inspect_err(|e| {
- tracing::error!(error=?e, "Failed to retrieve insights");
- });
-
- if insights.is_err() {
- return StatusCode::INTERNAL_SERVER_ERROR.into_response();
- }
-
- let insights = insights.unwrap();
-
- let count = user_insight::count_total(&ctx.macro_db, params.generated, &user_ctx.user_id)
- .await
- .context("failed to get total")
- .inspect_err(|e| {
- tracing::error!(error=?e, "failed to get total");
- });
-
- if count.is_err() {
- return StatusCode::INTERNAL_SERVER_ERROR.into_response();
- }
- let count = count.unwrap();
-
- Json(GetUserInsightsResponse {
- insights,
- total: count,
- })
- .into_response()
-}
-
-#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
-pub struct UpdateInsightRequest {
- pub insight_id: String,
- pub content: String,
-}
-
-#[utoipa::path(
- patch,
- tag = "user_insight",
- description = "update_user_insight",
- path = "/user_insight",
- request_body=UpdateInsightRequest,
- responses(
- (status = 200, body=UserInsightRecord),
- (status = 500, body=String),
- (status = 404, body=String),
- (status = 401, body=String),
- )
-)]
-#[tracing::instrument(skip(ctx, user_ctx))]
-pub async fn handle_update_user_insight(
- State(ctx): State<ApiContext>,
- user_ctx: Extension<UserContext>,
- Json(UpdateInsightRequest {
- insight_id,
- content,
- }): Json<UpdateInsightRequest>,
-) -> Result<Response, Response> {
- let mut insight = user_insight::get_insight(&ctx.macro_db, &insight_id, &user_ctx.user_id)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "error fetching insight");
- StatusCode::INTERNAL_SERVER_ERROR.into_response()
- })?
- .ok_or(StatusCode::NOT_FOUND.into_response())?;
-
- insight.content = content;
- insight.generated = false;
-
- let updated =
- user_insight::update_insights(&ctx.macro_db, &user_ctx.user_id, vec![insight.clone()])
- .await
- .map_err(|e| {
- tracing::error!(erro=?e, "error updating insight");
- StatusCode::INTERNAL_SERVER_ERROR.into_response()
- })?
- .first()
- .map(String::to_owned)
- .ok_or(StatusCode::NOT_FOUND.into_response())?;
-
- if updated != insight_id {
- tracing::error!("How did we get here. (user insight update)(turn the server off)");
- }
-
- Ok(Json(insight).into_response())
-}
-
-#[derive(Clone, Debug, ToSchema, Serialize, Deserialize)]
-pub struct IdList {
- pub ids: Vec<String>,
-}
-
-#[
- utoipa::path(
- delete,
- tag = "user_insight",
- description = "update_user_insight",
- path = "/user_insight",
- request_body=IdList,
- responses(
- (status = 200, body=IdList),
- (status = 500, body=String),
- (status = 404, body=String),
- (status = 401, body=String),
- )
- )
-]
-#[tracing::instrument(skip(ctx, user_ctx))]
-pub async fn handle_delete_user_insights(
- State(ctx): State<ApiContext>,
- user_ctx: Extension<UserContext>,
- ids: Json<IdList>,
-) -> Result<Response, Response> {
- let deleted = user_insight::delete_user_insights(&ctx.macro_db, &ids.ids, &user_ctx.user_id)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "error deleting insights");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- "Internal server serror".to_string(),
- )
- .into_response()
- })?;
- Ok((StatusCode::OK, Json(IdList { ids: deleted })).into_response())
-}
-
-#[derive(Clone, Debug, ToSchema, Deserialize, Serialize)]
-pub struct CreateInsightsRequest {
- pub insights: Vec<String>,
-}
-
-#[
- utoipa::path(
- post,
- tag = "user_insight",
- description = "update_user_insight",
- path = "/user_insight",
- request_body=CreateInsightsRequest,
- responses(
- (status = 200, body=IdList),
- (status = 500, body=String),
- (status = 404, body=String),
- (status = 401, body=String),
- )
- )
-]
-#[tracing::instrument(skip(ctx, user_ctx))]
-pub async fn handle_create_insights(
- State(ctx): State<ApiContext>,
- user_ctx: Extension<UserContext>,
- insights: Json<CreateInsightsRequest>,
-) -> Result<Response, Response> {
- let insights = insights
- .insights
- .iter()
- .map(|content| UserInsightRecord::user_created(content.to_owned(), &user_ctx.user_id))
- .collect::<Vec<_>>();
-
- let created = user_insight::create_insights(&ctx.macro_db, &insights, &user_ctx.user_id)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "failed to create insights");
- StatusCode::INTERNAL_SERVER_ERROR.into_response()
- })?;
- Ok(Json(IdList { ids: created }).into_response())
-}
-
-pub fn router() -> Router<ApiContext> {
- Router::new()
- .route("/", get(handle_get_user_insights))
- .route("/", post(handle_create_insights))
- .route("/", patch(handle_update_user_insight))
- .route("/", delete(handle_delete_user_insights))
-}
diff --git a/rust/cloud-storage/insight_service/src/config.rs b/rust/cloud-storage/insight_service/src/config.rs
deleted file mode 100644
index df6f0854c5..0000000000
--- a/rust/cloud-storage/insight_service/src/config.rs
+++ /dev/null
@@ -1,87 +0,0 @@
-use anyhow::Context;
-pub use macro_env::Environment;
-use std::env::var;
-#[derive(Debug, Clone)]
-pub struct Config {
- /// Current environment
- pub environment: Environment,
- /// SQS Url
- pub queue_url: String,
- /// max messages per poll
- pub queue_max_messages: u32,
- /// queue wait time
- pub queue_wait_time_seconds: u32,
- /// macro_db_url
- pub macro_db_url: String,
- /// api port
- pub port: u32,
- pub lexical_service_url: String,
- pub internal_auth_key: String,
- pub document_storage_service_url: String,
- pub sync_service_url: String,
- pub sync_service_auth_key: String,
- pub email_service_url: String,
- pub document_cognition_service_url: String,
-}
-
-impl Config {
- pub fn from_env() -> Result<Self, anyhow::Error> {
- let environment = Environment::new_or_prod();
-
- let queue_url = var("INSIGHT_CONTEXT_QUEUE").context("INSIGHT_CONTEXT_QUEUE")?;
-
- let queue_max_messages = var("INSIGHT_CONTEXT_QUEUE_MAX_MESSAGES")
- .unwrap_or("5".to_string())
- .parse::<u32>()
- .context("INSIGHT_CONTEXT_QUEUE_MAX_MESSAGES")?;
-
- let queue_wait_time_seconds = var("INSIGHT_CONTEXT_QUEUE_WAIT_TIME_SECONDS")
- .unwrap_or("5".to_string())
- .parse::<u32>()
- .unwrap();
-
- let macro_db_url = var("MACRODB_URL").context("MACRODB_URL")?;
-
- let port = var("PORT")
- .unwrap_or("8080".to_string())
- .parse::<u32>()
- .expect("PORT to be a number");
-
- let lexical_service_url =
- var("LEXICAL_SERVICE_URL").expect("LEXICAL_SERVICE_URL to be provied");
-
- let internal_auth_key = std::env::var("SERVICE_INTERNAL_AUTH_KEY")
- .expect("SERVICE_INTERNAL_AUTH_KEY environment variable not set");
-
- let document_storage_service_url = std::env::var("DOCUMENT_STORAGE_SERVICE_URL")
- .expect("DOCUMENT_STORAGE_SERVICE_URL must be provided");
-
- let sync_service_url =
- std::env::var("SYNC_SERVICE_URL").expect("SYNC_SERVICE_URL must be provided");
-
- let sync_service_auth_key =
- std::env::var("SYNC_SERVICE_AUTH_KEY").expect("SYNC_SERVICE_AUTH_KEY must be provided");
-
- let email_service_url =
- std::env::var("EMAIL_SERVICE_URL").expect("EMAIL_SERVICE_URL must be provided");
-
- let document_cognition_service_url = std::env::var("DOCUMENT_COGNITION_SERVICE_URL")
- .expect("DOCUMENT_COGNITION_SERVICE_URL must be provided");
-
- Ok(Config {
- environment,
- queue_url,
- queue_wait_time_seconds,
- queue_max_messages,
- macro_db_url,
- port,
- lexical_service_url,
- internal_auth_key,
- document_storage_service_url,
- sync_service_url,
- sync_service_auth_key,
- email_service_url,
- document_cognition_service_url,
- })
- }
-}
diff --git a/rust/cloud-storage/insight_service/src/context.rs b/rust/cloud-storage/insight_service/src/context.rs
deleted file mode 100644
index 110a321048..0000000000
--- a/rust/cloud-storage/insight_service/src/context.rs
+++ /dev/null
@@ -1,65 +0,0 @@
-use crate::config::Config;
-use anyhow::Context;
-use document_cognition_service_client::DocumentCognitionServiceClient;
-use document_storage_service_client::DocumentStorageServiceClient;
-use email_service_client::EmailServiceClient;
-use lexical_client::LexicalClient;
-use scribe::{ScribeClient, dcs::DcsClient, document::DocumentClient, email::EmailClient};
-use sqlx::{PgPool, Pool, Postgres};
-use std::sync::Arc;
-use sync_service_client::SyncServiceClient;
-pub type InsightScribe = ScribeClient<DocumentClient, (), DcsClient, EmailClient, ()>;
-// Extend with channels, sync, etc
-pub struct ServiceContext {
- pub macro_db: Pool<Postgres>,
- pub content_client: InsightScribe,
-}
-
-impl ServiceContext {
- pub async fn try_from_config(config: &Config) -> Result<Self, anyhow::Error> {
- let macro_db = PgPool::connect(config.macro_db_url.as_str())
- .await
- .context("connect to MacroDB")?;
-
- let dss_client = DocumentStorageServiceClient::new(
- config.internal_auth_key.clone(),
- config.document_storage_service_url.clone(),
- );
-
- let sync_service_client = SyncServiceClient::new(
- config.sync_service_auth_key.clone(),
- config.sync_service_url.clone(),
- );
-
- let email_service_client = EmailServiceClient::new(
- config.internal_auth_key.clone(),
- config.email_service_url.clone(),
- );
-
- let dcs_client = DocumentCognitionServiceClient::new(
- config.internal_auth_key.clone(),
- config.document_cognition_service_url.clone(),
- );
-
- let lexical_client = LexicalClient::new(
- config.sync_service_auth_key.clone(),
- config.lexical_service_url.clone(),
- );
-
- let content_client = ScribeClient::new()
- .with_dcs_client(dcs_client)
- .with_document_client(
- DocumentClient::builder()
- .with_dss_client(Arc::new(dss_client))
- .with_lexical_client(Arc::new(lexical_client))
- .with_sync_service_client(Arc::new(sync_service_client))
- .build(),
- )
- .with_email_client(email_service_client);
-
- Ok(Self {
- macro_db,
- content_client,
- })
- }
-}
diff --git a/rust/cloud-storage/insight_service/src/example/shape_check.rs b/rust/cloud-storage/insight_service/src/example/shape_check.rs
deleted file mode 100644
index 487f789a12..0000000000
--- a/rust/cloud-storage/insight_service/src/example/shape_check.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-use crate::insight::consumer::generator::generate_insights;
-use chrono::Utc;
-use macro_entrypoint::MacroEntrypoint;
-use model::insight_context::chat::{ChatContext, Conversation, UserMessage};
-
-const MESSAGES: &str = include_str!("../../../test/chat_log.txt");
-
-fn make_context() -> ChatContext {
- let my_messages = MESSAGES
- .lines()
- .map(|m| UserMessage {
- attachment_insights: vec![],
- date: Utc::now(),
- content: m.to_string(),
- })
- .collect::<Vec<_>>();
-
- ChatContext(vec![Conversation {
- conversation_title: "test conversation".to_string(),
- messages: my_messages,
- }])
-}
-
-#[tokio::main]
-async fn main() -> Result<(), anyhow::Error> {
- MacroEntrypoint::default().init();
-
- let mock_chat_context = make_context();
- let log_description = "ai chat messages sent by a user";
- let new_insights = generate_insights(
- "chat",
- log_description,
- mock_chat_context.into(),
- &[],
- )
- .await
- .expect("no error");
- assert!(!new_insights.is_empty(), "not empty");
- panic!("INSPECT THE GENERATED INSPECT\n{:#?}", new_insights);
-}
diff --git a/rust/cloud-storage/insight_service/src/insight/batch_processor.rs b/rust/cloud-storage/insight_service/src/insight/batch_processor.rs
deleted file mode 100644
index 81832adaef..0000000000
--- a/rust/cloud-storage/insight_service/src/insight/batch_processor.rs
+++ /dev/null
@@ -1,275 +0,0 @@
-use crate::insight::smart_ranking::{RankingContext, select_insights_for_llm_context};
-use anyhow::{Context, Result};
-use chrono::{Duration, Utc};
-use macro_db_client::insight::user as user_insight;
-use sqlx::PgPool;
-
-/// Default target tokens for insight batch
-const DEFAULT_TARGET_TOKENS: usize = 2048;
-
-/// Default batch expiration duration (7 days)
-const DEFAULT_BATCH_EXPIRATION_DAYS: i64 = 7;
-
-/// Get target tokens from environment or use default
-fn get_target_tokens() -> usize {
- std::env::var("INSIGHT_BATCH_TARGET_TOKENS")
- .ok()
- .and_then(|s| s.parse().ok())
- .unwrap_or(DEFAULT_TARGET_TOKENS)
-}
-
-/// Get batch expiration days from environment or use default
-fn get_batch_expiration_days() -> i64 {
- std::env::var("INSIGHT_BATCH_EXPIRATION_DAYS")
- .ok()
- .and_then(|s| s.parse().ok())
- .unwrap_or(DEFAULT_BATCH_EXPIRATION_DAYS)
-}
-
-/// Default maximum insights to fetch per user
-const DEFAULT_MAX_INSIGHTS: i64 = 1000;
-
-/// Get the maximum insights limit from environment or use default
-fn get_max_insights_limit() -> i64 {
- std::env::var("INSIGHT_BATCH_MAX_INSIGHTS")
- .ok()
- .and_then(|s| s.parse().ok())
- .unwrap_or(DEFAULT_MAX_INSIGHTS)
-}
-
-/// Daily job to generate insight batches for users
-pub struct InsightBatchProcessor {
- macro_db: PgPool,
-}
-
-impl InsightBatchProcessor {
- pub fn new(macro_db: PgPool) -> Self {
- Self { macro_db }
- }
-
- /// Process all users who need updated insight batches
- #[tracing::instrument(skip(self))]
- pub async fn process_all_users(&self, batch_size: i64) -> Result<ProcessingStats> {
- let mut stats = ProcessingStats::default();
-
- tracing::info!("Starting daily insight batch processing");
-
- // Clean up expired batches first
- let expired_count = user_insight::delete_expired_insight_batches(&self.macro_db)
- .await
- .context("Failed to clean up expired batches")?;
-
- tracing::info!("Cleaned up {} expired insight batches", expired_count);
- stats.expired_cleaned = expired_count;
-
- // Get users who need batch refresh
- let user_ids = user_insight::get_users_needing_batch_refresh(&self.macro_db, batch_size)
- .await
- .context("Failed to get users needing batch refresh")?;
-
- tracing::info!(
- "Found {} users needing insight batch refresh",
- user_ids.len()
- );
-
- // Process each user
- for user_id in &user_ids {
- match self.process_user_batch(user_id).await {
- Ok(_) => {
- stats.users_processed += 1;
- tracing::debug!("Successfully processed batch for user {}", user_id);
- }
- Err(e) => {
- stats.users_failed += 1;
- tracing::error!(
- error = ?e,
- user_id = %user_id,
- "Failed to process batch for user"
- );
- }
- }
- }
-
- tracing::info!(
- "Batch processing complete. Processed: {}, Failed: {}, Expired cleaned: {}",
- stats.users_processed,
- stats.users_failed,
- stats.expired_cleaned
- );
-
- Ok(stats)
- }
-
- /// Process insight batch for a single user
- #[tracing::instrument(skip(self))]
- pub async fn process_user_batch(&self, user_id: &str) -> Result<()> {
- // Get all generated insights for user
- let max_insights = get_max_insights_limit() as u32;
- let all_insights = user_insight::get_user_insights(
- &self.macro_db,
- user_id,
- Some(true), // Only generated insights
- max_insights,
- 0,
- )
- .await
- .context("Failed to fetch user insights")?;
-
- if all_insights.is_empty() {
- tracing::debug!("No insights found for user {}", user_id);
- return Ok(());
- }
-
- // Set up ranking context for smart selection
- let ranking_context = RankingContext {
- current_time: Utc::now(),
- query_keywords: None, // Could be enhanced with user preferences
- max_insights: 50, // Allow up to 50 insights to be considered
- prefer_actionable: true, // Prioritize actionable insights
- };
-
- // Use smart ranking to select best insights within token budget
- let selected_insights =
- select_insights_for_llm_context(&all_insights, &ranking_context, get_target_tokens());
-
- if selected_insights.is_empty() {
- tracing::warn!("No insights selected for user {}", user_id);
- return Ok(());
- }
-
- // Calculate stats
- let insight_ids: Vec<String> = selected_insights
- .iter()
- .filter_map(|i| i.id.clone())
- .collect();
-
- let total_chars: usize = selected_insights.iter().map(|i| i.content.len()).sum();
-
- let estimated_tokens = total_chars / 4;
-
- // Create expiration time
- let expires_at = Utc::now() + Duration::days(get_batch_expiration_days());
-
- // Store ranking context for debugging/analytics
- let ranking_context_json = serde_json::json!({
- "target_tokens": get_target_tokens(),
- "prefer_actionable": ranking_context.prefer_actionable,
- "selection_time": ranking_context.current_time,
- "total_insights_considered": all_insights.len(),
- "insights_selected": insight_ids.len()
- });
-
- // Upsert the batch
- let batch_id = user_insight::upsert_user_insight_batch(
- &self.macro_db,
- user_id,
- &insight_ids,
- total_chars as i32,
- estimated_tokens as i32,
- expires_at,
- Some(&ranking_context_json),
- )
- .await
- .context("Failed to upsert insight batch")?;
-
- tracing::info!(
- "Created insight batch {} for user {} with {} insights ({} chars, ~{} tokens)",
- batch_id,
- user_id,
- insight_ids.len(),
- total_chars,
- estimated_tokens
- );
-
- Ok(())
- }
-
- /// Process a single user immediately (for API triggered processing)
- pub async fn process_user_immediate(&self, user_id: &str) -> Result<()> {
- self.process_user_batch(user_id).await
- }
-}
-
-#[derive(Debug, Default)]
-pub struct ProcessingStats {
- pub users_processed: u64,
- pub users_failed: u64,
- pub expired_cleaned: u64,
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use chrono::Utc;
- use model::insight_context::{InsightType, UserInsightRecord};
-
- fn create_test_insight(
- id: &str,
- content: &str,
- confidence: i32,
- insight_type: InsightType,
- ) -> UserInsightRecord {
- UserInsightRecord {
- id: Some(id.to_string()),
- user_id: "test_user".to_string(),
- content: content.to_string(),
- confidence: Some(confidence),
- generated: true,
- source: "email".to_string(),
- source_location: None,
- created_at: Utc::now(),
- updated_at: Utc::now(),
- span_start: None,
- span_end: None,
- insight_type: Some(insight_type),
- relevance_keywords: Some(vec!["test".to_string()]),
- }
- }
-
- #[test]
- fn test_target_token_calculation() {
- // Test that our target is reasonable
- assert_eq!(get_target_tokens(), 2048);
-
- // With default 4 chars per token, we get 8192 characters
- let target_chars = get_target_tokens() * 4;
- assert_eq!(target_chars, 8192);
-
- // Should fit roughly 40-50 insights of ~150-200 chars each
- let avg_insight_chars = 175;
- let expected_insights = target_chars / avg_insight_chars;
- assert!(expected_insights >= 40 && expected_insights <= 50);
- }
-
- #[test]
- fn test_insights_selection_prioritizes_actionable() {
- let insights = vec![
- create_test_insight(
- "1",
- "Low confidence informational",
- 30,
- InsightType::Informational,
- ),
- create_test_insight(
- "2",
- "High confidence actionable",
- 90,
- InsightType::Actionable,
- ),
- create_test_insight("3", "Medium confidence warning", 70, InsightType::Warning),
- ];
-
- let context = RankingContext {
- current_time: Utc::now(),
- query_keywords: None,
- max_insights: 10,
- prefer_actionable: true,
- };
-
- let selected = select_insights_for_llm_context(&insights, &context, 1000);
-
- // Should prefer the actionable insight first due to high confidence + actionable type
- assert!(!selected.is_empty());
- assert_eq!(selected[0].id.as_ref().unwrap(), "2");
- }
-}
diff --git a/rust/cloud-storage/insight_service/src/insight/consumer/chat.rs b/rust/cloud-storage/insight_service/src/insight/consumer/chat.rs
deleted file mode 100644
index c252f455b3..0000000000
--- a/rust/cloud-storage/insight_service/src/insight/consumer/chat.rs
+++ /dev/null
@@ -1,171 +0,0 @@
-use super::InsightContextConsumer;
-use super::generator::generate_insights;
-use crate::context::ServiceContext;
-use crate::service::document::{get_plaintext_content_from_id, summarize_document};
-use anyhow::{Context, Error};
-use macro_db_client::insight::document::create_document_summaries;
-use model::chat::{ChatHistory, Summary};
-use model::document::DocumentBasic;
-use model::insight_context::chat::{AttachmentInsight, ChatContext, Conversation, UserMessage};
-use model::insight_context::{UserInsightRecord, document::DocumentSummary};
-use std::collections::HashMap;
-use std::sync::Arc;
-
-pub const CONTEXT_SOURCE_NAME: &str = "chat";
-
-pub struct ChatInsightContextConsumer;
-
-#[async_trait::async_trait]
-impl InsightContextConsumer for ChatInsightContextConsumer {
- fn source_name(&self) -> String {
- CONTEXT_SOURCE_NAME.to_string()
- }
-
- fn trigger_generation_at_n_messages(&self) -> usize {
- 10
- }
-
- async fn generate_insights(
- &self,
- resource_ids: &[String],
- user_id: &str,
- existing_insights: &[UserInsightRecord],
- service_context: Arc<ServiceContext>,
- ) -> Result<Vec<UserInsightRecord>, Error> {
- tracing::debug!("generate chat insights");
- let history = service_context
- .content_client
- .chat
- .get_chat_history_for_messages(resource_ids, None)
- .await
- .map_err(|e| anyhow::anyhow!("Failed to get chat history: {}", e))
- .inspect_err(|err| tracing::error!(error=?err, "failed to fetch chat context"))
- .and_then(|response| {
- if response.conversation.is_empty() {
- tracing::error!("could not find expected chat context");
- Err(anyhow::anyhow!("Could not find expected chat context"))
- } else {
- Ok(response)
- }
- })?;
-
- // let attachment_ids = deduplicate_attachment_ids(&history);
- // let attachment_insights = get_or_make_summaries(service_context, &attachment_ids)
- // .await
- // .context("get or make document insights")?;
-
- let log_description = "user chatbot conversations including, context about documents the user chose to include";
-
- let context = summarize_attachments(service_context.clone(), history)
- .await
- .context("failed to summarize attachments")?;
-
- generate_insights(
- CONTEXT_SOURCE_NAME,
- user_id,
- log_description,
- context.into(),
- existing_insights,
- )
- .await
- }
-}
-
-pub async fn summarize_attachments(
- ctx: Arc<ServiceContext>,
- chat_history: ChatHistory,
-) -> Result<ChatContext, Error> {
- // helper
- let iterate_attachments = || {
- chat_history.conversation.iter().flat_map(|conversation| {
- conversation
- .messages
- .iter()
- .flat_map(|message| message.attachment_summaries.iter())
- })
- };
-
- // all attachment document ids
- let document_ids = iterate_attachments()
- .map(|summary| match summary {
- Summary::NoSummary { document_id } => (document_id.as_str(), None),
- Summary::Summary(summary) => (summary.document_id.as_str(), Some(summary.clone())),
- })
- .collect::<HashMap<_, _>>();
-
- // summarize and save anything that needs summarizing
- let summaries = futures::future::join_all(document_ids.into_iter().map(|(id, summary)| {
- let ctx = ctx.clone();
- async move {
- let summarizer = || async {
- let (text, metadata) = get_plaintext_content_from_id(ctx.clone(), id).await?;
- let summary = summarize_document(text, metadata.clone()).await?;
- let summary = DocumentSummary {
- created_at: None,
- id: None,
- document_id: id.to_owned(),
- summary,
- version_id: "latest".to_string(), // content_lib always gets latest version
- };
- let summary = create_document_summaries(&ctx.macro_db, vec![summary])
- .await?
- .first()
- .map(|first| (first.to_owned(), metadata))
- .ok_or_else(|| anyhow::anyhow!("expected one summary"))?;
- Ok::<(DocumentSummary, DocumentBasic), Error>(summary)
- };
-
- match summary {
- Some(_existing_summary) => {
- // Always regenerate summary for now since we can't easily compare versions
- // TODO: Add version comparison logic if needed
- summarizer().await
- }
- None => summarizer().await,
- }
- }
- }))
- .await
- .into_iter()
- .flatten()
- .map(|(summary, metadata)| (summary.document_id.clone(), (summary, metadata)))
- .collect::<HashMap<_, _>>();
-
- let chat_context = ChatContext(
- chat_history
- .conversation
- .into_iter()
- .map(|conversation| Conversation {
- conversation_title: conversation.title,
- messages: conversation
- .messages
- .into_iter()
- .map(|message| UserMessage {
- content: message.content,
- date: message.date,
- attachment_insights: message
- .attachment_summaries
- .into_iter()
- .flat_map(|summary| {
- summaries
- .get(summary.document_id())
- .ok_or_else(|| {
- anyhow::anyhow!(
- "expected summary for {}",
- summary.document_id()
- )
- })
- .map(|(summary, metadata)| AttachmentInsight::Document {
- file_type: metadata.file_type.clone().unwrap_or_default(),
- summary: summary.summary.clone(),
- title: metadata.document_name.clone(),
- })
- })
- .collect(),
- })
- .collect(),
- })
- .collect(),
- );
- Ok(chat_context)
-}
diff --git a/rust/cloud-storage/insight_service/src/insight/consumer/email_processing.rs b/rust/cloud-storage/insight_service/src/insight/consumer/email_processing.rs
deleted file mode 100644
index a612a88aff..0000000000
--- a/rust/cloud-storage/insight_service/src/insight/consumer/email_processing.rs
+++ /dev/null
@@ -1,1049 +0,0 @@
-use ai::{
- structured_output_v2::structured_completion_v2,
- types::{MessageBuilder, RequestBuilder},
-};
-use anyhow::{Context, Result};
-use async_stream::stream;
-use chrono::{DateTime, Utc};
-use futures::stream::{FuturesUnordered, Stream, StreamExt};
-use macro_db_client::insight::user::create_insights;
-use model::insight_context::EmailSourceLocation;
-use model::insight_context::{
- SourceLocation, UserInsightRecord, email_insights::EMAIL_INSIGHT_PROVIDER_SOURCE_NAME,
-};
-use models_email::email::service::message::ParsedMessage;
-use std::{
- collections::{HashMap, HashSet},
- sync::Arc,
-};
-use tokio::{pin, sync::Semaphore, task::JoinHandle};
-
-use crate::{
- context::ServiceContext,
- insight::consumer::INSIGHT_MODEL,
- insight::deduplication::{DeduplicationConfig, InsightDeduplicator},
-};
-use macro_db_client::insight::user::get_user_insights;
-
-use super::EmailInsights;
-use super::shared_prompts::{
- CLASSIFICATION_TYPES_PROMPT, CONFIDENCE_SCORING_PROMPT, KEYWORDS_PROMPT,
-};
-use crate::context::InsightScribe;
-
-pub const MAX_CONCURRENT_AI_REQUESTS: usize = 4;
-pub const MAX_CONCURRENT_THREAD_REQUESTS: usize = 3;
-const CHAT_COMPLETION_REQUEST_MAX_TOKENS: usize = 32_000;
-const MAX_MESSAGES_PER_THREAD_BATCH: usize = 50; // Smaller batches, max is 100 in email service
-const MAX_THREADS_IN_MEMORY: usize = 10; // Limit concurrent threads in memory
-const MAX_CHARS_PER_EMAIL_PROMPT: usize = 32_000; // Your existing limit
-
-fn build_email_insights_system_prompt(user_emails: &[String]) -> String {
- format!(
- r#"You are an intelligent internal tool that analyzes user behavior to find patterns. You will be provided
-a concatenated list of a user's email threads and you will find insights in these threads.
-The user in question is identified by their email address(es) and their user id.
-The user's email address(es) which you will use to identify this user is/are: [{}].
-Insights are one to three sentences describing user preferences, or who the user is as a person.
-You need not generate an insight for every message. You should combine similar ideas into a single user insight.
-Use the email thread id and message id (both are standard UUIDs) to identify the insight source location.
-An insight source location is a list of thread ids and a list of message ids,
-and can have multiple thread ids and message ids (if necessary).
-Try to keep insights to a single thread unless you feel they are relevant to multiple threads.
-Generally, you should generate insights across multiple messages in a thread.
-Insights should be atomic in nature, do not try to combine too much information into a single insight.
-If you are unsure if an insight is relevant to the user, prioritize adding it to the insight list.
-Remember, if there are no useful insights, return an empty list of insights (not null or omitted).
-
-{}
-
-{}
-
-{}
-When specifying a source location (if any), use this format:
-{{{{
- "threadIds": ["uuid-string-1", "uuid-string-2"],
- "messageIds": ["uuid-string-3"],
- "confidence": 3,
- "success": true,
- "insightType": "actionable",
- "relevanceKeywords": ["email", "project", "deadline"]
-}}}}
-
-All fields must be present, and all IDs must be strings (even if they look like numbers or UUIDs).
-"#,
- user_emails.join(", "),
- CONFIDENCE_SCORING_PROMPT,
- CLASSIFICATION_TYPES_PROMPT,
- KEYWORDS_PROMPT
- )
-}
-
-pub fn new_thread_processor(
- service_context: Arc<ServiceContext>,
- user_id: String,
- user_emails: &[String],
-) -> ThreadProcessor {
- let system_prompt = build_email_insights_system_prompt(user_emails);
- tracing::debug!("Building thread processor for: {}", user_id);
- ThreadProcessor {
- service_context,
- fetch_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_THREAD_REQUESTS)),
- ai_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_AI_REQUESTS)),
- system_prompt,
- user_id,
- user_emails: user_emails.to_vec(),
- }
-}
-
-pub struct ThreadProcessor {
- pub service_context: Arc<ServiceContext>,
- pub fetch_semaphore: Arc<Semaphore>,
- pub ai_semaphore: Arc<Semaphore>,
- pub system_prompt: String,
- pub user_id: String,
- pub user_emails: Vec<String>,
-}
-
-impl ThreadProcessor {
- /// Process threads with enhanced deduplication against existing insights
- pub async fn process_threads_streaming_with_deduplication(
- &self,
- thread_ids: &[String],
- ) -> Result<Vec<String>> {
- let mut all_insight_records = Vec::new();
- let thread_chunks = thread_ids.chunks(MAX_THREADS_IN_MEMORY);
-
- for thread_chunk in thread_chunks {
- tracing::debug!(?thread_chunk, "Processing thread chunk with deduplication");
- let chunk_results = self.process_thread_chunk(thread_chunk).await?;
- all_insight_records.extend(chunk_results);
- }
-
- // Get existing insights for deduplication (limit to recent insights for performance)
- let existing_insights = get_user_insights(
- &self.service_context.macro_db,
- &self.user_id,
- Some(true),
- 1000,
- 0,
- )
- .await
- .context("Failed to fetch existing insights for deduplication")?;
-
- // Deduplicate insights using email-specific configuration
- let original_count = all_insight_records.len();
- let deduplicated_insights = if !all_insight_records.is_empty() {
- let deduplication_config = DeduplicationConfig {
- exact_match_enabled: true,
- semantic_similarity_threshold: 0.80, // Lower threshold for emails
- edit_distance_threshold: 15,
- source_location_weight: 0.4, // Higher weight for email source overlap
- confidence_weight: 0.1,
- llm_fallback_enabled: true, // Enable LLM for email edge cases
- };
-
- let deduplicator = InsightDeduplicator::new(deduplication_config);
- deduplicator
- .deduplicate_insights(&all_insight_records, &existing_insights)
- .await
- .context("Failed to deduplicate thread insights")?
- } else {
- all_insight_records
- };
-
- tracing::info!(
- original_count = original_count,
- existing_count = existing_insights.len(),
- deduplicated_count = deduplicated_insights.len(),
- "Thread insight deduplication completed"
- );
-
- // Create insights from deduplicated records
- let ids = if !deduplicated_insights.is_empty() {
- tracing::debug!(
- "Creating {} deduplicated insights in DB",
- deduplicated_insights.len()
- );
- create_insights(
- &self.service_context.macro_db,
- &deduplicated_insights,
- &self.user_id,
- )
- .await?
- } else {
- tracing::debug!("No insights to create after deduplication");
- vec![]
- };
-
- Ok(ids)
- }
-
- /// Process messages with enhanced deduplication against existing insights
- pub async fn process_messages_streaming_with_deduplication(
- &self,
- message_thread_ids: &[(String, String)], // message_id, thread_id
- ) -> Result<Vec<String>> {
- let mut all_insight_records = Vec::new();
- let mut thread_messages_map: HashMap<String, Vec<String>> = HashMap::new();
-
- for (message_id, thread_id) in message_thread_ids {
- thread_messages_map
- .entry(thread_id.clone())
- .or_default()
- .push(message_id.clone());
- }
-
- let thread_messages = thread_messages_map.into_iter().collect::<Vec<_>>();
- let thread_message_chunks = thread_messages.chunks(MAX_THREADS_IN_MEMORY);
-
- for thread_message_chunk in thread_message_chunks {
- tracing::debug!(
- ?thread_message_chunk,
- "Processing messages chunk with deduplication"
- );
- let chunk_results = self.process_messages_chunk(thread_message_chunk).await?;
- all_insight_records.extend(chunk_results);
- }
-
- // Get existing insights for deduplication (limit to recent insights for performance)
- let existing_insights = get_user_insights(
- &self.service_context.macro_db,
- &self.user_id,
- Some(true),
- 1000,
- 0,
- )
- .await
- .context("Failed to fetch existing insights for deduplication")?;
-
- // Deduplicate insights using email-specific configuration
- let original_count = all_insight_records.len();
- let deduplicated_insights = if !all_insight_records.is_empty() {
- let deduplication_config = DeduplicationConfig {
- exact_match_enabled: true,
- semantic_similarity_threshold: 0.80, // Lower threshold for emails
- edit_distance_threshold: 15,
- source_location_weight: 0.4, // Higher weight for email source overlap
- confidence_weight: 0.1,
- llm_fallback_enabled: true, // Enable LLM for email edge cases
- };
-
- let deduplicator = InsightDeduplicator::new(deduplication_config);
- deduplicator
- .deduplicate_insights(&all_insight_records, &existing_insights)
- .await
- .context("Failed to deduplicate message insights")?
- } else {
- all_insight_records
- };
-
- tracing::info!(
- original_count = original_count,
- existing_count = existing_insights.len(),
- deduplicated_count = deduplicated_insights.len(),
- "Message insight deduplication completed"
- );
-
- // Create insights from deduplicated records
- let ids = if !deduplicated_insights.is_empty() {
- tracing::debug!(
- "Creating {} deduplicated insights in DB",
- deduplicated_insights.len()
- );
- create_insights(
- &self.service_context.macro_db,
- &deduplicated_insights,
- &self.user_id,
- )
- .await?
- } else {
- tracing::debug!("No insights to create after deduplication");
- vec![]
- };
-
- Ok(ids)
- }
-
- async fn process_thread_chunk(&self, thread_ids: &[String]) -> Result<Vec<UserInsightRecord>> {
- let mut chunker = MessageChunker::new(MAX_CHARS_PER_EMAIL_PROMPT);
- let mut ai_futures = FuturesUnordered::new();
- let mut all_records = Vec::new();
- let stream_thread_fetcher = StreamingThreadFetcher {
- content_client: self.service_context.content_client.clone(),
- semaphore: self.fetch_semaphore.clone(),
- };
-
- // Process each thread as a stream
- for thread_id in thread_ids {
- tracing::debug!(%thread_id, "Fetching messages for thread");
- let thread_stream = stream_thread_fetcher
- .fetch_thread_stream(thread_id.clone())
- .await?;
-
- pin!(thread_stream);
-
- // Process thread messages in batches
- while let Some(batch_result) = thread_stream.next().await {
- let messages = batch_result?;
- tracing::debug!(%thread_id, batch_size = messages.len(), "Fetched message batch");
-
- for message in messages {
- tracing::debug!(%thread_id, msg_id = %message.db_id, "Adding message to chunk");
- // Try to add message to current chunk
- if let Some(ready_chunk) = chunker.try_add_message(thread_id, &message) {
- tracing::debug!(
- chunk_size = ready_chunk.content.len(),
- thread_ids = ?ready_chunk.thread_ids,
- "Emitting chunk for AI processing"
- );
- // Process the ready chunk
- let future = self.process_chunk(ready_chunk, false).await;
- ai_futures.push(future);
-
- // Limit concurrent AI requests
- if ai_futures.len() >= MAX_CONCURRENT_AI_REQUESTS
- && let Some(result) = ai_futures.next().await
- {
- match result? {
- Ok(Some(records)) => all_records.extend(records),
- Ok(None) => {} // No insights generated
- Err(e) => tracing::warn!("Insight generation failed: {:?}", e),
- }
- }
- }
- }
- }
- }
-
- // Process final chunk if any
- if let Some(final_chunk) = chunker.finalize() {
- tracing::debug!(
- chunk_size = final_chunk.content.len(),
- thread_ids = ?final_chunk.thread_ids,
- "Emitting final chunk for AI processing"
- );
- let future = self.process_chunk(final_chunk, false).await;
- ai_futures.push(future);
- }
-
- // Collect remaining results
- while let Some(result) = ai_futures.next().await {
- match result? {
- Ok(Some(records)) => all_records.extend(records),
- Ok(None) => {} // No insights generated
- Err(e) => tracing::warn!("Insight generation failed: {:?}", e),
- }
- }
-
- Ok(all_records)
- }
-
- async fn process_messages_chunk(
- &self,
- thread_messages: &[(String, Vec<String>)], // thread_id, message_ids
- ) -> Result<Vec<UserInsightRecord>> {
- let mut chunker = MessageChunker::new(MAX_CHARS_PER_EMAIL_PROMPT);
- let mut ai_futures = FuturesUnordered::new();
- let mut all_records = Vec::new();
- let stream_thread_fetcher = StreamingThreadFetcher {
- content_client: self.service_context.content_client.clone(),
- semaphore: self.fetch_semaphore.clone(),
- };
-
- // Process each thread as a stream
- for (thread_id, message_ids) in thread_messages {
- tracing::debug!(%thread_id, "Fetching messages for thread");
- let thread_stream = stream_thread_fetcher
- .fetch_messages_stream(message_ids.clone())
- .await?;
-
- pin!(thread_stream);
-
- // Process thread messages in batches
- while let Some(batch_result) = thread_stream.next().await {
- let messages = batch_result?;
- tracing::debug!(%thread_id, batch_size = messages.len(), "Fetched message batch");
-
- for message in messages {
- tracing::debug!(%thread_id, msg_id = %message.db_id, "Adding message to chunk");
- // Try to add message to current chunk
- if let Some(ready_chunk) = chunker.try_add_message(thread_id, &message) {
- tracing::debug!(
- chunk_size = ready_chunk.content.len(),
- thread_ids = ?ready_chunk.thread_ids,
- "Emitting chunk for AI processing"
- );
- // Process the ready chunk
- let future = self.process_chunk(ready_chunk, true).await;
- ai_futures.push(future);
-
- // Limit concurrent AI requests
- if ai_futures.len() >= MAX_CONCURRENT_AI_REQUESTS
- && let Some(result) = ai_futures.next().await
- {
- match result? {
- Ok(Some(records)) => all_records.extend(records),
- Ok(None) => {} // No insights generated
- Err(e) => tracing::warn!("Insight generation failed: {:?}", e),
- }
- }
- }
- }
- }
- }
-
- // Process final chunk if any
- if let Some(final_chunk) = chunker.finalize() {
- tracing::debug!(
- chunk_size = final_chunk.content.len(),
- thread_ids = ?final_chunk.thread_ids,
- "Emitting final chunk for AI processing"
- );
- let future = self.process_chunk(final_chunk, true).await;
- ai_futures.push(future);
- }
-
- // Collect remaining results
- while let Some(result) = ai_futures.next().await {
- match result? {
- Ok(Some(records)) => all_records.extend(records),
- Ok(None) => {} // No insights generated
- Err(e) => tracing::warn!("Insight generation failed: {:?}", e),
- }
- }
-
- Ok(all_records)
- }
-
- async fn process_chunk(
- &self,
- chunk: ChunkReady,
- use_message_ids: bool, // insert message IDs into default source location
- ) -> JoinHandle<Result<Option<Vec<UserInsightRecord>>>> {
- let permit = self.ai_semaphore.clone().acquire_owned().await.unwrap();
- let system_prompt = self.system_prompt.clone();
- let user_id = self.user_id.clone();
- let user_emails = self.user_emails.clone();
-
- tracing::debug!(
- chunk_size = chunk.content.len(),
- thread_ids = ?chunk.thread_ids,
- "Creating default source location for chunk"
- );
- let default_source_location = Some(SourceLocation::Email(EmailSourceLocation {
- thread_ids: chunk.thread_ids.clone().into_iter().collect(),
- message_ids: if use_message_ids {
- chunk.message_ids.clone().into_iter().collect()
- } else {
- vec![]
- },
- email_addresses: None, // Will be populated by into_insight_records
- }));
-
- tracing::debug!("Spawning AI request for chunk");
- tokio::spawn(async move {
- let _permit = permit;
- match generate_email_insights_from_prompt(system_prompt, chunk.content).await {
- Ok(insights) if !insights.insights.is_empty() => {
- tracing::debug!("AI returned {} insights", insights.insights.len());
-
- // Build message map for precise span calculation
- let messages_by_id: std::collections::HashMap<String, &ParsedMessage> = chunk
- .messages
- .iter()
- .map(|msg| (msg.db_id.to_string(), msg))
- .collect();
-
- Ok(Some(insights.into_insight_records(
- EMAIL_INSIGHT_PROVIDER_SOURCE_NAME,
- &user_id,
- default_source_location,
- chunk.span_start,
- chunk.span_end,
- Some(&messages_by_id),
- Some(&user_emails),
- )))
- }
- Ok(_) => {
- tracing::debug!("AI returned no insights");
- Ok(None)
- }
- Err(e) => {
- tracing::error!("Insight generation failed: {:?}", e);
- Ok(None)
- }
- }
- })
- }
-}
-
-struct StreamingThreadFetcher {
- content_client: InsightScribe,
- semaphore: Arc<Semaphore>,
-}
-
-impl StreamingThreadFetcher {
- async fn fetch_thread_stream(
- &self,
- thread_id: String,
- ) -> Result<impl Stream<Item = Result<Vec<ParsedMessage>>>> {
- let content_client = self.content_client.clone();
- let semaphore = self.semaphore.clone();
-
- Ok(stream! {
- let _permit = semaphore.acquire().await.unwrap();
- let mut offset = 0;
-
- loop {
- match content_client
- .email
- .get_email_messages_by_thread_id(&thread_id, offset, MAX_MESSAGES_PER_THREAD_BATCH as i64, None)
- .await
- {
- Ok(messages) => {
- if messages.is_empty() {
- break;
- }
-
- let message_count = messages.len();
- offset += message_count as i64;
- yield Ok(messages);
-
- // If we got fewer than requested, we're done
- if message_count < MAX_MESSAGES_PER_THREAD_BATCH {
- break;
- }
- }
- Err(e) => {
- yield Err(anyhow::anyhow!("Failed to get email messages by thread ID: {}", e));
- break;
- }
- }
- }
- })
- }
-
- async fn fetch_messages_stream(
- &self,
- message_ids: Vec<String>,
- ) -> Result<impl Stream<Item = Result<Vec<ParsedMessage>>>> {
- let content_client = self.content_client.clone();
- let semaphore = self.semaphore.clone();
-
- Ok(stream! {
- let _permit = semaphore.acquire().await.unwrap();
- let message_ids_chunks = message_ids.chunks(MAX_MESSAGES_PER_THREAD_BATCH);
-
- for message_ids_chunk in message_ids_chunks {
- tracing::debug!(?message_ids_chunk, "Processing message IDs chunk");
- let message_ids_chunk_owned: Vec<String> = message_ids_chunk.to_vec();
- let batch_result = content_client
- .email
- .get_email_messages_by_id_batch(&message_ids_chunk_owned, None)
- .await;
- match batch_result {
- Ok(messages) => {
- yield Ok(messages);
- }
- Err(e) => {
- yield Err(anyhow::anyhow!("Failed to get email messages by ID batch: {}", e));
- break;
- }
- }
- }
- })
- }
-}
-
-struct MessageChunker {
- current_chunk: String,
- current_size: usize,
- current_thread_ids: HashSet<String>,
- current_message_ids: HashSet<String>,
- max_size: usize,
- earliest_date: Option<DateTime<Utc>>,
- latest_date: Option<DateTime<Utc>>,
- current_messages: Vec<ParsedMessage>,
-}
-
-struct ChunkReady {
- content: String,
- thread_ids: HashSet<String>,
- message_ids: HashSet<String>,
- span_start: Option<DateTime<Utc>>,
- span_end: Option<DateTime<Utc>>,
- messages: Vec<ParsedMessage>,
-}
-
-impl MessageChunker {
- fn new(max_size: usize) -> Self {
- Self {
- current_chunk: String::new(),
- current_size: 0,
- current_thread_ids: HashSet::new(),
- current_message_ids: HashSet::new(),
- max_size,
- earliest_date: None,
- latest_date: None,
- current_messages: Vec::new(),
- }
- }
-
- fn try_add_message(&mut self, thread_id: &str, message: &ParsedMessage) -> Option<ChunkReady> {
- let formatted_msg = format_message(thread_id, message);
- let msg_size = formatted_msg.len();
- let msg_date = message.internal_date_ts;
-
- // If adding this message would exceed limit and we have content, emit chunk
- if self.current_size + msg_size > self.max_size && !self.current_chunk.is_empty() {
- let chunk = ChunkReady {
- content: std::mem::take(&mut self.current_chunk),
- thread_ids: std::mem::take(&mut self.current_thread_ids),
- message_ids: std::mem::take(&mut self.current_message_ids),
- span_start: self.earliest_date,
- span_end: self.latest_date,
- messages: std::mem::take(&mut self.current_messages),
- };
- self.current_size = 0;
-
- // Reset date tracking for new chunk with this message
- self.earliest_date = msg_date;
- self.latest_date = msg_date;
-
- // Start new chunk with this message
- self.current_chunk = formatted_msg;
- self.current_size = msg_size;
- self.current_thread_ids.insert(thread_id.to_string());
- self.current_message_ids.insert(message.db_id.to_string());
- self.current_messages.push(message.clone());
-
- return Some(chunk);
- }
-
- // Add to current chunk and update date tracking
- self.current_chunk.push_str(&formatted_msg);
- self.current_size += msg_size;
- self.current_thread_ids.insert(thread_id.to_string());
- self.current_message_ids.insert(message.db_id.to_string());
- self.current_messages.push(message.clone());
-
- // Update date tracking with this message's timestamp
- if let Some(date) = msg_date {
- self.earliest_date = Some(
- self.earliest_date
- .map_or(date, |existing| existing.min(date)),
- );
- self.latest_date = Some(self.latest_date.map_or(date, |existing| existing.max(date)));
- }
-
- None
- }
-
- fn finalize(self) -> Option<ChunkReady> {
- if self.current_chunk.is_empty() {
- None
- } else {
- Some(ChunkReady {
- content: self.current_chunk,
- thread_ids: self.current_thread_ids,
- message_ids: self.current_message_ids,
- span_start: self.earliest_date,
- span_end: self.latest_date,
- messages: self.current_messages,
- })
- }
- }
-}
-
-fn clean_text(text: &str) -> String {
- text.chars()
- .filter(|c| {
- // Remove various Unicode control and formatting characters
- !matches!(*c,
- // Zero-width characters
- '\u{200B}' | // Zero Width Space
- '\u{200C}' | // Zero Width Non-Joiner
- '\u{200D}' | // Zero Width Joiner
- '\u{2060}' | // Word Joiner
- '\u{FEFF}' | // Zero Width No-Break Space (BOM)
-
- // Directional marks
- '\u{200E}' | // Left-to-Right Mark
- '\u{200F}' | // Right-to-Left Mark
- '\u{202A}' | // Left-to-Right Embedding
- '\u{202B}' | // Right-to-Left Embedding
- '\u{202C}' | // Pop Directional Formatting
- '\u{202D}' | // Left-to-Right Override
- '\u{202E}' | // Right-to-Left Override
- '\u{2066}' | // Left-to-Right Isolate
- '\u{2067}' | // Right-to-Left Isolate
- '\u{2068}' | // First Strong Isolate
- '\u{2069}' | // Pop Directional Isolate
-
- // Other control characters
- '\u{00AD}' | // Soft Hyphen
- '\u{034F}' | // Combining Grapheme Joiner
- '\u{061C}' | // Arabic Letter Mark
- '\u{180E}' | // Mongolian Vowel Separator
- '\u{2028}' | // Line Separator
- '\u{2029}' | // Paragraph Separator
-
- // Variation selectors (can cause display issues)
- '\u{FE00}'..='\u{FE0F}' | // Variation Selectors 1-16
- '\u{E0100}'..='\u{E01EF}' // Variation Selectors 17-256
- )
- })
- // Also collapse multiple whitespace into single spaces
- .collect::<String>()
- .split_whitespace()
- .collect::<Vec<&str>>()
- .join(" ")
-}
-
-fn format_message(thread_id: &str, msg: &ParsedMessage) -> String {
- let mut msg_text = String::new();
- msg_text.push_str("---\n");
- msg_text.push_str(&format!("Thread id: {}\n", thread_id));
- msg_text.push_str(&format!("Message id: {}\n", msg.db_id));
-
- if let Some(subject) = &msg.subject {
- msg_text.push_str(&format!("Subject: {}\n", subject));
- }
-
- if let Some(from) = &msg.from {
- msg_text.push_str(&format!(
- "From: {} <{}>\n",
- from.name.clone().unwrap_or_default(),
- from.email
- ));
- }
-
- if !msg.to.is_empty() {
- let tos = msg
- .to
- .iter()
- .map(|c| format!("{} <{}>", c.name.clone().unwrap_or_default(), c.email))
- .collect::<Vec<_>>()
- .join(", ");
- msg_text.push_str(&format!("To: {}\n", tos));
- }
-
- if !msg.cc.is_empty() {
- let ccs = msg
- .cc
- .iter()
- .map(|c| format!("{} <{}>", c.name.clone().unwrap_or_default(), c.email))
- .collect::<Vec<_>>()
- .join(", ");
- msg_text.push_str(&format!("CC: {}\n", ccs));
- }
-
- if !msg.bcc.is_empty() {
- let bccs = msg
- .bcc
- .iter()
- .map(|c| format!("{} <{}>", c.name.clone().unwrap_or_default(), c.email))
- .collect::<Vec<_>>()
- .join(", ");
- msg_text.push_str(&format!("BCC: {}\n", bccs));
- }
-
- if !msg.labels.is_empty() {
- let labels = msg
- .labels
- .iter()
- .map(|l| l.name.clone())
- .collect::<Vec<_>>()
- .join(", ");
- msg_text.push_str(&format!("Labels: {}\n", labels));
- }
-
- if let Some(body) = &msg.body_parsed {
- let cleaned_body = clean_text(body);
- let truncated_body = if cleaned_body.len() > MAX_CHARS_PER_EMAIL_PROMPT / 2 {
- format!(
- "{}... [truncated, original length: {} chars]",
- &cleaned_body[..MAX_CHARS_PER_EMAIL_PROMPT / 2],
- cleaned_body.len()
- )
- } else {
- cleaned_body
- };
- msg_text.push_str(&format!("Body: {}\n", truncated_body));
- } else {
- tracing::warn!("No body found for message {:?}", msg);
- }
-
- msg_text
-}
-
-async fn generate_email_insights_from_prompt(
- system_prompt: String,
- prompt: String,
-) -> anyhow::Result<EmailInsights> {
- let request = RequestBuilder::new()
- .max_tokens(CHAT_COMPLETION_REQUEST_MAX_TOKENS as u32)
- .system_prompt(system_prompt)
- .model(INSIGHT_MODEL)
- .messages(vec![MessageBuilder::new().user().content(prompt).build()])
- .build();
-
- let insights = structured_completion_v2::<EmailInsights>(request)
- .await
- .context("Generate new email user insights")?;
-
- tracing::debug!(?insights, "email insight generation insights");
-
- Ok(insights)
-}
-
-#[cfg(test)]
-mod email_tests {
- use super::*;
- use model::insight_context::{EmailSourceLocation, SourceLocation};
-
- #[derive(Default, Clone)]
- struct TestParsedMessage {
- pub db_id: String,
- pub body_parsed: Option<String>,
- }
-
- fn make_test_parsed_message(thread_id: &str, db_id: &str) -> (String, TestParsedMessage) {
- (
- thread_id.to_string(),
- TestParsedMessage {
- db_id: db_id.to_string(),
- body_parsed: Some("Test body".to_string()),
- },
- )
- }
-
- #[test]
- fn test_chunking_and_default_source_location() {
- // Simulate two threads, each with two messages
- let all_messages = vec![
- make_test_parsed_message("thread1", "msg1"),
- make_test_parsed_message("thread1", "msg2"),
- make_test_parsed_message("thread2", "msg3"),
- make_test_parsed_message("thread2", "msg4"),
- ];
-
- // Simulate chunking logic (small chunk size to force two chunks)
- let max_chars = 60; // small for test
- let mut chunker = MessageChunker {
- current_chunk: String::new(),
- current_size: 0,
- current_thread_ids: HashSet::new(),
- current_message_ids: HashSet::new(),
- max_size: max_chars,
- earliest_date: None,
- latest_date: None,
- current_messages: Vec::new(),
- };
- let mut chunks = Vec::new();
- for (thread_id, msg) in &all_messages {
- let formatted_msg = format!(
- "Thread id: {}\nMessage id: {}\nBody: {}\n",
- thread_id,
- msg.db_id,
- msg.body_parsed.as_deref().unwrap_or("")
- );
- let msg_size = formatted_msg.len();
- if chunker.current_size + msg_size > chunker.max_size
- && !chunker.current_chunk.is_empty()
- {
- chunks.push(ChunkReady {
- content: std::mem::take(&mut chunker.current_chunk),
- thread_ids: std::mem::take(&mut chunker.current_thread_ids),
- message_ids: std::mem::take(&mut chunker.current_message_ids),
- span_start: None,
- span_end: None,
- messages: std::mem::take(&mut chunker.current_messages),
- });
- chunker.current_size = 0;
- }
- chunker.current_chunk.push_str(&formatted_msg);
- chunker.current_size += msg_size;
- chunker.current_thread_ids.insert(thread_id.clone());
- }
- if !chunker.current_chunk.is_empty() {
- chunks.push(ChunkReady {
- content: chunker.current_chunk,
- thread_ids: chunker.current_thread_ids,
- message_ids: chunker.current_message_ids,
- span_start: None,
- span_end: None,
- messages: chunker.current_messages,
- });
- }
-
- // For each chunk, collect thread_ids and check default_source_location
- for chunk in &chunks {
- let default_source_location = SourceLocation::Email(EmailSourceLocation {
- thread_ids: chunk.thread_ids.clone().into_iter().collect(),
- message_ids: vec![],
- email_addresses: None,
- });
- // The chunk should only contain messages from the threads in thread_ids
- for tid in &chunk.thread_ids {
- assert!(
- default_source_location
- .as_email()
- .unwrap()
- .thread_ids
- .contains(tid)
- );
- }
- // The default_source_location should include all thread_ids in the chunk
- let SourceLocation::Email(email_loc) = &default_source_location;
- assert!(email_loc.thread_ids.len() >= 1);
- for tid in &email_loc.thread_ids {
- assert!(chunk.thread_ids.contains(tid));
- }
- }
- }
-
- // Helper for matching SourceLocation::Email
- trait AsEmail {
- fn as_email(&self) -> Option<&EmailSourceLocation>;
- }
- impl AsEmail for SourceLocation {
- fn as_email(&self) -> Option<&EmailSourceLocation> {
- let SourceLocation::Email(e) = self;
- Some(e)
- }
- }
-
- #[test]
- fn test_message_chunker_date_tracking() {
- use chrono::{DateTime, Utc};
-
- // Create test messages with different timestamps
- let earlier_date = DateTime::parse_from_rfc3339("2023-01-01T10:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
- let later_date = DateTime::parse_from_rfc3339("2023-01-03T14:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
-
- let msg1 = ParsedMessage {
- db_id: uuid::Uuid::new_v4(),
- link_id: uuid::Uuid::new_v4(),
- thread_db_id: uuid::Uuid::new_v4(),
- subject: Some("Test 1".to_string()),
- from: None,
- to: vec![],
- cc: vec![],
- bcc: vec![],
- labels: vec![],
- body_parsed: Some("Body 1".to_string()),
- internal_date_ts: Some(earlier_date),
- };
-
- let msg2 = ParsedMessage {
- db_id: uuid::Uuid::new_v4(),
- link_id: uuid::Uuid::new_v4(),
- thread_db_id: uuid::Uuid::new_v4(),
- subject: Some("Test 2".to_string()),
- from: None,
- to: vec![],
- cc: vec![],
- bcc: vec![],
- labels: vec![],
- body_parsed: Some("Body 2".to_string()),
- internal_date_ts: Some(later_date),
- };
-
- let mut chunker = MessageChunker::new(1000); // Large size to fit both messages
-
- // Add first message
- let result1 = chunker.try_add_message("thread1", &msg1);
- assert!(result1.is_none()); // Should not chunk yet
-
- // Add second message
- let result2 = chunker.try_add_message("thread1", &msg2);
- assert!(result2.is_none()); // Should still not chunk
-
- // Finalize the chunk
- let final_chunk = chunker.finalize().unwrap();
-
- // Check date tracking
- assert_eq!(final_chunk.span_start, Some(earlier_date)); // earliest: msg1.internal_date_ts
- assert_eq!(final_chunk.span_end, Some(later_date)); // latest: msg2.internal_date_ts
- assert_eq!(final_chunk.messages.len(), 2);
- }
-
- #[test]
- fn test_message_chunker_forces_chunk_with_dates() {
- use chrono::{DateTime, Utc};
-
- let date1 = DateTime::parse_from_rfc3339("2023-01-01T10:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
- let date2 = DateTime::parse_from_rfc3339("2023-01-02T12:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
- let date3 = DateTime::parse_from_rfc3339("2023-01-03T14:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
-
- let create_message = |id: &str, date: DateTime<Utc>| ParsedMessage {
- db_id: uuid::Uuid::new_v4(),
- link_id: uuid::Uuid::new_v4(),
- thread_db_id: uuid::Uuid::new_v4(),
- subject: Some(format!("Test {}", id)),
- from: None,
- to: vec![],
- cc: vec![],
- bcc: vec![],
- labels: vec![],
- body_parsed: Some(format!(
- "Very long body content for message {} that will exceed the chunk size limit",
- id
- )),
- internal_date_ts: Some(date),
- };
-
- let msg1 = create_message("1", date1);
- let msg2 = create_message("2", date2);
- let msg3 = create_message("3", date3);
-
- let mut chunker = MessageChunker::new(150); // Small size to force chunking
-
- // Add messages and expect chunking
- let chunk1 = chunker.try_add_message("thread1", &msg1);
- assert!(chunk1.is_none()); // First message fits
-
- let chunk2 = chunker.try_add_message("thread1", &msg2);
- assert!(chunk2.is_some()); // Should trigger chunk due to size
-
- let emitted_chunk = chunk2.unwrap();
- assert_eq!(emitted_chunk.span_start, Some(date1));
- assert_eq!(emitted_chunk.span_end, Some(date1)); // Only msg1 in this chunk
- assert_eq!(emitted_chunk.messages.len(), 1); // Only msg1 message in chunk content
-
- // Add third message (might trigger another chunk due to size)
- let chunk3 = chunker.try_add_message("thread1", &msg3);
-
- if chunk3.is_some() {
- // msg3 triggered another chunk, so msg2 is alone in the second chunk
- let second_chunk = chunk3.unwrap();
- assert_eq!(second_chunk.span_start, Some(date2)); // msg2 only
- assert_eq!(second_chunk.span_end, Some(date2));
- assert_eq!(second_chunk.messages.len(), 1);
-
- // msg3 should be in the final chunk
- let final_chunk = chunker.finalize().unwrap();
- assert_eq!(final_chunk.span_start, Some(date3)); // msg3 only
- assert_eq!(final_chunk.span_end, Some(date3));
- assert_eq!(final_chunk.messages.len(), 1);
- } else {
- // msg3 fit with msg2 in the same chunk
- let final_chunk = chunker.finalize().unwrap();
- assert_eq!(final_chunk.span_start, Some(date2)); // msg2 and msg3
- assert_eq!(final_chunk.span_end, Some(date3));
- assert_eq!(final_chunk.messages.len(), 2);
- }
- }
-}
diff --git a/rust/cloud-storage/insight_service/src/insight/consumer/generator.rs b/rust/cloud-storage/insight_service/src/insight/consumer/generator.rs
deleted file mode 100644
index 680a541545..0000000000
--- a/rust/cloud-storage/insight_service/src/insight/consumer/generator.rs
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- A generic insight generator reference implementation
- This implementation may be good enough to use with may context sources but testing is needed
-*/
-
-use crate::context::ServiceContext;
-use crate::insight::consumer::{INSIGHT_MODEL, Insights};
-use crate::insight::deduplication::{DeduplicationConfig, InsightDeduplicator};
-use ai::structured_output_v2::structured_completion_v2;
-use ai::types::{MessageBuilder, RequestBuilder};
-use ai_format::insight_context_log::InsightContextLog;
-use anyhow::{Context, Result};
-use model::insight_context::UserInsightRecord;
-use std::fmt::Display;
-use std::sync::Arc;
-
-use super::email_processing::new_thread_processor;
-use super::shared_prompts::{
- CLASSIFICATION_TYPES_PROMPT, CONFIDENCE_SCORING_PROMPT, KEYWORDS_PROMPT,
-};
-
-static CHAT_COMPLETION_REQUEST_MAX_TOKENS: usize = 32_000;
-
-fn build_base_prompt() -> String {
- format!(
- r#"You are an intelligent internal tool that analyzes user behavior to find patterns. You will be provided
-user logs and you will find insights in these logs. Insights are one to three sentences describing user preferences,
-or who the user is as a person. You need not generate an insight for every log. You should combine similar logs into a single
-user insight.
-
-{}
-
-{}
-
-{}
-The logs you are analyzing are:
- "#,
- CONFIDENCE_SCORING_PROMPT, CLASSIFICATION_TYPES_PROMPT, KEYWORDS_PROMPT
- )
-}
-
-pub async fn generate_insights<T>(
- source: &str,
- user_id: &str,
- log_description: &'static str, // a description of the logs being generated over
- context: InsightContextLog<T>,
- existing_insights: &[UserInsightRecord],
-) -> Result<Vec<UserInsightRecord>>
-where
- T: Display + Sized,
-{
- //1. generate insights for current context
- let base_prompt = build_base_prompt();
- let prompt = format!("{} {}", base_prompt, log_description);
- let existing_insights_string = existing_insights
- .iter()
- .map(|insight| insight.to_string())
- .collect::<Vec<_>>()
- .join("\n");
- let log_string = context.to_string();
- let context_string = format!(
- "These are existing insights about the user: {existing_insights_string}\nCONTEXT LOGS\n{log_string}"
- );
-
- let request = RequestBuilder::new()
- .max_tokens(CHAT_COMPLETION_REQUEST_MAX_TOKENS as u32)
- .system_prompt(prompt)
- .model(INSIGHT_MODEL)
- .messages(vec![
- MessageBuilder::new().user().content(context_string).build(),
- ])
- .build();
-
- let insights = structured_completion_v2::<Insights>(request)
- .await
- .context("Generate new user insights")?;
-
- let new_insights = insights.into_insight_records(source, user_id, None, None, None, None, None);
-
- // 2. deduplicate insights using efficient multi-layer approach
- let deduplication_config = DeduplicationConfig {
- exact_match_enabled: true,
- semantic_similarity_threshold: 0.85,
- edit_distance_threshold: 10,
- source_location_weight: 0.3,
- confidence_weight: 0.2,
- llm_fallback_enabled: false, // Disable LLM fallback for general insights
- };
- let deduplicator = InsightDeduplicator::new(deduplication_config);
- let deduplicated_insights = deduplicator
- .deduplicate_insights(&new_insights, existing_insights)
- .await
- .context("Failed to deduplicate insights")?;
-
- tracing::debug!(
- new_count = new_insights.len(),
- existing_count = existing_insights.len(),
- deduplicated_count = deduplicated_insights.len(),
- "Insight deduplication completed"
- );
-
- Ok(deduplicated_insights)
-}
-
-#[tracing::instrument(skip(service_context))]
-pub async fn generate_email_insights_for_threads(
- service_context: Arc<ServiceContext>,
- user_id: &str,
- user_emails: &[String],
- thread_ids: &[String],
-) -> Result<Vec<String>> {
- let processor = new_thread_processor(service_context, user_id.to_string(), user_emails);
- processor
- .process_threads_streaming_with_deduplication(thread_ids)
- .await
-}
-
-#[tracing::instrument(skip(service_context))]
-pub async fn generate_email_insights_for_messages(
- service_context: Arc<ServiceContext>,
- user_id: &str,
- user_emails: &[String],
- message_thread_ids: &[(String, String)], // message_id, thread_id
-) -> Result<Vec<String>> {
- let processor = new_thread_processor(service_context, user_id.to_string(), user_emails);
- processor
- .process_messages_streaming_with_deduplication(message_thread_ids)
- .await
-}
diff --git a/rust/cloud-storage/insight_service/src/insight/consumer/mod.rs b/rust/cloud-storage/insight_service/src/insight/consumer/mod.rs
deleted file mode 100644
index 40fff74b47..0000000000
--- a/rust/cloud-storage/insight_service/src/insight/consumer/mod.rs
+++ /dev/null
@@ -1,765 +0,0 @@
-pub mod chat;
-pub mod email_processing;
-pub mod generator;
-pub mod shared_prompts;
-
-use crate::context::ServiceContext;
-use ai::{traits::Metadata, types::Model};
-pub use chat::ChatInsightContextConsumer;
-use chrono::{DateTime, Utc};
-use model::insight_context::{
- EmailSourceLocation, InsightType as ModelInsightType, SourceLocation, UserInsightRecord,
-};
-use models_email::email::service::message::ParsedMessage;
-use schemars::JsonSchema;
-use serde::{Deserialize, Serialize};
-use std::collections::HashMap;
-use std::str::FromStr;
-
-pub const INSIGHT_MODEL: Model = Model::OpenAIGPT4o;
-
-/// Helper function to parse insight type from string
-fn parse_insight_type(type_str: &str) -> Option<ModelInsightType> {
- ModelInsightType::from_str(type_str).ok()
-}
-
-#[async_trait::async_trait]
-pub trait InsightContextConsumer: Send + Sync {
- fn source_name(&self) -> String;
- fn trigger_generation_at_n_messages(&self) -> usize;
-
- async fn generate_insights(
- &self,
- resource_ids: &[String],
- user_id: &str,
- existing_insights: &[model::insight_context::UserInsightRecord],
- service_context: std::sync::Arc<ServiceContext>,
- ) -> Result<Vec<model::insight_context::UserInsightRecord>, anyhow::Error>;
-}
-
-impl std::fmt::Debug for dyn InsightContextConsumer {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.debug_struct("InsightContextConsumer")
- .field("source_name", &self.source_name())
- .finish()
- }
-}
-
-pub trait InsightType: for<'de> Deserialize<'de> + JsonSchema {
- fn insight_content(&self) -> String;
- fn source_location(&self) -> Option<SourceLocation>;
- fn confidence(&self) -> i32;
- fn insight_type(&self) -> Option<model::insight_context::InsightType>;
- fn relevance_keywords(&self) -> Option<Vec<String>>;
-}
-
-#[derive(Serialize, Deserialize, Debug, JsonSchema)]
-#[serde(deny_unknown_fields)]
-pub struct StructuredInsights<T> {
- pub insights: Vec<T>,
-}
-
-pub type EmailInsights = StructuredInsights<EmailInsight>;
-// Insights with no source location
-pub type Insights = StructuredInsights<Insight>;
-
-impl<T> StructuredInsights<T>
-where
- T: InsightType,
-{
- #[expect(
- clippy::too_many_arguments,
- reason = "no good reason but too hard to fix right now"
- )]
- pub fn into_insight_records(
- self,
- source: &str,
- user_id: &str,
- default_source_location: Option<SourceLocation>,
- fallback_span_start: Option<DateTime<Utc>>,
- fallback_span_end: Option<DateTime<Utc>>,
- messages_by_id: Option<&HashMap<String, &ParsedMessage>>,
- user_emails: Option<&[String]>,
- ) -> Vec<UserInsightRecord> {
- self.insights
- .into_iter()
- .map(|insight| {
- let now = Utc::now();
- let mut source_location = insight
- .source_location()
- .or_else(|| default_source_location.clone());
-
- // Calculate precise span dates from LLM-specific message IDs
- let (span_start, span_end) = calculate_insight_span_dates(
- &insight,
- messages_by_id,
- fallback_span_start,
- fallback_span_end,
- );
-
- // Extract user email addresses from the messages and update source location
- if let Some(emails) = user_emails {
- let user_email_addresses =
- calculate_user_email_addresses(&insight, messages_by_id, emails);
-
- // Update the source location with user email addresses
- if let Some(SourceLocation::Email(ref mut email_location)) = source_location {
- email_location.email_addresses = user_email_addresses;
- }
- }
- UserInsightRecord {
- id: None,
- user_id: user_id.to_string(),
- confidence: validate_confidence_score(insight.confidence()),
- content: insight.insight_content(),
- generated: true,
- created_at: now,
- updated_at: now,
- source: source.to_string(),
- source_location,
- span_end,
- span_start,
- insight_type: insight.insight_type(),
- relevance_keywords: insight.relevance_keywords(),
- }
- })
- .collect()
- }
-}
-
-/// Validate confidence score is within the valid range (1-5), return None if invalid
-fn validate_confidence_score(score: i32) -> Option<i32> {
- if (1..=5).contains(&score) {
- Some(score)
- } else {
- tracing::warn!(
- "Invalid confidence score received from LLM: {}. Expected 1-5, setting to None",
- score
- );
- None
- }
-}
-
-/// Calculate precise span dates for an insight based on the specific message IDs the LLM referenced
-fn calculate_insight_span_dates<T: InsightType>(
- insight: &T,
- messages_by_id: Option<&HashMap<String, &ParsedMessage>>,
- fallback_span_start: Option<DateTime<Utc>>,
- fallback_span_end: Option<DateTime<Utc>>,
-) -> (Option<DateTime<Utc>>, Option<DateTime<Utc>>) {
- // Try to get specific message IDs from the insight if it's an EmailInsight
- (|| {
- let SourceLocation::Email(email_location) = insight.source_location()?;
- let msg_map = messages_by_id?;
- // Calculate span from the specific messages the LLM referenced
- let mut earliest_date: Option<DateTime<Utc>> = None;
- let mut latest_date: Option<DateTime<Utc>> = None;
- for message_id in &email_location.message_ids {
- let Some(ParsedMessage {
- internal_date_ts: Some(date),
- ..
- }) = msg_map.get(message_id)
- else {
- continue;
- };
- earliest_date = Some(earliest_date.map_or(*date, |existing| existing.min(*date)));
- latest_date = Some(latest_date.map_or(*date, |existing| existing.max(*date)));
- }
- // If we found specific dates, use them
- if earliest_date.is_some() || latest_date.is_some() {
- return Some((earliest_date, latest_date));
- }
- None
- })()
- .unwrap_or((fallback_span_start, fallback_span_end))
-}
-
-/// Extract user email addresses from messages based on the specific message IDs the LLM referenced
-fn calculate_user_email_addresses<T: InsightType>(
- insight: &T,
- messages_by_id: Option<&HashMap<String, &ParsedMessage>>,
- user_emails: &[String],
-) -> Option<Vec<String>> {
- // Try to get specific message IDs from the insight if it's an EmailInsight
- let SourceLocation::Email(email_location) = insight.source_location()?;
- let msg_map = messages_by_id?;
- let mut found_user_emails = std::collections::HashSet::new();
- for message_id in &email_location.message_ids {
- let Some(message) = msg_map.get(message_id) else {
- continue;
- };
- // Check from field
- if let Some(from) = &message.from
- && user_emails.contains(&from.email)
- {
- found_user_emails.insert(from.email.clone());
- }
- // Check to, cc, bcc fields
- for contact in &message.to {
- if user_emails.contains(&contact.email) {
- found_user_emails.insert(contact.email.clone());
- }
- }
- for contact in &message.cc {
- if user_emails.contains(&contact.email) {
- found_user_emails.insert(contact.email.clone());
- }
- }
- for contact in &message.bcc {
- if user_emails.contains(&contact.email) {
- found_user_emails.insert(contact.email.clone());
- }
- }
- }
- let mut emails: Vec<String> = found_user_emails.into_iter().collect();
- emails.sort(); // For consistent ordering
- if emails.is_empty() {
- return None;
- }
- Some(emails)
-}
-
-impl<T> Metadata for StructuredInsights<T>
-where
- T: InsightType,
-{
- fn description() -> Option<String> {
- Some("A list of insights generated from log context. Timestamps should always be taken directly from logs".to_string())
- }
-
- fn name() -> String {
- "Insights_Schema".to_string()
- }
-}
-
-#[derive(Serialize, Deserialize, JsonSchema, Debug)]
-#[serde(deny_unknown_fields)]
-pub struct Insight {
- pub insight_content: String,
- pub earliest_log_timestamp: String,
- pub latest_log_timestamp: String,
- pub confidence: i32,
- pub insight_type: String, // "actionable", "informational", "warning", "trend"
- pub relevance_keywords: Vec<String>,
-}
-
-impl InsightType for Insight {
- fn insight_content(&self) -> String {
- self.insight_content.clone()
- }
-
- fn source_location(&self) -> Option<SourceLocation> {
- None
- }
-
- fn confidence(&self) -> i32 {
- self.confidence
- }
-
- fn insight_type(&self) -> Option<model::insight_context::InsightType> {
- parse_insight_type(&self.insight_type)
- }
-
- fn relevance_keywords(&self) -> Option<Vec<String>> {
- Some(self.relevance_keywords.clone())
- }
-}
-
-#[derive(Serialize, Deserialize, JsonSchema, Debug)]
-#[serde(deny_unknown_fields)]
-pub struct EmailInsight {
- // false if deserialization failed
- pub success: bool,
- pub insight_content: String,
- pub thread_ids: Vec<String>,
- pub message_ids: Vec<String>,
- pub confidence: i32,
- pub insight_type: String, // "actionable", "informational", "warning", "trend"
- pub relevance_keywords: Vec<String>,
-}
-
-impl InsightType for EmailInsight {
- fn insight_content(&self) -> String {
- self.insight_content.clone()
- }
-
- fn source_location(&self) -> Option<SourceLocation> {
- match self.success {
- true => {
- let source_location = EmailSourceLocation {
- thread_ids: self.thread_ids.clone(),
- message_ids: self.message_ids.clone(),
- email_addresses: None,
- };
- Some(SourceLocation::Email(source_location))
- }
- false => None,
- }
- }
-
- fn confidence(&self) -> i32 {
- self.confidence
- }
-
- fn insight_type(&self) -> Option<model::insight_context::InsightType> {
- parse_insight_type(&self.insight_type)
- }
-
- fn relevance_keywords(&self) -> Option<Vec<String>> {
- Some(self.relevance_keywords.clone())
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use chrono::{DateTime, Utc};
- use models_email::email::service::address::ContactInfo;
- use schemars::JsonSchema;
-
- // Helper function to create test ParsedMessage
- fn create_test_message(id: &str, internal_date_ts: Option<DateTime<Utc>>) -> ParsedMessage {
- ParsedMessage {
- db_id: uuid::Uuid::parse_str(id).unwrap_or_else(|_| uuid::Uuid::new_v4()),
- link_id: uuid::Uuid::new_v4(),
- thread_db_id: uuid::Uuid::new_v4(),
- subject: Some("Test".to_string()),
- from: None,
- to: vec![],
- cc: vec![],
- bcc: vec![],
- labels: vec![],
- body_parsed: Some("Test body".to_string()),
- internal_date_ts,
- }
- }
-
- // Mock insight that implements InsightType for testing
- #[derive(serde::Deserialize, JsonSchema)]
- struct MockInsight {
- content: String,
- #[serde(skip)]
- source_location: Option<SourceLocation>,
- #[serde(skip)]
- confidence: Option<i32>,
- }
-
- impl InsightType for MockInsight {
- fn insight_content(&self) -> String {
- self.content.clone()
- }
-
- fn source_location(&self) -> Option<SourceLocation> {
- self.source_location.clone()
- }
-
- fn confidence(&self) -> i32 {
- self.confidence.unwrap_or(3)
- }
-
- fn insight_type(&self) -> Option<model::insight_context::InsightType> {
- None
- }
-
- fn relevance_keywords(&self) -> Option<Vec<String>> {
- None
- }
- }
-
- #[test]
- fn test_calculate_insight_span_dates_with_specific_messages() {
- let date1 = DateTime::parse_from_rfc3339("2023-01-01T10:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
- let date2 = DateTime::parse_from_rfc3339("2023-01-02T12:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
- let date3 = DateTime::parse_from_rfc3339("2023-01-03T14:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
-
- // Create test messages
- let msg1 = create_test_message("550e8400-e29b-41d4-a716-446655440001", Some(date1));
- let msg2 = create_test_message("550e8400-e29b-41d4-a716-446655440002", Some(date2));
- let msg3 = create_test_message("550e8400-e29b-41d4-a716-446655440003", Some(date3));
-
- // Create message map
- let mut messages_by_id = HashMap::new();
- messages_by_id.insert(msg1.db_id.to_string(), &msg1);
- messages_by_id.insert(msg2.db_id.to_string(), &msg2);
- messages_by_id.insert(msg3.db_id.to_string(), &msg3);
-
- // Create insight that references specific messages
- let insight = MockInsight {
- content: "Test insight".to_string(),
- source_location: Some(SourceLocation::Email(EmailSourceLocation {
- thread_ids: vec!["thread1".to_string()],
- message_ids: vec![
- msg1.db_id.to_string(),
- msg3.db_id.to_string(), // Skip msg2
- ],
- email_addresses: None,
- })),
- confidence: Some(3),
- };
-
- let fallback_start = DateTime::parse_from_rfc3339("2022-12-01T00:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
- let fallback_end = DateTime::parse_from_rfc3339("2023-12-01T00:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
-
- let (start, end) = calculate_insight_span_dates(
- &insight,
- Some(&messages_by_id),
- Some(fallback_start),
- Some(fallback_end),
- );
-
- // Should use specific messages (msg1 and msg3), not fallback dates
- assert_eq!(start, Some(date1)); // earliest from msg1 and msg3
- assert_eq!(end, Some(date3)); // latest from msg1 and msg3
- }
-
- #[test]
- fn test_calculate_insight_span_dates_fallback_to_chunk_dates() {
- let fallback_start = DateTime::parse_from_rfc3339("2023-01-01T00:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
- let fallback_end = DateTime::parse_from_rfc3339("2023-01-31T23:59:59Z")
- .unwrap()
- .with_timezone(&Utc);
-
- // Create insight with no source location (should use fallback)
- let insight = MockInsight {
- content: "Test insight".to_string(),
- source_location: None,
- confidence: Some(3),
- };
-
- let (start, end) =
- calculate_insight_span_dates(&insight, None, Some(fallback_start), Some(fallback_end));
-
- // Should use fallback dates
- assert_eq!(start, Some(fallback_start));
- assert_eq!(end, Some(fallback_end));
- }
-
- #[test]
- fn test_calculate_insight_span_dates_missing_messages() {
- let date1 = DateTime::parse_from_rfc3339("2023-01-01T10:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
- let msg1 = create_test_message("550e8400-e29b-41d4-a716-446655440001", Some(date1));
-
- let mut messages_by_id = HashMap::new();
- messages_by_id.insert(msg1.db_id.to_string(), &msg1);
-
- // Create insight that references messages not in the map
- let insight = MockInsight {
- content: "Test insight".to_string(),
- source_location: Some(SourceLocation::Email(EmailSourceLocation {
- thread_ids: vec!["thread1".to_string()],
- message_ids: vec!["nonexistent-message-id".to_string()],
- email_addresses: None,
- })),
- confidence: Some(3),
- };
-
- let fallback_start = DateTime::parse_from_rfc3339("2022-12-01T00:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
- let fallback_end = DateTime::parse_from_rfc3339("2023-12-01T00:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
-
- let (start, end) = calculate_insight_span_dates(
- &insight,
- Some(&messages_by_id),
- Some(fallback_start),
- Some(fallback_end),
- );
-
- // Should fall back to chunk dates since message wasn't found
- assert_eq!(start, Some(fallback_start));
- assert_eq!(end, Some(fallback_end));
- }
-
- #[test]
- fn test_calculate_insight_span_dates_uses_internal_date() {
- let internal_date = DateTime::parse_from_rfc3339("2023-01-01T08:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
-
- // Message with internal_date_ts
- let msg = create_test_message("550e8400-e29b-41d4-a716-446655440001", Some(internal_date));
-
- let mut messages_by_id = HashMap::new();
- messages_by_id.insert(msg.db_id.to_string(), &msg);
-
- let insight = MockInsight {
- content: "Test insight".to_string(),
- source_location: Some(SourceLocation::Email(EmailSourceLocation {
- thread_ids: vec!["thread1".to_string()],
- message_ids: vec![msg.db_id.to_string()],
- email_addresses: None,
- })),
- confidence: Some(3),
- };
-
- let (start, end) =
- calculate_insight_span_dates(&insight, Some(&messages_by_id), None, None);
-
- // Should use internal_date_ts
- assert_eq!(start, Some(internal_date));
- assert_eq!(end, Some(internal_date));
- }
-
- #[test]
- fn test_calculate_insight_span_dates_none_when_no_date() {
- // Message with no timestamp
- let msg = create_test_message("550e8400-e29b-41d4-a716-446655440001", None);
-
- let mut messages_by_id = HashMap::new();
- messages_by_id.insert(msg.db_id.to_string(), &msg);
-
- let insight = MockInsight {
- content: "Test insight".to_string(),
- source_location: Some(SourceLocation::Email(EmailSourceLocation {
- thread_ids: vec!["thread1".to_string()],
- message_ids: vec![msg.db_id.to_string()],
- email_addresses: None,
- })),
- confidence: Some(3),
- };
-
- let fallback_start = DateTime::parse_from_rfc3339("2022-12-01T00:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
- let fallback_end = DateTime::parse_from_rfc3339("2023-12-01T00:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
-
- let (start, end) = calculate_insight_span_dates(
- &insight,
- Some(&messages_by_id),
- Some(fallback_start),
- Some(fallback_end),
- );
-
- // Should fall back to chunk dates since message has no timestamp
- assert_eq!(start, Some(fallback_start));
- assert_eq!(end, Some(fallback_end));
- }
-
- #[test]
- fn test_into_insight_records_integration() {
- let date1 = DateTime::parse_from_rfc3339("2023-01-01T10:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
- let date2 = DateTime::parse_from_rfc3339("2023-01-03T14:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
-
- let msg1 = create_test_message("550e8400-e29b-41d4-a716-446655440001", Some(date1));
- let msg2 = create_test_message("550e8400-e29b-41d4-a716-446655440002", Some(date2));
-
- let mut messages_by_id = HashMap::new();
- messages_by_id.insert(msg1.db_id.to_string(), &msg1);
- messages_by_id.insert(msg2.db_id.to_string(), &msg2);
-
- // Create EmailInsight that references both messages
- let email_insight = EmailInsight {
- insight_content: "Test email insight".to_string(),
- thread_ids: vec!["thread1".to_string()],
- message_ids: vec![msg1.db_id.to_string(), msg2.db_id.to_string()],
- confidence: 4,
- success: true,
- insight_type: "informational".to_string(),
- relevance_keywords: vec!["test".to_string(), "email".to_string()],
- };
-
- let insights = StructuredInsights {
- insights: vec![email_insight],
- };
-
- let fallback_start = DateTime::parse_from_rfc3339("2022-01-01T00:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
- let fallback_end = DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
- .unwrap()
- .with_timezone(&Utc);
-
- let records = insights.into_insight_records(
- "email",
- "test_user",
- None,
- Some(fallback_start),
- Some(fallback_end),
- Some(&messages_by_id),
- None, // No user emails for this test
- );
-
- assert_eq!(records.len(), 1);
- let record = &records[0];
-
- // Should use precise dates from the specific messages, not fallback
- assert_eq!(record.span_start, Some(date1)); // earliest
- assert_eq!(record.span_end, Some(date2)); // latest
- assert_eq!(record.content, "Test email insight");
- assert_eq!(record.source, "email");
- assert_eq!(record.user_id, "test_user");
- }
-
- #[test]
- fn test_calculate_user_email_addresses() {
- let user_emails = vec![
- "[email protected]".to_string(),
- "[email protected]".to_string(),
- ];
-
- // Create test message with user emails in various fields
- let from_contact = ContactInfo {
- email: "[email protected]".to_string(),
- name: Some("User Name".to_string()),
- photo_url: None,
- };
- let to_contact = ContactInfo {
- email: "[email protected]".to_string(),
- name: Some("Other User".to_string()),
- photo_url: None,
- };
- let cc_contact = ContactInfo {
- email: "[email protected]".to_string(),
- name: Some("User Two".to_string()),
- photo_url: None,
- };
-
- let msg = ParsedMessage {
- db_id: uuid::Uuid::new_v4(),
- link_id: uuid::Uuid::new_v4(),
- thread_db_id: uuid::Uuid::new_v4(),
- subject: Some("Test Email".to_string()),
- from: Some(from_contact),
- to: vec![to_contact],
- cc: vec![cc_contact],
- bcc: vec![],
- labels: vec![],
- body_parsed: Some("Test body".to_string()),
- internal_date_ts: None,
- };
-
- // Create message map
- let mut messages_by_id = HashMap::new();
- messages_by_id.insert(msg.db_id.to_string(), &msg);
-
- // Create insight that references this message
- let insight = MockInsight {
- content: "Test insight".to_string(),
- source_location: Some(SourceLocation::Email(EmailSourceLocation {
- thread_ids: vec!["thread1".to_string()],
- message_ids: vec![msg.db_id.to_string()],
- email_addresses: None,
- })),
- confidence: Some(3),
- };
-
- // Test the function
- let result = calculate_user_email_addresses(&insight, Some(&messages_by_id), &user_emails);
-
- // Should find both user emails (from from field and cc field)
- assert!(result.is_some());
- let found_emails = result.unwrap();
- assert_eq!(found_emails.len(), 2);
- assert!(found_emails.contains(&"[email protected]".to_string()));
- assert!(found_emails.contains(&"[email protected]".to_string()));
- }
-
- #[test]
- fn test_calculate_user_email_addresses_no_user_emails() {
- let user_emails = vec!["[email protected]".to_string()];
-
- // Create test message with no user emails
- let from_contact = ContactInfo {
- email: "[email protected]".to_string(),
- name: Some("Other User".to_string()),
- photo_url: None,
- };
-
- let msg = ParsedMessage {
- db_id: uuid::Uuid::new_v4(),
- link_id: uuid::Uuid::new_v4(),
- thread_db_id: uuid::Uuid::new_v4(),
- subject: Some("Test Email".to_string()),
- from: Some(from_contact),
- to: vec![],
- cc: vec![],
- bcc: vec![],
- labels: vec![],
- body_parsed: Some("Test body".to_string()),
- internal_date_ts: None,
- };
-
- // Create message map
- let mut messages_by_id = HashMap::new();
- messages_by_id.insert(msg.db_id.to_string(), &msg);
-
- // Create insight that references this message
- let insight = MockInsight {
- content: "Test insight".to_string(),
- source_location: Some(SourceLocation::Email(EmailSourceLocation {
- thread_ids: vec!["thread1".to_string()],
- message_ids: vec![msg.db_id.to_string()],
- email_addresses: None,
- })),
- confidence: Some(3),
- };
-
- // Test the function
- let result = calculate_user_email_addresses(&insight, Some(&messages_by_id), &user_emails);
-
- // Should find no user emails
- assert!(result.is_none());
- }
-
- #[test]
- fn test_validate_confidence_score() {
- // Valid scores
- assert_eq!(validate_confidence_score(1), Some(1));
- assert_eq!(validate_confidence_score(2), Some(2));
- assert_eq!(validate_confidence_score(3), Some(3));
- assert_eq!(validate_confidence_score(4), Some(4));
- assert_eq!(validate_confidence_score(5), Some(5));
-
- // Invalid scores
- assert_eq!(validate_confidence_score(0), None);
- assert_eq!(validate_confidence_score(6), None);
- assert_eq!(validate_confidence_score(-1), None);
- assert_eq!(validate_confidence_score(100), None);
- }
-
- #[test]
- fn test_into_insight_records_with_invalid_confidence() {
- // Create mock insight with invalid confidence
- let insight = MockInsight {
- content: "Test insight with invalid confidence".to_string(),
- source_location: None,
- confidence: Some(10), // Invalid - should become None
- };
-
- let insights = StructuredInsights {
- insights: vec![insight],
- };
-
- let records =
- insights.into_insight_records("test", "test_user", None, None, None, None, None);
-
- assert_eq!(records.len(), 1);
- let record = &records[0];
-
- // Should have None confidence due to invalid score
- assert_eq!(record.confidence, None);
- assert_eq!(record.content, "Test insight with invalid confidence");
- }
-}
diff --git a/rust/cloud-storage/insight_service/src/insight/consumer/shared_prompts.rs b/rust/cloud-storage/insight_service/src/insight/consumer/shared_prompts.rs
deleted file mode 100644
index a6d4a6341a..0000000000
--- a/rust/cloud-storage/insight_service/src/insight/consumer/shared_prompts.rs
+++ /dev/null
@@ -1,17 +0,0 @@
-pub const CONFIDENCE_SCORING_PROMPT: &str = r#"For each insight, assign a confidence score from 1 to 5 that reflects not only how strongly supported the insight is by the underlying data (i.e., how confident we are it's true), but also how useful or actionable it would be to the end user.
-This score should blend the concepts of evidence strength and user value.
-Use the following scale:
- • 1 (Very Low Usefulness): The insight is highly speculative or based on minimal evidence. It is unlikely to be useful or meaningful to the user.
- • 2 (Low Usefulness): There is some indication supporting the insight, but it is uncertain or only weakly useful. The relevance to the user may be limited or unclear.
- • 3 (Moderate Usefulness): The insight has reasonable support and is somewhat useful to the user. It reflects a moderate pattern or behavior that could be informative but may not be highly impactful.
- • 4 (High Usefulness): The insight is well-supported by strong evidence and has clear potential value to the user. It likely reflects a real, recurring behavior or preference and could support better personalization or decision-making.
- • 5 (Very High Usefulness): The insight is supported by consistent and compelling evidence and would be highly valuable or actionable for the user. It reveals a meaningful pattern that could directly improve their experience or outcomes.
-Ensure each score reflects this combined notion of trustworthiness and user value, not just raw data confidence."#;
-
-pub const CLASSIFICATION_TYPES_PROMPT: &str = r#"Additionally, classify each insight into one of these types:
-- "actionable": Requires user action or decision-making (e.g., preferences that suggest specific actions)
-- "informational": Background information about user preferences or characteristics (e.g., demographic info, general preferences)
-- "warning": Potential issues, risks, or problems to be aware of (e.g., concerning patterns, security issues)
-- "trend": Pattern or trend analysis over time (e.g., changing behaviors, usage patterns)"#;
-
-pub const KEYWORDS_PROMPT: &str = r#"Also provide 3-5 relevant keywords that describe the main topics, themes, or concepts of the insight. These should be single words or short phrases that capture the essence of the insight for search and categorization purposes."#;
diff --git a/rust/cloud-storage/insight_service/src/insight/context_consumer_registry.rs b/rust/cloud-storage/insight_service/src/insight/context_consumer_registry.rs
deleted file mode 100644
index 49ea3f60f2..0000000000
--- a/rust/cloud-storage/insight_service/src/insight/context_consumer_registry.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-use super::consumer::ChatInsightContextConsumer;
-use super::consumer::InsightContextConsumer;
-use std::sync::Arc;
-
-// register consumers here
-pub fn create_consumers() -> Vec<Arc<dyn InsightContextConsumer>> {
- let chat_consumer: ChatInsightContextConsumer = ChatInsightContextConsumer;
- vec![Arc::new(chat_consumer)]
-}
diff --git a/rust/cloud-storage/insight_service/src/insight/context_router.rs b/rust/cloud-storage/insight_service/src/insight/context_router.rs
deleted file mode 100644
index 8b12b21c3c..0000000000
--- a/rust/cloud-storage/insight_service/src/insight/context_router.rs
+++ /dev/null
@@ -1,116 +0,0 @@
-use super::consumer::InsightContextConsumer;
-use super::context_consumer_registry::create_consumers;
-use model::insight_context::ProvidedContext;
-use std::collections::HashMap;
-use std::iter::IntoIterator;
-use std::sync::Arc;
-
-pub struct ContextRouter {
- consumers: HashMap<String, Arc<dyn InsightContextConsumer>>,
-}
-
-impl ContextRouter {
- pub fn default() -> Self {
- let consumers = create_consumers();
- Self::new(consumers)
- }
-
- pub fn new<T>(consumers: T) -> Self
- where
- T: IntoIterator<Item = Arc<dyn InsightContextConsumer>>,
- {
- let consumers = consumers
- .into_iter()
- .map(|consumer| (consumer.source_name(), consumer))
- .collect::<HashMap<_, _>>();
- Self { consumers }
- }
-
- pub fn route_context(
- &self,
- context: &ProvidedContext,
- ) -> Option<Arc<dyn InsightContextConsumer>> {
- self.consumers.get(&context.provider_source).map(Arc::clone)
- }
-}
-
-#[cfg(test)]
-mod test {
- use super::*;
- use crate::context::ServiceContext;
- use crate::insight::consumer::InsightContextConsumer;
- use model::insight_context::UserInsightRecord;
- use std::sync::Arc;
- struct MockConsumerChat;
- struct MockConsumerGoblin;
-
- #[async_trait::async_trait]
- impl InsightContextConsumer for MockConsumerChat {
- fn source_name(&self) -> String {
- "chat".to_string()
- }
- fn trigger_generation_at_n_messages(&self) -> usize {
- unimplemented!()
- }
- async fn generate_insights(
- &self,
- _: &[String],
- _: &str,
- _: &[UserInsightRecord],
- _: Arc<ServiceContext>,
- ) -> Result<Vec<UserInsightRecord>, anyhow::Error> {
- unimplemented!()
- }
- }
-
- #[async_trait::async_trait]
- impl InsightContextConsumer for MockConsumerGoblin {
- fn source_name(&self) -> String {
- "goblin".to_string()
- }
- fn trigger_generation_at_n_messages(&self) -> usize {
- unimplemented!()
- }
- async fn generate_insights(
- &self,
- _: &[String],
- _: &str,
- _: &[UserInsightRecord],
- _: Arc<ServiceContext>,
- ) -> Result<Vec<UserInsightRecord>, anyhow::Error> {
- unimplemented!()
- }
- }
- fn make_consumers() -> Vec<Arc<dyn InsightContextConsumer>> {
- vec![Arc::new(MockConsumerChat), Arc::new(MockConsumerGoblin)]
- }
-
- #[test]
- fn test_routing() -> Result<(), ()> {
- let router = ContextRouter::new(make_consumers());
- let chat_context = ProvidedContext {
- provider_source: "chat".to_string(),
- resource_id: "swag".to_string(),
- user_id: "nunya".to_string(),
- };
- let consumer = router.route_context(&chat_context);
- assert!(consumer.is_some(), "some consumer");
- assert_eq!(
- consumer.expect("what the freak").source_name().as_str(),
- "chat"
- );
- let dne = ProvidedContext {
- provider_source: "dne".to_string(),
- resource_id: "swag".to_string(),
- user_id: "nunya".to_string(),
- };
- assert!(router.route_context(&dne).is_none(), "no dne");
- let gob = ProvidedContext {
- provider_source: "goblin".to_string(),
- resource_id: "swag".to_string(),
- user_id: "nunya".to_string(),
- };
- assert!(router.route_context(&gob).is_some(), "yes gob");
- Ok(())
- }
-}
diff --git a/rust/cloud-storage/insight_service/src/insight/deduplication.rs b/rust/cloud-storage/insight_service/src/insight/deduplication.rs
deleted file mode 100644
index 297d9e07a1..0000000000
--- a/rust/cloud-storage/insight_service/src/insight/deduplication.rs
+++ /dev/null
@@ -1,477 +0,0 @@
-use anyhow::Result;
-use model::insight_context::UserInsightRecord;
-use sha2::{Digest, Sha256};
-use std::collections::{HashMap, HashSet};
-
-/// Configuration for deduplication behavior
-#[derive(Debug, Clone)]
-#[allow(dead_code)]
-pub struct DeduplicationConfig {
- /// Enable exact content hash matching
- pub exact_match_enabled: bool,
- /// Minimum similarity threshold for semantic comparison (0.0-1.0)
- pub semantic_similarity_threshold: f32,
- /// Maximum edit distance for fuzzy matching
- pub edit_distance_threshold: usize,
- /// Weight for source location overlap in similarity calculation
- pub source_location_weight: f32,
- /// Weight for confidence score difference in similarity calculation
- pub confidence_weight: f32,
- /// Enable LLM-based final decision for edge cases
- pub llm_fallback_enabled: bool,
-}
-
-impl Default for DeduplicationConfig {
- fn default() -> Self {
- Self {
- exact_match_enabled: true,
- semantic_similarity_threshold: 0.85,
- edit_distance_threshold: 10,
- source_location_weight: 0.3,
- confidence_weight: 0.2,
- llm_fallback_enabled: true,
- }
- }
-}
-
-/// Similarity metrics between two insights
-#[derive(Debug, Clone)]
-#[allow(dead_code)]
-pub struct SimilarityScore {
- pub exact_match: bool,
- pub content_similarity: f32,
- pub edit_distance: usize,
- pub token_overlap: f32,
- pub source_overlap: f32,
- pub confidence_diff: i32,
- pub overall_score: f32,
-}
-
-/// Multi-layer insight deduplication system
-pub struct InsightDeduplicator {
- config: DeduplicationConfig,
-}
-
-impl InsightDeduplicator {
- pub fn new(config: DeduplicationConfig) -> Self {
- Self { config }
- }
-
- /// Deduplicate insights using multi-layer approach
- pub async fn deduplicate_insights(
- &self,
- new_insights: &[UserInsightRecord],
- existing_insights: &[UserInsightRecord],
- ) -> Result<Vec<UserInsightRecord>> {
- let mut deduplicated = Vec::new();
- let existing_by_hash = self.build_hash_index(existing_insights);
-
- for new_insight in new_insights {
- if self
- .should_keep_insight(new_insight, existing_insights, &existing_by_hash)
- .await?
- {
- deduplicated.push(new_insight.clone());
- } else {
- tracing::debug!(
- insight_id = ?new_insight.id,
- content = %new_insight.content,
- "Insight filtered as duplicate"
- );
- }
- }
-
- Ok(deduplicated)
- }
-
- /// Determine if an insight should be kept based on similarity analysis
- async fn should_keep_insight(
- &self,
- new_insight: &UserInsightRecord,
- existing_insights: &[UserInsightRecord],
- existing_by_hash: &HashMap<String, &UserInsightRecord>,
- ) -> Result<bool> {
- // Layer 1: Exact content hash matching (fastest)
- if self.config.exact_match_enabled {
- let content_hash = self.calculate_content_hash(&new_insight.content);
- if existing_by_hash.contains_key(&content_hash) {
- tracing::debug!("Exact content match found, filtering duplicate");
- return Ok(false);
- }
- }
-
- // Layer 2: Find semantically similar insights
- let similar_insights = self.find_similar_insights(new_insight, existing_insights);
-
- if similar_insights.is_empty() {
- return Ok(true); // No similar insights found, keep it
- }
-
- // Layer 3: Analyze similarity scores
- let mut max_similarity = 0.0f32;
- let mut most_similar_insight = None;
-
- for (insight, similarity) in &similar_insights {
- if similarity.overall_score > max_similarity {
- max_similarity = similarity.overall_score;
- most_similar_insight = Some(*insight);
- }
- }
-
- // If similarity is below threshold, keep the insight
- if max_similarity < self.config.semantic_similarity_threshold {
- return Ok(true);
- }
-
- // Layer 4: LLM-based decision for edge cases (if enabled)
- if self.config.llm_fallback_enabled && max_similarity > 0.9 {
- return self
- .llm_deduplication_decision(new_insight, most_similar_insight.unwrap())
- .await;
- }
-
- // Filter high-similarity insights
- tracing::debug!(
- similarity_score = %max_similarity,
- threshold = %self.config.semantic_similarity_threshold,
- "Filtering insight based on similarity threshold"
- );
- Ok(false)
- }
-
- /// Build hash index for fast exact matching
- fn build_hash_index<'a>(
- &self,
- insights: &'a [UserInsightRecord],
- ) -> HashMap<String, &'a UserInsightRecord> {
- insights
- .iter()
- .map(|insight| (self.calculate_content_hash(&insight.content), insight))
- .collect()
- }
-
- /// Calculate normalized content hash
- fn calculate_content_hash(&self, content: &str) -> String {
- let normalized = self.normalize_content(content);
- let mut hasher = Sha256::new();
- hasher.update(normalized.as_bytes());
- format!("{:x}", hasher.finalize())
- }
-
- /// Normalize content for better comparison
- fn normalize_content(&self, content: &str) -> String {
- content
- .to_lowercase()
- .chars()
- .filter(|c| c.is_alphanumeric() || c.is_whitespace())
- .collect::<String>()
- .split_whitespace()
- .collect::<Vec<_>>()
- .join(" ")
- }
-
- /// Find insights with similarity above threshold
- fn find_similar_insights<'a>(
- &self,
- new_insight: &UserInsightRecord,
- existing_insights: &'a [UserInsightRecord],
- ) -> Vec<(&'a UserInsightRecord, SimilarityScore)> {
- existing_insights
- .iter()
- .map(|existing| (existing, self.calculate_similarity(new_insight, existing)))
- .filter(|(_, similarity)| similarity.overall_score > 0.5) // Pre-filter low similarity
- .collect()
- }
-
- /// Calculate comprehensive similarity score between two insights
- fn calculate_similarity(
- &self,
- insight1: &UserInsightRecord,
- insight2: &UserInsightRecord,
- ) -> SimilarityScore {
- let normalized1 = self.normalize_content(&insight1.content);
- let normalized2 = self.normalize_content(&insight2.content);
-
- // Exact match check
- let exact_match = normalized1 == normalized2;
-
- // Edit distance calculation
- let edit_distance = self.calculate_edit_distance(&normalized1, &normalized2);
-
- // Token overlap calculation
- let tokens1: HashSet<&str> = normalized1.split_whitespace().collect();
- let tokens2: HashSet<&str> = normalized2.split_whitespace().collect();
- let intersection_size = tokens1.intersection(&tokens2).count();
- let union_size = tokens1.union(&tokens2).count();
- let token_overlap = if union_size > 0 {
- intersection_size as f32 / union_size as f32
- } else {
- 0.0
- };
-
- // Content similarity based on token overlap and edit distance
- let max_len = normalized1.len().max(normalized2.len()) as f32;
- let content_similarity = if max_len > 0.0 {
- 1.0 - (edit_distance as f32 / max_len)
- } else {
- 0.0
- };
-
- // Source location overlap
- let source_overlap = self.calculate_source_overlap(insight1, insight2);
-
- // Confidence score difference
- let confidence_diff = match (insight1.confidence, insight2.confidence) {
- (Some(c1), Some(c2)) => (c1 - c2).abs(),
- _ => 0,
- };
-
- // Calculate weighted overall score
- // Base score from content and tokens, then boost from source overlap, then penalize for confidence diff
- let base_score = content_similarity * 0.6 + token_overlap * 0.4;
- let source_boost = source_overlap * self.config.source_location_weight;
- let confidence_penalty = (confidence_diff as f32 / 5.0) * self.config.confidence_weight;
- let overall_score = base_score + source_boost - confidence_penalty;
-
- SimilarityScore {
- exact_match,
- content_similarity,
- edit_distance,
- token_overlap,
- source_overlap,
- confidence_diff,
- overall_score: overall_score.clamp(0.0, 1.0),
- }
- }
-
- /// Calculate edit distance between two strings
- #[expect(
- clippy::needless_range_loop,
- reason = "clippy's suggestion here is bad"
- )]
- fn calculate_edit_distance(&self, s1: &str, s2: &str) -> usize {
- let len1 = s1.len();
- let len2 = s2.len();
- let mut matrix = vec![vec![0; len2 + 1]; len1 + 1];
-
- // Initialize first row and column
- for i in 0..=len1 {
- matrix[i][0] = i;
- }
- for j in 0..=len2 {
- matrix[0][j] = j;
- }
-
- // Fill the matrix
- for (i, c1) in s1.chars().enumerate() {
- for (j, c2) in s2.chars().enumerate() {
- let cost = if c1 == c2 { 0 } else { 1 };
- matrix[i + 1][j + 1] = std::cmp::min(
- std::cmp::min(
- matrix[i][j + 1] + 1, // Deletion
- matrix[i + 1][j] + 1, // Insertion
- ),
- matrix[i][j] + cost, // Substitution
- );
- }
- }
-
- matrix[len1][len2]
- }
-
- /// Calculate source location overlap
- fn calculate_source_overlap(
- &self,
- insight1: &UserInsightRecord,
- insight2: &UserInsightRecord,
- ) -> f32 {
- use model::insight_context::SourceLocation;
-
- match (&insight1.source_location, &insight2.source_location) {
- (Some(SourceLocation::Email(loc1)), Some(SourceLocation::Email(loc2))) => {
- let thread_overlap = self.calculate_set_overlap(&loc1.thread_ids, &loc2.thread_ids);
- let message_overlap =
- self.calculate_set_overlap(&loc1.message_ids, &loc2.message_ids);
- (thread_overlap + message_overlap) / 2.0
- }
- (None, None) => 0.0, // No location data
- _ => 0.0, // One has location, other doesn't, or different types
- }
- }
-
- /// Calculate overlap between two sets of strings
- fn calculate_set_overlap(&self, set1: &[String], set2: &[String]) -> f32 {
- if set1.is_empty() && set2.is_empty() {
- return 0.0;
- }
-
- let s1: HashSet<&String> = set1.iter().collect();
- let s2: HashSet<&String> = set2.iter().collect();
- let intersection_size = s1.intersection(&s2).count();
- let union_size = s1.union(&s2).count();
-
- if union_size > 0 {
- intersection_size as f32 / union_size as f32
- } else {
- 0.0
- }
- }
-
- /// LLM-based deduplication decision for edge cases
- async fn llm_deduplication_decision(
- &self,
- _new_insight: &UserInsightRecord,
- _existing_insight: &UserInsightRecord,
- ) -> Result<bool> {
- // TODO: Implement LLM call for edge cases
- // This would use a focused prompt comparing just two insights
- // For now, return conservative decision
- tracing::debug!(
- "LLM fallback deduplication not yet implemented, using conservative approach"
- );
- Ok(false) // Conservative: filter as duplicate
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use chrono::Utc;
- use model::insight_context::{EmailSourceLocation, SourceLocation};
-
- fn create_test_insight(content: &str, confidence: Option<i32>) -> UserInsightRecord {
- UserInsightRecord {
- id: None,
- user_id: "test_user".to_string(),
- content: content.to_string(),
- confidence,
- generated: true,
- created_at: Utc::now(),
- updated_at: Utc::now(),
- source: "test".to_string(),
- source_location: None,
- span_start: None,
- span_end: None,
- insight_type: None,
- relevance_keywords: None,
- }
- }
-
- #[test]
- fn test_exact_content_matching() {
- let deduplicator = InsightDeduplicator::new(DeduplicationConfig::default());
-
- let insight1 = create_test_insight("User prefers morning meetings", Some(4));
- let insight2 = create_test_insight("User prefers morning meetings", Some(4));
-
- let similarity = deduplicator.calculate_similarity(&insight1, &insight2);
- assert!(similarity.exact_match);
- assert!(similarity.overall_score > 0.9);
- }
-
- #[test]
- fn test_fuzzy_content_matching() {
- let deduplicator = InsightDeduplicator::new(DeduplicationConfig::default());
-
- let insight1 = create_test_insight("User prefers morning meetings", Some(4));
- let insight2 = create_test_insight("User likes morning meetings", Some(4));
-
- let similarity = deduplicator.calculate_similarity(&insight1, &insight2);
- assert!(!similarity.exact_match);
- assert!(similarity.overall_score > 0.7); // High similarity
- assert!(similarity.token_overlap >= 0.6);
- }
-
- #[test]
- fn test_different_insights() {
- let deduplicator = InsightDeduplicator::new(DeduplicationConfig::default());
-
- let insight1 = create_test_insight("User prefers morning meetings", Some(4));
- let insight2 = create_test_insight("User enjoys reading technical documentation", Some(3));
-
- let similarity = deduplicator.calculate_similarity(&insight1, &insight2);
- assert!(!similarity.exact_match);
- assert!(similarity.overall_score < 0.3); // Low similarity
- }
-
- #[test]
- fn test_source_location_overlap() {
- let deduplicator = InsightDeduplicator::new(DeduplicationConfig::default());
-
- let mut insight1 = create_test_insight("User prefers morning meetings", Some(4));
- let mut insight2 = create_test_insight("User likes morning meetings", Some(4));
-
- // Add overlapping source locations
- let source_loc = SourceLocation::Email(EmailSourceLocation {
- thread_ids: vec!["thread1".to_string(), "thread2".to_string()],
- message_ids: vec!["msg1".to_string()],
- email_addresses: None,
- });
-
- insight1.source_location = Some(source_loc.clone());
- insight2.source_location = Some(source_loc);
-
- let similarity = deduplicator.calculate_similarity(&insight1, &insight2);
- assert_eq!(similarity.source_overlap, 1.0); // Perfect overlap
- }
-
- #[tokio::test]
- async fn test_deduplication_pipeline() {
- let mut config = DeduplicationConfig::default();
- config.semantic_similarity_threshold = 0.5; // Lower threshold to catch the similar insight
- let deduplicator = InsightDeduplicator::new(config);
-
- let existing_insights = vec![
- create_test_insight("User prefers morning meetings", Some(4)),
- create_test_insight("User enjoys coding in Rust", Some(5)),
- ];
-
- let new_insights = vec![
- create_test_insight("User prefers morning meetings", Some(4)), // Exact duplicate
- create_test_insight("User likes morning meetings", Some(4)), // Similar (59% similarity)
- create_test_insight("User reads books in the evening", Some(3)), // Different - should be kept
- ];
-
- let result = deduplicator
- .deduplicate_insights(&new_insights, &existing_insights)
- .await
- .unwrap();
-
- // Should filter exact duplicate and similar insight, keep only the different one
- assert_eq!(result.len(), 1);
- assert!(result[0].content.contains("evening"));
- }
-
- #[tokio::test]
- async fn test_deduplication_with_more_similar_content() {
- let mut config = DeduplicationConfig::default();
- config.semantic_similarity_threshold = 0.8; // Lower threshold to catch the "improved" variant
- let deduplicator = InsightDeduplicator::new(config);
-
- let existing_insights = vec![create_test_insight(
- "User prefers morning meetings for better productivity",
- Some(4),
- )];
-
- let new_insights = vec![
- create_test_insight(
- "User prefers morning meetings for better productivity",
- Some(4),
- ), // Exact
- create_test_insight(
- "User prefers morning meetings for improved productivity",
- Some(4),
- ), // Very similar
- create_test_insight("User enjoys evening walks", Some(3)), // Different
- ];
-
- let result = deduplicator
- .deduplicate_insights(&new_insights, &existing_insights)
- .await
- .unwrap();
-
- // Should keep only the different insight
- assert_eq!(result.len(), 1);
- assert!(result[0].content.contains("evening"));
- }
-}
diff --git a/rust/cloud-storage/insight_service/src/insight/insight_context_handler.rs b/rust/cloud-storage/insight_service/src/insight/insight_context_handler.rs
deleted file mode 100644
index 8b8d999a07..0000000000
--- a/rust/cloud-storage/insight_service/src/insight/insight_context_handler.rs
+++ /dev/null
@@ -1,693 +0,0 @@
-use super::consumer::InsightContextConsumer;
-use crate::{
- context::ServiceContext,
- insight::consumer::generator::{
- generate_email_insights_for_messages, generate_email_insights_for_threads,
- },
-};
-use anyhow::Context;
-use macro_db_client::{insight, insights_backfill};
-use model::insight_context::{
- ProvidedContext,
- email_insights::{EmailInfo, GenerateEmailInsightContext},
-};
-use std::{collections::HashSet, sync::Arc};
-
-// TODO config
-const INSIGHT_LIMIT: i64 = 300;
-
-pub enum HandleContext {
- InsightsGenerated,
- NoAction,
-}
-
-pub async fn handle_context(
- service_context: Arc<ServiceContext>,
- context: ProvidedContext,
- consumer: Arc<dyn InsightContextConsumer>,
-) -> Result<HandleContext, anyhow::Error> {
- tracing::debug!("Handle context");
- // 1. save new peice of context
- insight::context::create_insight_context(&service_context.macro_db, &context)
- .await
- .context("failed to create context entry")?;
-
- tracing::debug!("Fetching unprocessed context");
- // 2. fetch unprocessed context
- let context_size = consumer.trigger_generation_at_n_messages();
- let (ids, entries) = insight::context::read_pending_context(
- &service_context.macro_db,
- &consumer.source_name(),
- &context.user_id,
- context_size as i64,
- )
- .await
- .context("failed to read pending context entries")?
- .into_iter()
- .collect::<(Vec<_>, Vec<_>)>();
- let resource_ids = entries
- .iter()
- .map(|swag| swag.resource_id.clone())
- .collect::<Vec<_>>();
- tracing::debug!("found pending context {}", ids.len());
-
- tracing::debug!("context fetched -> No action");
- // if there is not enough context exit
- if entries.len() < context_size {
- tracing::debug!("Not enough context");
- return Ok(HandleContext::NoAction);
- }
- tracing::debug!("context fetched -> fetching related insights");
- // else generate insights and mark context as consumed
- let related_insights = insight::user::read_insights_for_context(
- &service_context.macro_db,
- &context.user_id,
- consumer.source_name(),
- None, // No specific keywords for general insight generation
- true, // Prefer actionable insights for context
- INSIGHT_LIMIT as usize,
- )
- .await
- .context("failed to fetch related insights")?;
-
- tracing::debug!("context fetched -> generating new insights ...");
- let new_insights = consumer
- .generate_insights(
- &resource_ids,
- &context.user_id,
- &related_insights,
- service_context.clone(),
- )
- .await
- .context("insight generation failed")?
- .into_iter()
- .map(|mut insight| {
- insight.generated = true;
- insight.source = consumer.source_name();
- insight
- })
- .collect::<Vec<_>>();
-
- tracing::debug!("new insights generated ({:#?})", new_insights);
- tracing::debug!("writing insights");
-
- insight::context::mark_consumed(&service_context.macro_db, &ids)
- .await
- .context("failed to update insight context")?;
-
- let replace_ids = related_insights
- .into_iter()
- .filter_map(|insight| insight.id)
- .collect::<Vec<_>>();
-
- insight::user::replace_insights(
- &service_context.macro_db,
- &replace_ids,
- &new_insights,
- &context.user_id,
- )
- .await?;
-
- tracing::debug!("done");
- Ok(HandleContext::InsightsGenerated)
-}
-
-pub async fn handle_email_context(
- service_context: Arc<ServiceContext>,
- context: GenerateEmailInsightContext,
- sqs_message_id: Option<&str>,
-) -> Result<HandleContext, anyhow::Error> {
- match &context.info {
- EmailInfo::Backfill(batch) => {
- tracing::info!(
- user = %context.macro_user_id,
- user_emails = ?batch.user_emails,
- is_complete = %batch.is_complete,
- thread_count = batch.thread_ids.len(),
- "Processing email backfill batch"
- );
- let ids = match generate_email_insights_for_threads(
- service_context.clone(),
- &context.macro_user_id,
- &batch.user_emails,
- &batch.thread_ids,
- )
- .await
- {
- Ok(ids) => ids,
- Err(e) => {
- tracing::error!(error=?e, batch_id=%batch.batch_id, job_id=%batch.job_id, "Failed to generate insights");
-
- // Mark batch as failed
- if let Err(mark_err) = insights_backfill::batch::update::update_insights_backfill_batch_status(
- &service_context.macro_db,
- &batch.batch_id,
- model::insight_context::insights_backfill::InsightsBackfillBatchStatus::Failed,
- Some(&format!("Insight generation failed: {}", e)),
- sqs_message_id,
- ).await {
- tracing::error!(error=?mark_err, batch_id=%batch.batch_id, "Failed to mark batch as failed");
- }
-
- return Err(e);
- }
- };
-
- if ids.is_empty() {
- tracing::info!("no email user insights generated");
- return Ok(HandleContext::NoAction);
- }
-
- tracing::info!("email user insights generated with ids {:#?}", ids);
-
- // Handle backfill tracking - create job and batch if they don't exist, then update progress
- let job_id = &batch.job_id;
- let insights_generated_count = ids.len() as i32;
- let threads_processed_count = batch.thread_ids.len() as i32;
-
- // Ensure job exists (create if first batch for this job)
- if let Err(e) = ensure_backfill_job_exists(
- &service_context.macro_db,
- job_id,
- &context.macro_user_id,
- )
- .await
- {
- tracing::error!(error=?e, job_id=%job_id, "Failed to ensure job exists");
- // Continue processing even if job creation fails
- }
-
- // Handle batch-level tracking
- let batch_id = &batch.batch_id;
-
- // Ensure batch exists and mark as in progress
- if let Err(e) = ensure_batch_exists_and_start(
- &service_context.macro_db,
- batch_id,
- job_id,
- &batch.thread_ids,
- sqs_message_id,
- )
- .await
- {
- tracing::error!(error=?e, batch_id=%batch_id, job_id=%job_id, "Failed to ensure batch exists");
- }
-
- // Update batch results
- if let Err(e) = update_batch_results(
- &service_context.macro_db,
- batch_id,
- insights_generated_count,
- &ids,
- )
- .await
- {
- tracing::error!(error=?e, batch_id=%batch_id, "Failed to update batch results");
- }
-
- // Mark batch as complete
- if let Err(e) = mark_batch_complete(&service_context.macro_db, batch_id).await {
- tracing::error!(error=?e, batch_id=%batch_id, "Failed to mark batch as complete");
- }
-
- // Update job progress counters
- if let Err(e) = increment_job_progress(
- &service_context.macro_db,
- job_id,
- &context.macro_user_id,
- threads_processed_count,
- insights_generated_count,
- )
- .await
- {
- tracing::error!(error=?e, job_id=%job_id, "Failed to update job progress counters");
- }
-
- // If this is the last batch for the user, mark the job as complete
- if batch.is_complete
- && let Err(e) =
- mark_job_complete(&service_context.macro_db, job_id, &context.macro_user_id)
- .await
- {
- tracing::error!(error=?e, job_id=%job_id, "Failed to mark job as complete");
- }
-
- tracing::info!(
- job_id=%job_id,
- batch_id=%batch_id,
- user_id=%context.macro_user_id,
- insights_count=%insights_generated_count,
- threads_count=%threads_processed_count,
- is_complete=%batch.is_complete,
- "Updated backfill tracking"
- );
-
- Ok(HandleContext::InsightsGenerated)
- }
- EmailInfo::NewMessages(batch) => {
- let message_thread_ids = batch
- .messages
- .iter()
- .map(|m| (m.message_id.to_string(), m.thread_id.to_string()))
- .collect::<Vec<_>>();
- let user_emails: Vec<String> = batch
- .messages
- .iter()
- .map(|m| m.user_email.clone())
- .collect::<HashSet<_>>()
- .into_iter()
- .collect();
-
- tracing::info!(
- user = %context.macro_user_id,
- new_msgs = ?batch,
- message_thread_ids = ?message_thread_ids,
- user_emails = ?user_emails,
- "Processing email new messages batch"
- );
-
- let ids = generate_email_insights_for_messages(
- service_context,
- &context.macro_user_id,
- &user_emails,
- &message_thread_ids,
- )
- .await?;
-
- if ids.is_empty() {
- tracing::info!("no email user insights generated");
- return Ok(HandleContext::NoAction);
- }
-
- tracing::info!("email user insights generated with ids {:#?}", ids);
- Ok(HandleContext::InsightsGenerated)
- }
- EmailInfo::LinkDeleted(link_info) => {
- tracing::info!(
- context = ?context,
- "link deleted - link_id: {:?}, email: {:?}",
- link_info.link_id,
- link_info.email_address
- );
- Ok(HandleContext::NoAction)
- }
- }
-}
-
-/// Ensure a backfill job exists, creating it if it doesn't
-async fn ensure_backfill_job_exists(
- db: &sqlx::Pool<sqlx::Postgres>,
- job_id: &str,
- user_id: &str,
-) -> anyhow::Result<()> {
- // Check if this specific job already exists
- match insights_backfill::job::get::get_insights_backfill_job_by_id(db, job_id).await {
- Ok(Some(_)) => {
- // Job already exists
- tracing::debug!(job_id=%job_id, user_id=%user_id, "Job already exists");
- return Ok(());
- }
- Ok(None) => {
- // No job exists, create one
- }
- Err(e) => {
- tracing::warn!(error=?e, job_id=%job_id, user_id=%user_id, "Error checking for job, attempting to create");
- }
- }
-
- // Create the job with the provided job_id as the primary key
- let result =
- insights_backfill::job::insert::create_insights_backfill_job_with_id(db, job_id, user_id)
- .await;
-
- match result {
- Ok(()) => {
- tracing::info!(job_id=%job_id, user_id=%user_id, "Created backfill job");
- }
- Err(e) => {
- // Job might already exist due to concurrent processing
- tracing::warn!(error=?e, job_id=%job_id, user_id=%user_id, "Failed to create job (may already exist)");
- }
- }
-
- Ok(())
-}
-
-/// Increment job progress counters
-async fn increment_job_progress(
- db: &sqlx::Pool<sqlx::Postgres>,
- job_id: &str,
- user_id: &str,
- threads_processed: i32,
- insights_generated: i32,
-) -> anyhow::Result<()> {
- // Update the specific job by its ID
- match insights_backfill::job::update::increment_insights_backfill_job_results(
- db,
- job_id,
- threads_processed,
- insights_generated,
- )
- .await
- {
- Ok(()) => {
- tracing::debug!(
- job_id=%job_id,
- user_id=%user_id,
- threads_processed=%threads_processed,
- insights_generated=%insights_generated,
- "Incremented job progress"
- );
- }
- Err(e) => {
- tracing::error!(error=?e, job_id=%job_id, user_id=%user_id, "Failed to increment job progress");
- return Err(e);
- }
- }
-
- Ok(())
-}
-
-/// Mark job as complete if this is the final batch
-async fn mark_job_complete(
- db: &sqlx::Pool<sqlx::Postgres>,
- job_id: &str,
- user_id: &str,
-) -> anyhow::Result<()> {
- // Update the specific job by its ID
- match insights_backfill::job::update::update_insights_backfill_job_status(
- db,
- job_id,
- model::insight_context::insights_backfill::InsightsBackfillJobStatus::Complete,
- )
- .await
- {
- Ok(()) => {
- tracing::info!(job_id=%job_id, user_id=%user_id, "Marked backfill job as complete");
- }
- Err(e) => {
- tracing::error!(error=?e, job_id=%job_id, user_id=%user_id, "Failed to mark job as complete");
- return Err(e);
- }
- }
-
- Ok(())
-}
-
-/// Ensure a batch exists and mark it as in progress
-async fn ensure_batch_exists_and_start(
- db: &sqlx::Pool<sqlx::Postgres>,
- batch_id: &str,
- job_id: &str,
- thread_ids: &[String],
- sqs_message_id: Option<&str>,
-) -> anyhow::Result<()> {
- use model::insight_context::insights_backfill::InsightsBackfillBatchStatus;
-
- // Check if batch already exists
- match insights_backfill::batch::get::get_insights_backfill_batch_by_id(db, batch_id).await {
- Ok(Some(batch)) => {
- // Batch exists, mark as in progress if not already
- if batch.status != InsightsBackfillBatchStatus::InProgress {
- insights_backfill::batch::update::update_insights_backfill_batch_status(
- db,
- batch_id,
- InsightsBackfillBatchStatus::InProgress,
- None,
- None,
- )
- .await?;
- tracing::debug!(batch_id=%batch_id, "Marked existing batch as in progress");
- }
- }
- Ok(None) => {
- // Create new batch
- insights_backfill::batch::insert::create_insights_backfill_batch_with_id(
- db,
- batch_id,
- job_id,
- thread_ids,
- sqs_message_id,
- )
- .await?;
-
- // Immediately mark as in progress
- insights_backfill::batch::update::update_insights_backfill_batch_status(
- db,
- batch_id,
- InsightsBackfillBatchStatus::InProgress,
- None,
- sqs_message_id,
- )
- .await?;
-
- tracing::info!(batch_id=%batch_id, job_id=%job_id, "Created and started batch");
- }
- Err(e) => {
- tracing::warn!(error=?e, batch_id=%batch_id, "Error checking for batch, attempting to create");
-
- // Try to create the batch, but handle duplicate key errors gracefully
- match insights_backfill::batch::insert::create_insights_backfill_batch_with_id(
- db,
- batch_id,
- job_id,
- thread_ids,
- sqs_message_id,
- )
- .await
- {
- Ok(()) => {
- // Successfully created, mark as in progress
- if let Err(update_err) =
- insights_backfill::batch::update::update_insights_backfill_batch_status(
- db,
- batch_id,
- InsightsBackfillBatchStatus::InProgress,
- None,
- None,
- )
- .await
- {
- tracing::warn!(error=?update_err, batch_id=%batch_id, "Failed to mark newly created batch as in progress");
- } else {
- tracing::info!(batch_id=%batch_id, job_id=%job_id, "Created and started batch after error");
- }
- }
- Err(create_err) => {
- // Check if it's a duplicate key error
- if create_err
- .to_string()
- .contains("duplicate key value violates unique constraint")
- {
- tracing::info!(batch_id=%batch_id, "Batch already exists (duplicate key), attempting to mark as in progress");
- // Batch already exists, try to mark it as in progress
- if let Err(update_err) =
- insights_backfill::batch::update::update_insights_backfill_batch_status(
- db,
- batch_id,
- InsightsBackfillBatchStatus::InProgress,
- None,
- None,
- )
- .await
- {
- tracing::warn!(error=?update_err, batch_id=%batch_id, "Failed to mark existing batch as in progress");
- }
- } else {
- tracing::error!(error=?create_err, batch_id=%batch_id, "Failed to create batch with non-duplicate error");
- return Err(create_err);
- }
- }
- }
- }
- }
-
- Ok(())
-}
-
-/// Update batch results with insights generated count and insight IDs
-async fn update_batch_results(
- db: &sqlx::Pool<sqlx::Postgres>,
- batch_id: &str,
- insights_generated_count: i32,
- insight_ids: &[String],
-) -> anyhow::Result<()> {
- insights_backfill::batch::update::update_insights_backfill_batch_results(
- db,
- batch_id,
- insights_generated_count,
- insight_ids.to_vec(),
- )
- .await?;
-
- tracing::debug!(batch_id=%batch_id, insights_generated_count=%insights_generated_count, insight_ids=?insight_ids, "Updated batch results");
- Ok(())
-}
-
-/// Mark batch as complete
-async fn mark_batch_complete(
- db: &sqlx::Pool<sqlx::Postgres>,
- batch_id: &str,
-) -> anyhow::Result<()> {
- use model::insight_context::insights_backfill::InsightsBackfillBatchStatus;
-
- insights_backfill::batch::update::update_insights_backfill_batch_status(
- db,
- batch_id,
- InsightsBackfillBatchStatus::Complete,
- None,
- None,
- )
- .await?;
-
- tracing::info!(batch_id=%batch_id, "Marked batch as complete");
- Ok(())
-}
-
-#[cfg(test)]
-mod test {
- use super::*;
- use crate::insight::consumer::ChatInsightContextConsumer;
- use chrono::Utc;
- use document_cognition_service_client::DocumentCognitionServiceClient;
- use document_storage_service_client::DocumentStorageServiceClient;
- use email_service_client::EmailServiceClient;
- use lexical_client::LexicalClient;
- use model::insight_context::UserInsightRecord;
- use scribe::{ScribeClient, document::DocumentClient};
- use sqlx::{Pool, Postgres};
- use std::sync::Arc;
- use sync_service_client::SyncServiceClient;
- pub struct MockChatInsightConsumer;
-
- pub fn service_context_test_with_macro_db(macro_db: Pool<Postgres>) -> ServiceContext {
- let bad_dss = DocumentStorageServiceClient::new(String::new(), String::new());
- let bad_sync_service = SyncServiceClient::new(String::new(), String::new());
- let bad_email = EmailServiceClient::new(String::new(), String::new());
- let bad_dcs = DocumentCognitionServiceClient::new(String::new(), String::new());
- let bad_lexical = LexicalClient::new(String::new(), String::new());
- let content_client = ScribeClient::new()
- .with_document_client(
- DocumentClient::builder()
- .with_dss_client(bad_dss)
- .with_lexical_client(bad_lexical)
- .with_sync_service_client(bad_sync_service)
- .build(),
- )
- .with_email_client(bad_email)
- .with_dcs_client(bad_dcs);
- ServiceContext {
- macro_db,
- content_client,
- }
- }
-
- #[async_trait::async_trait]
- impl InsightContextConsumer for MockChatInsightConsumer {
- fn source_name(&self) -> String {
- ChatInsightContextConsumer.source_name()
- }
- fn trigger_generation_at_n_messages(&self) -> usize {
- ChatInsightContextConsumer.trigger_generation_at_n_messages()
- }
-
- async fn generate_insights(
- &self,
- _: &[String],
- user_id: &str,
- _: &[UserInsightRecord],
- _: Arc<ServiceContext>,
- ) -> Result<Vec<UserInsightRecord>, anyhow::Error> {
- let now = Utc::now();
- Ok(vec![UserInsightRecord {
- id: None,
- confidence: None,
- content: "test".to_string(),
- created_at: now,
- updated_at: now,
- generated: false,
- source: "swag".to_string(),
- source_location: None,
- span_end: None,
- span_start: None,
- user_id: user_id.to_string(),
- insight_type: None,
- relevance_keywords: None,
- }])
- }
- }
-
- #[sqlx::test(fixtures(path = "../../fixtures", scripts("users")))]
- async fn test_chat_context(db: Pool<Postgres>) -> Result<(), anyhow::Error> {
- let consumer: Arc<dyn InsightContextConsumer> = Arc::new(MockChatInsightConsumer);
- let service_context = Arc::new(service_context_test_with_macro_db(db));
- let trigger_at_limit = consumer.trigger_generation_at_n_messages();
- let user_id = "macro|[email protected]".to_string();
- let context = ProvidedContext {
- provider_source: consumer.source_name(),
- resource_id: "c1".to_string(),
- user_id: user_id.clone(),
- };
- for _ in 0..trigger_at_limit - 1 {
- let result = handle_context(service_context.clone(), context.clone(), consumer.clone())
- .await
- .expect("handle context - no action");
- assert!(
- matches!(result, HandleContext::NoAction),
- "expected no action"
- );
- }
-
- let result = handle_context(service_context.clone(), context.clone(), consumer.clone())
- .await
- .expect("handle context - generate");
-
- assert!(matches!(result, HandleContext::InsightsGenerated));
-
- let unconsumed = insight::context::read_pending_context(
- &service_context.macro_db,
- consumer.source_name().as_str(),
- user_id.as_str(),
- 10000,
- )
- .await
- .expect("context");
-
- assert!(unconsumed.is_empty());
-
- let result = handle_context(service_context.clone(), context.clone(), consumer.clone())
- .await
- .expect("handle context - no action (2)");
-
- assert!(matches!(result, HandleContext::NoAction));
-
- let unconsumed = insight::context::read_pending_context(
- &service_context.macro_db,
- consumer.source_name().as_str(),
- user_id.as_str(),
- 10000,
- )
- .await
- .expect("context");
-
- assert_eq!(unconsumed.len(), 1, "one peice of unconsumed context");
- let insights = insight::user::read_recent_insights(
- &service_context.macro_db,
- &user_id,
- 1000,
- consumer.source_name(),
- )
- .await
- .expect("generated insights");
-
- assert_eq!(insights.len(), 1, "one generated insight");
-
- let insight = insights.first().expect("fist insight");
-
- assert_eq!(insight.content, "test".to_string(), "content");
- assert!(insight.generated, "generated");
- assert_eq!(insight.source, ChatInsightContextConsumer.source_name());
-
- Ok(())
- }
-}
diff --git a/rust/cloud-storage/insight_service/src/insight/mod.rs b/rust/cloud-storage/insight_service/src/insight/mod.rs
deleted file mode 100644
index b23f46c27d..0000000000
--- a/rust/cloud-storage/insight_service/src/insight/mod.rs
+++ /dev/null
@@ -1,50 +0,0 @@
-pub mod batch_processor;
-pub mod consumer;
-pub mod context_consumer_registry;
-pub mod context_router;
-pub mod deduplication;
-pub mod insight_context_handler;
-pub mod queue;
-pub mod smart_ranking;
-
-use crate::config::{Config, Environment};
-use crate::context::ServiceContext;
-use aws_sdk_sqs::Client;
-use queue::ContextQueue;
-use sqs_worker::SQSWorker;
-
-pub async fn setup_and_poll(config: Config) {
- let context_router = context_router::ContextRouter::default();
- let sqs_worker = make_sqs_worker(&config).await;
- let context_config = ServiceContext::try_from_config(&config)
- .await
- .expect("context config failed to initialize");
- let queue = ContextQueue::new(sqs_worker, context_config, context_router);
- queue.poll().await;
-}
-
-async fn make_sqs_worker(config: &Config) -> SQSWorker {
- let conf = match config.environment {
- Environment::Local => {
- aws_config::defaults(aws_config::BehaviorVersion::latest())
- .region("us-east-1")
- .endpoint_url(&config.queue_url)
- .load()
- .await
- }
- _ => {
- aws_config::defaults(aws_config::BehaviorVersion::latest())
- .region("us-east-1")
- .load()
- .await
- }
- };
-
- let client = Client::new(&conf);
- sqs_worker::SQSWorker::new(
- client,
- config.queue_url.clone(),
- config.queue_max_messages as i32,
- config.queue_wait_time_seconds as i32,
- )
-}
diff --git a/rust/cloud-storage/insight_service/src/insight/queue.rs b/rust/cloud-storage/insight_service/src/insight/queue.rs
deleted file mode 100644
index 507cc938c3..0000000000
--- a/rust/cloud-storage/insight_service/src/insight/queue.rs
+++ /dev/null
@@ -1,176 +0,0 @@
-use super::context_router::ContextRouter;
-use crate::{
- context::ServiceContext,
- insight::insight_context_handler::{handle_context, handle_email_context},
-};
-use anyhow::Context;
-use aws_sdk_sqs::types::Message;
-use macro_db_client::insights_backfill::job::update::update_insights_backfill_job_status;
-use model::insight_context::insights_backfill::InsightsBackfillJobStatus;
-use model::insight_context::{InsightContextQueueMessage, email_insights::EmailInfo};
-use sqs_worker::SQSWorker;
-use std::sync::Arc;
-
-fn message_from_str(body: &str) -> Result<InsightContextQueueMessage, anyhow::Error> {
- serde_json::from_str(body).context("deserialize error")
-}
-
-fn message_from_sqs_message(
- msg: &aws_sdk_sqs::types::Message,
-) -> Result<InsightContextQueueMessage, anyhow::Error> {
- msg.body()
- .ok_or_else(|| anyhow::anyhow!("no message body"))
- .and_then(message_from_str)
-}
-
-pub struct ContextQueue {
- inner: Arc<SQSWorker>,
- context_router: ContextRouter,
- service_context: Arc<ServiceContext>,
-}
-
-impl ContextQueue {
- pub fn new(
- worker: SQSWorker,
- context_config: ServiceContext,
- context_router: ContextRouter,
- ) -> Self {
- Self {
- inner: Arc::new(worker),
- context_router,
- service_context: Arc::new(context_config),
- }
- }
-
- #[tracing::instrument(skip(self))]
- pub async fn poll(&self) {
- tracing::debug!("Polling Start");
- loop {
- tracing::trace!("Poll");
- match self.inner.receive_messages().await {
- Ok(messages) => {
- if messages.is_empty() {
- tracing::trace!("no messages found");
- continue;
- }
- for message in messages {
- let _ = self.handle_message(message).await;
- }
- }
- Err(e) => tracing::trace!(error =? e, "error receiving messages"),
- }
- }
- }
-
- #[tracing::instrument(skip(self))]
- async fn handle_message(&self, message: Message) -> Result<(), ()> {
- tracing::debug!("MESSAGE RECIEVED\n{:?}", message);
- let context_message = message_from_sqs_message(&message).map_err(|e| {
- tracing::error!(error =? e, sqx_message=?message, "Malformed SQS message");
- })?;
-
- match context_message {
- // its context
- InsightContextQueueMessage::Context(context) => {
- // find a context consumer
- let context_consumer = self
- .context_router
- .route_context(&context)
- .ok_or_else(|| {
- anyhow::anyhow!("Router could not find a consumer for provided context")
- })
- .map_err(|e| {
- tracing::error!(error=?e, provided_context=?context);
- })?;
-
- // clone stuff
- let sqs_worker_clone = Arc::clone(&self.inner);
- let consumer_clone = Arc::clone(&context_consumer);
- let service_context = Arc::clone(&self.service_context);
-
- // start task
- tokio::spawn(async move {
- match handle_context(service_context, context, consumer_clone.clone()).await {
- Ok(_) => {
- sqs_worker_clone.cleanup_message(&message).await.ok();
- }
- Err(e) => {
- tracing::error!(error=?e, "context handler exited with an error");
- }
- }
- });
- }
- InsightContextQueueMessage::Email { context } => {
- let sqs_worker_clone = Arc::clone(&self.inner);
- let service_context = Arc::clone(&self.service_context);
- let service_context_clone = Arc::clone(&service_context);
- let context_clone = context.clone();
- tokio::spawn(async move {
- match handle_email_context(service_context, context, message.message_id()).await
- {
- Ok(_) => {
- sqs_worker_clone.cleanup_message(&message).await.ok();
- }
- Err(e) => {
- if let EmailInfo::Backfill(batch) = &context_clone.info {
- tracing::error!(error=?e, "email context handler exited with an error for job {}", batch.job_id);
- if let Err(e) = update_insights_backfill_job_status(
- &service_context_clone.macro_db,
- &batch.job_id,
- InsightsBackfillJobStatus::Failed,
- )
- .await
- {
- tracing::error!(error=?e, "failed to add job {} to db", batch.job_id);
- }
- } else {
- tracing::error!(error=?e, "email context handler exited with an error");
- }
- sqs_worker_clone.cleanup_message(&message).await.ok();
- }
- }
- });
- }
- InsightContextQueueMessage::Test { .. } => {
- self.inner.cleanup_message(&message).await.ok();
- }
- }
- Ok(())
- }
-}
-
-#[cfg(test)]
-mod test {
- use super::*;
- use model::insight_context::InsightContextQueueMessage;
-
- fn make_sqs_message() -> aws_sdk_sqs::types::Message {
- let message = include_str!("../../tests/chat_context.json");
- aws_sdk_sqs::types::Message::builder()
- .set_body(Some(message.to_string()))
- .build()
- }
-
- #[test]
- fn test_deserialize_message() {
- let message_json: &'static str = include_str!("../../tests/chat_context.json");
- let message = message_from_str(message_json);
- assert!(message.is_ok());
- }
-
- #[tokio::test]
- async fn test_context_message_from_sqs_queue() {
- let message = make_sqs_message();
- let parsed = message_from_sqs_message(&message);
- assert!(parsed.is_ok());
- let parsed_message = parsed.unwrap();
-
- #[allow(irrefutable_let_patterns)]
- if let InsightContextQueueMessage::Context(context) = parsed_message {
- assert_eq!(context.provider_source, "chat".to_string());
- assert_eq!(context.user_id, "fake|user.com");
- } else {
- panic!("message does not match\n{:?}", parsed_message);
- }
- }
-}
diff --git a/rust/cloud-storage/insight_service/src/insight/smart_ranking.rs b/rust/cloud-storage/insight_service/src/insight/smart_ranking.rs
deleted file mode 100644
index 08409b45e7..0000000000
--- a/rust/cloud-storage/insight_service/src/insight/smart_ranking.rs
+++ /dev/null
@@ -1,292 +0,0 @@
-use chrono::{DateTime, Duration, Utc};
-use model::insight_context::{InsightType, UserInsightRecord};
-
-/// Default characters per token estimation
-const DEFAULT_CHARS_PER_TOKEN: usize = 4;
-
-/// Get characters per token from environment or use default
-fn get_chars_per_token() -> usize {
- std::env::var("INSIGHT_CHARS_PER_TOKEN_ESTIMATE")
- .ok()
- .and_then(|s| s.parse().ok())
- .unwrap_or(DEFAULT_CHARS_PER_TOKEN)
-}
-
-#[derive(Debug, Clone)]
-pub struct RankingContext {
- pub current_time: DateTime<Utc>,
- pub query_keywords: Option<Vec<String>>, // keywords to match against relevance_keywords
- pub max_insights: usize,
- pub prefer_actionable: bool, // prioritize actionable insights
-}
-
-impl Default for RankingContext {
- fn default() -> Self {
- Self {
- current_time: Utc::now(),
- query_keywords: None,
- max_insights: 20,
- prefer_actionable: false,
- }
- }
-}
-
-#[derive(Debug, Clone)]
-#[allow(dead_code)]
-pub struct InsightScore {
- pub insight_id: String,
- pub total_score: f32,
- pub breakdown: ScoreBreakdown,
-}
-
-#[derive(Debug, Clone)]
-#[allow(dead_code)]
-pub struct ScoreBreakdown {
- pub recency_score: f32,
- pub confidence_score: f32,
- pub type_bonus: f32,
- pub keyword_match_score: f32,
-}
-
-/// Smart insight ranking algorithm for LLM context selection
-pub fn rank_insights_for_context(
- insights: &[UserInsightRecord],
- context: &RankingContext,
-) -> Vec<InsightScore> {
- let mut scores: Vec<InsightScore> = insights
- .iter()
- .map(|insight| calculate_insight_score(insight, context))
- .collect();
-
- // Sort by total score descending
- scores.sort_by(|a, b| b.total_score.partial_cmp(&a.total_score).unwrap());
-
- // Return top N insights
- scores.into_iter().take(context.max_insights).collect()
-}
-
-fn calculate_insight_score(insight: &UserInsightRecord, context: &RankingContext) -> InsightScore {
- let recency_score = calculate_recency_score(insight, context.current_time);
- let confidence_score = insight.confidence.unwrap_or(50) as f32 / 100.0;
- let type_bonus = calculate_type_bonus(insight, context);
- let keyword_match_score = calculate_keyword_match_score(insight, context);
-
- // Simple weighted combination: confidence + recency + type + keywords
- let total_score = (confidence_score * 0.4) + // Most important: how confident/accurate
- (recency_score * 0.3) + // Second: how recent
- (type_bonus * 0.2) + // Third: insight type (actionable > warning > info)
- (keyword_match_score * 0.1); // Fourth: keyword relevance
-
- InsightScore {
- insight_id: insight.id.clone().unwrap_or_default(),
- total_score,
- breakdown: ScoreBreakdown {
- recency_score,
- confidence_score,
- type_bonus,
- keyword_match_score,
- },
- }
-}
-
-fn calculate_recency_score(insight: &UserInsightRecord, current_time: DateTime<Utc>) -> f32 {
- // prefer span_start over created_at since it represents the insight source creation time (not the insight creation time)
- let age = current_time.signed_duration_since(insight.span_start.unwrap_or(insight.created_at));
-
- // Decay function: newer insights score higher
- if age <= Duration::days(1) {
- 1.0
- } else if age <= Duration::days(7) {
- 0.8
- } else if age <= Duration::days(30) {
- 0.6
- } else if age <= Duration::days(90) {
- 0.4
- } else {
- 0.2
- }
-}
-
-fn calculate_type_bonus(insight: &UserInsightRecord, context: &RankingContext) -> f32 {
- match &insight.insight_type {
- Some(InsightType::Actionable) => {
- if context.prefer_actionable {
- 1.0
- } else {
- 0.8
- }
- }
- Some(InsightType::Warning) => 0.7,
- Some(InsightType::Trend) => 0.6,
- Some(InsightType::Informational) => 0.5,
- None => 0.5, // Default for unclassified insights
- }
-}
-
-fn calculate_keyword_match_score(insight: &UserInsightRecord, context: &RankingContext) -> f32 {
- let Some(query_keywords) = &context.query_keywords else {
- return 0.5; // Default score when no keywords to match
- };
-
- let Some(insight_keywords) = &insight.relevance_keywords else {
- return 0.3; // Lower score for insights without keywords
- };
-
- // Simple keyword matching - count how many query keywords match insight keywords
- let matches = query_keywords
- .iter()
- .filter(|query_kw| {
- insight_keywords
- .iter()
- .any(|insight_kw| insight_kw.to_lowercase().contains(&query_kw.to_lowercase()))
- })
- .count();
-
- if matches == 0 {
- 0.2
- } else {
- // Score based on match ratio (capped at 1.0)
- (matches as f32 / query_keywords.len() as f32).min(1.0)
- }
-}
-
-/// Select best insights considering token budget constraints
-pub fn select_insights_for_llm_context(
- insights: &[UserInsightRecord],
- context: &RankingContext,
- max_tokens: usize,
-) -> Vec<UserInsightRecord> {
- let ranked_scores = rank_insights_for_context(insights, context);
- let mut selected_insights = Vec::new();
- let mut token_count = 0;
-
- for score in ranked_scores {
- if let Some(insight) = insights
- .iter()
- .find(|i| i.id.as_ref() == Some(&score.insight_id))
- {
- // Configurable token estimation
- let insight_tokens = insight.content.len() / get_chars_per_token();
-
- if token_count + insight_tokens <= max_tokens {
- selected_insights.push(insight.clone());
- token_count += insight_tokens;
- } else {
- break;
- }
- }
- }
-
- selected_insights
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use chrono::Utc;
-
- #[test]
- fn test_recency_scoring() {
- let now = Utc::now();
- let insight = UserInsightRecord {
- id: Some("test".to_string()),
- user_id: "user1".to_string(),
- content: "test insight".to_string(),
- created_at: now - Duration::hours(2),
- updated_at: now,
- confidence: Some(80),
- generated: true,
- source: "email".to_string(),
- source_location: None,
- span_start: None,
- span_end: None,
- insight_type: None,
- relevance_keywords: None,
- };
-
- let score = calculate_recency_score(&insight, now);
- assert_eq!(score, 1.0); // Should be max score for recent insight
- }
-
- #[test]
- fn test_insight_ranking() {
- let insights = vec![
- UserInsightRecord {
- id: Some("high_conf".to_string()),
- confidence: Some(90),
- created_at: Utc::now() - Duration::hours(1),
- content: "High confidence insight".to_string(),
- user_id: "user1".to_string(),
- updated_at: Utc::now(),
- generated: true,
- source: "email".to_string(),
- source_location: None,
- span_start: None,
- span_end: None,
- insight_type: Some(InsightType::Actionable),
- relevance_keywords: Some(vec!["email".to_string(), "urgent".to_string()]),
- },
- UserInsightRecord {
- id: Some("low_conf".to_string()),
- confidence: Some(30),
- created_at: Utc::now() - Duration::days(1),
- content: "Low confidence insight".to_string(),
- user_id: "user1".to_string(),
- updated_at: Utc::now(),
- generated: true,
- source: "email".to_string(),
- source_location: None,
- span_start: None,
- span_end: None,
- insight_type: Some(InsightType::Informational),
- relevance_keywords: None,
- },
- ];
-
- let context = RankingContext {
- current_time: Utc::now(),
- query_keywords: Some(vec!["email".to_string()]),
- max_insights: 2,
- prefer_actionable: true,
- };
-
- let ranked = rank_insights_for_context(&insights, &context);
-
- // High confidence + recent + actionable type + keyword match should rank higher
- assert!(ranked[0].total_score > ranked[1].total_score);
- assert_eq!(ranked[0].insight_id, "high_conf");
- }
-
- #[test]
- fn test_keyword_matching() {
- let insight = UserInsightRecord {
- id: Some("test".to_string()),
- user_id: "user1".to_string(),
- content: "test".to_string(),
- created_at: Utc::now(),
- updated_at: Utc::now(),
- confidence: Some(50),
- generated: true,
- source: "email".to_string(),
- source_location: None,
- span_start: None,
- span_end: None,
- insight_type: None,
- relevance_keywords: Some(vec![
- "email".to_string(),
- "urgent".to_string(),
- "project".to_string(),
- ]),
- };
-
- let context = RankingContext {
- current_time: Utc::now(),
- query_keywords: Some(vec!["email".to_string(), "project".to_string()]),
- max_insights: 10,
- prefer_actionable: false,
- };
-
- let score = calculate_keyword_match_score(&insight, &context);
- assert_eq!(score, 1.0); // Perfect match: 2 out of 2 keywords match
- }
-}
diff --git a/rust/cloud-storage/insight_service/src/main.rs b/rust/cloud-storage/insight_service/src/main.rs
deleted file mode 100644
index 3765156b44..0000000000
--- a/rust/cloud-storage/insight_service/src/main.rs
+++ /dev/null
@@ -1,71 +0,0 @@
-mod api;
-mod config;
-mod context;
-mod insight;
-mod serve;
-mod service;
-
-use clap::Parser;
-use config::Config;
-use macro_entrypoint::MacroEntrypoint;
-
-#[derive(Parser)]
-#[command(name = "insight_service")]
-#[command(about = "Insight service for generating and managing user insights")]
-struct Args {
- #[arg(long, help = "Run as a batch job instead of starting the server")]
- batch_job: bool,
-}
-
-#[tokio::main]
-async fn main() {
- let args = Args::parse();
-
- MacroEntrypoint::default().init();
-
- let config = Config::from_env().unwrap();
-
- if args.batch_job {
- tracing::info!("Starting insight batch processing job");
-
- // Run batch processing instead of server
- use context::ServiceContext;
- use insight::batch_processor::InsightBatchProcessor;
- use std::sync::Arc;
-
- let service_context = Arc::new(
- ServiceContext::try_from_config(&config)
- .await
- .expect("To be valid context"),
- );
- let processor = InsightBatchProcessor::new(service_context.macro_db.clone());
-
- let batch_size = std::env::var("BATCH_SIZE")
- .unwrap_or("500".to_string())
- .parse::<i64>()
- .unwrap_or(500);
-
- match processor.process_all_users(batch_size).await {
- Ok(stats) => {
- tracing::info!(
- "Batch processing completed successfully. Processed: {}, Failed: {}, Expired cleaned: {}",
- stats.users_processed,
- stats.users_failed,
- stats.expired_cleaned
- );
- std::process::exit(0);
- }
- Err(e) => {
- tracing::error!("Batch processing failed: {:?}", e);
- std::process::exit(1);
- }
- }
- } else {
- tracing::info!("insight generation service started");
-
- tracing::info!("Context queue started, polling for messages");
- let config_clone = config.clone();
- tokio::spawn(insight::setup_and_poll(config_clone));
- serve::setup_and_serve(config).await
- }
-}
diff --git a/rust/cloud-storage/insight_service/src/serve.rs b/rust/cloud-storage/insight_service/src/serve.rs
deleted file mode 100644
index 0758b31ee6..0000000000
--- a/rust/cloud-storage/insight_service/src/serve.rs
+++ /dev/null
@@ -1,51 +0,0 @@
-use super::config::Config;
-use crate::api::{ApiContext, router as api_router, swagger};
-use axum::{Router, routing::get};
-use macro_auth::middleware::decode_jwt::JwtValidationArgs;
-use macro_cors::cors_layer;
-use tower_http::trace::TraceLayer;
-use utoipa::OpenApi;
-use utoipa_swagger_ui::SwaggerUi;
-
-pub async fn setup_and_serve(config: Config) {
- let secretsmanager_client =
- secretsmanager_client::SecretsManager::new(aws_sdk_secretsmanager::Client::new(
- &aws_config::defaults(aws_config::BehaviorVersion::latest())
- .region("us-east-1")
- .load()
- .await,
- ));
- tracing::debug!("initialized secretsmanager client");
-
- let jwt_args =
- JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client)
- .await
- .unwrap();
-
- let port = config.port;
- let api_context = ApiContext::connect_from_config(config, jwt_args)
- .await
- .expect("Failed to setup API context");
-
- let router = Router::new()
- .route("/health", get(|| async { "healthy" }))
- .nest(
- "/",
- api_router().layer(axum::middleware::from_fn_with_state(
- api_context.clone(),
- macro_middleware::auth::decode_jwt::handler,
- )),
- )
- .layer(cors_layer())
- .layer(TraceLayer::new_for_http())
- .merge(SwaggerUi::new("/docs").url("/api-doc/openapi.json", swagger::ApiDoc::openapi()))
- .with_state(api_context);
-
- let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port))
- .await
- .expect("Failed to bind to port");
-
- axum::serve(listener, router)
- .await
- .expect("Failed to start service router")
-}
diff --git a/rust/cloud-storage/insight_service/src/service/document/content.rs b/rust/cloud-storage/insight_service/src/service/document/content.rs
deleted file mode 100644
index 1cda273837..0000000000
--- a/rust/cloud-storage/insight_service/src/service/document/content.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-use crate::context::ServiceContext;
-use anyhow::Error;
-use model::document::DocumentBasic;
-use std::sync::Arc;
-
-pub async fn get_plaintext_content_from_id(
- service_context: Arc<ServiceContext>,
- document_id: &str,
-) -> Result<(String, DocumentBasic), Error> {
- service_context
- .content_client
- .document
- .fetch(document_id)
- .document_content()
- .await
- .map_err(|e| anyhow::anyhow!("Failed to get document content: {}", e))
- .and_then(|document| {
- let metadata = document.metadata().clone();
- document.content.text_content().map(|text| (text, metadata))
- })
-}
diff --git a/rust/cloud-storage/insight_service/src/service/document/mod.rs b/rust/cloud-storage/insight_service/src/service/document/mod.rs
deleted file mode 100644
index 4b9285cf21..0000000000
--- a/rust/cloud-storage/insight_service/src/service/document/mod.rs
+++ /dev/null
@@ -1,5 +0,0 @@
-mod content;
-mod summary;
-
-pub use content::*;
-pub use summary::*;
diff --git a/rust/cloud-storage/insight_service/src/service/document/summary.rs b/rust/cloud-storage/insight_service/src/service/document/summary.rs
deleted file mode 100644
index 2fccc09db7..0000000000
--- a/rust/cloud-storage/insight_service/src/service/document/summary.rs
+++ /dev/null
@@ -1,12 +0,0 @@
-use ai::simple_completion::simple_completion;
-use ai::types::Model;
-use anyhow::Error;
-use model::document::DocumentBasic;
-
-pub async fn summarize_document(text: String, _: DocumentBasic) -> Result<String, Error> {
- const SUMMARIZER_MODEL: Model = Model::OpenAiGpt41;
- const SYSTEM_PROMPT: &str = "You are a summarizer tool. Your job is to summarize the document context you are given. You
- summaries should be no longer than 5 sentences. The request section will contain the document you are to summarize";
-
- simple_completion(SYSTEM_PROMPT, text.as_str(), SUMMARIZER_MODEL).await
-}
diff --git a/rust/cloud-storage/insight_service/src/service/mod.rs b/rust/cloud-storage/insight_service/src/service/mod.rs
deleted file mode 100644
index b3316091b4..0000000000
--- a/rust/cloud-storage/insight_service/src/service/mod.rs
+++ /dev/null
@@ -1 +0,0 @@
-pub mod document;
diff --git a/rust/cloud-storage/insight_service/test/chat_log.txt b/rust/cloud-storage/insight_service/test/chat_log.txt
deleted file mode 100644
index 7ec6ba2df2..0000000000
--- a/rust/cloud-storage/insight_service/test/chat_log.txt
+++ /dev/null
@@ -1,25 +0,0 @@
- Do you know what version you are?
- What model are you:?
- Hello
- again!
- stunning. do one with a river. use even more shapes!
- draw a landscape like bob ross did. make it pretty. use alot of shapes
- agai
- make it more happy???
- draw a face
- again still wrong
- again that one was wrong :(
- use 50 shapes
- draw a building
- again!
- Draw a flowchart of a pretty woman
- draw picture of pretty woman
- hes kinda square. make him less square. make him killing a bad guy
- Draw me spiderman using 50 shapes
- wow such a pretty house. Now draw an apartment
- again
- again
- draw house
- hi
- again
- draw me a doggie
\ No newline at end of file
diff --git a/rust/cloud-storage/insight_service/tests/chat_context.json b/rust/cloud-storage/insight_service/tests/chat_context.json
deleted file mode 100644
index 3a04ea3fad..0000000000
--- a/rust/cloud-storage/insight_service/tests/chat_context.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "type": "context",
- "provider_source": "chat",
- "user_id": "fake|user.com",
- "resource_id": "message_id"
-}
\ No newline at end of file
diff --git a/rust/cloud-storage/insight_service_client/Cargo.toml b/rust/cloud-storage/insight_service_client/Cargo.toml
deleted file mode 100644
index eaa8d8d7bb..0000000000
--- a/rust/cloud-storage/insight_service_client/Cargo.toml
+++ /dev/null
@@ -1,22 +0,0 @@
-[package]
-edition = "2024"
-name = "insight_service_client"
-publish = false
-version = "0.1.0"
-
-[dependencies]
-ai_format = { path = "../ai_format" }
-anyhow.workspace = true
-async-trait.workspace = true
-aws-sdk-sqs.workspace = true
-chrono.workspace = true
-model = { path = "../model" }
-serde.workspace = true
-sqlx.workspace = true
-sqs_client = { path = "../sqs_client" }
-strum.workspace = true
-strum_macros = { workspace = true }
-tracing.workspace = true
-
-[dev-dependencies]
-tokio.workspace = true
diff --git a/rust/cloud-storage/insight_service_client/README.md b/rust/cloud-storage/insight_service_client/README.md
deleted file mode 100644
index dcd28f198e..0000000000
--- a/rust/cloud-storage/insight_service_client/README.md
+++ /dev/null
@@ -1,5 +0,0 @@
-A lib defining a `ContextConsumer` trait and a `ContextProviderStruct`.
-
-Context is provided by services and processed in the `insight_service`. Context is then aggregated and passed to consumers to generate insight.
-
-The `chat_insight_context` lib defines a context consumer for DCS(chat)
\ No newline at end of file
diff --git a/rust/cloud-storage/insight_service_client/chat_log.txt b/rust/cloud-storage/insight_service_client/chat_log.txt
deleted file mode 100644
index 7ec6ba2df2..0000000000
--- a/rust/cloud-storage/insight_service_client/chat_log.txt
+++ /dev/null
@@ -1,25 +0,0 @@
- Do you know what version you are?
- What model are you:?
- Hello
- again!
- stunning. do one with a river. use even more shapes!
- draw a landscape like bob ross did. make it pretty. use alot of shapes
- agai
- make it more happy???
- draw a face
- again still wrong
- again that one was wrong :(
- use 50 shapes
- draw a building
- again!
- Draw a flowchart of a pretty woman
- draw picture of pretty woman
- hes kinda square. make him less square. make him killing a bad guy
- Draw me spiderman using 50 shapes
- wow such a pretty house. Now draw an apartment
- again
- again
- draw house
- hi
- again
- draw me a doggie
\ No newline at end of file
diff --git a/rust/cloud-storage/insight_service_client/src/lib.rs b/rust/cloud-storage/insight_service_client/src/lib.rs
deleted file mode 100644
index 315dd9181e..0000000000
--- a/rust/cloud-storage/insight_service_client/src/lib.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-mod provider;
-
-pub use provider::*;
diff --git a/rust/cloud-storage/insight_service_client/src/provider.rs b/rust/cloud-storage/insight_service_client/src/provider.rs
deleted file mode 100644
index 90f3cabeb7..0000000000
--- a/rust/cloud-storage/insight_service_client/src/provider.rs
+++ /dev/null
@@ -1,49 +0,0 @@
-use anyhow::Context;
-use model::insight_context::email_insights::GenerateEmailInsightContext;
-use model::insight_context::{InsightContextQueueMessage, ProvidedContext};
-use sqs_client::SQS;
-
-#[derive(Debug, Clone)]
-pub struct InsightContextProvider {
- pub source_name: String,
- pub sqs_client: SQS,
-}
-
-impl InsightContextProvider {
- #[tracing::instrument(skip(sqs_client))]
- pub fn create(sqs_client: SQS, source_name: &'static str) -> Self {
- Self {
- source_name: source_name.to_string(),
- sqs_client,
- }
- }
-
- #[tracing::instrument(skip(self))]
- pub async fn provide_context(&self, user_id: &str, resource_id: &str) {
- let message = InsightContextQueueMessage::Context(ProvidedContext {
- provider_source: self.source_name.to_owned(),
- resource_id: resource_id.to_string(),
- user_id: user_id.to_string(),
- });
-
- tracing::debug!("provide context {:?}", message);
- let _ = self
- .sqs_client
- .enqueue_insight_context(message)
- .await
- .context(format!("failed to send context {}", self.source_name));
- }
-
- /// Enqueue a batch of email threads for insight generation
- #[tracing::instrument(skip(self))]
- pub async fn provide_email_context(
- &self,
- context: GenerateEmailInsightContext,
- ) -> anyhow::Result<()> {
- let message = InsightContextQueueMessage::Email { context };
- self.sqs_client
- .enqueue_insight_context(message)
- .await
- .context("failed to send email context")
- }
-}
diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfile
index 2ac95b97b2..9535bdb6d4 100644
--- a/rust/cloud-storage/justfile
+++ b/rust/cloud-storage/justfile
@@ -49,7 +49,6 @@ setup_test_envs:
echo "DATABASE_URL={{ MACRODB }}" >> ./organization_retention_handler/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./sha_cleanup_worker/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./sha_ref_count_resetter/.env
- echo "DATABASE_URL={{ MACRODB }}" >> ./insight_service/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./metering_service/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./roles_and_permissions/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./teams/.env
@@ -69,7 +68,5 @@ initialize_dbs: setup_macrodb
just notification_db_client/setup
# contactsdb
just contacts_db_client/setup
- # insight integration
- just insight_service/prepare-test
# metering db
just metering_db_client/setup
diff --git a/rust/cloud-storage/macro_db_client/src/chat_history/mod.rs b/rust/cloud-storage/macro_db_client/src/chat_history/mod.rs
new file mode 100644
index 0000000000..1d23a4ffea
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/src/chat_history/mod.rs
@@ -0,0 +1,125 @@
+use anyhow::Error;
+use chrono::{DateTime, Utc};
+use model::chat::{ChatHistory, ConversationRecord, MessageWithAttachments};
+use sqlx::{Executor, FromRow, Postgres};
+use std::collections::HashMap;
+
+#[derive(FromRow)]
+struct ChatHistoryRow {
+ chat_id: String,
+ chat_title: Option<String>,
+ message_content: String,
+ message_created_at: DateTime<Utc>,
+ attachment_id: Option<String>,
+}
+
+/// Get chat history for a single chat by ID
+pub async fn get_chat_history<'e, E>(db: E, chat_id: &str) -> Result<ChatHistory, Error>
+where
+ E: Executor<'e, Database = Postgres>,
+{
+ let rows = sqlx::query_as::<_, ChatHistoryRow>(
+ r#"
+ SELECT
+ c.id as chat_id,
+ c.title as chat_title,
+ m.content as message_content,
+ m."createdAt" as message_created_at,
+ ma."attachmentId" as attachment_id
+ FROM "Chat" c
+ JOIN "ChatMessage" m ON m."chatId" = c.id
+ LEFT JOIN "ChatMessageAttachment" ma ON ma."messageId" = m.id
+ WHERE c.id = $1
+ ORDER BY m."createdAt" ASC
+ "#,
+ )
+ .bind(chat_id)
+ .fetch_all(db)
+ .await?;
+
+ Ok(build_chat_history(rows))
+}
+
+/// Get chat history for messages by their IDs
+pub async fn get_chat_history_for_messages<'e, E>(
+ db: E,
+ message_ids: &[String],
+) -> Result<ChatHistory, Error>
+where
+ E: Executor<'e, Database = Postgres>,
+{
+ let rows = sqlx::query_as::<_, ChatHistoryRow>(
+ r#"
+ SELECT
+ c.id as chat_id,
+ c.title as chat_title,
+ m.content as message_content,
+ m."createdAt" as message_created_at,
+ ma."attachmentId" as attachment_id
+ FROM "Chat" c
+ JOIN "ChatMessage" m ON m."chatId" = c.id
+ LEFT JOIN "ChatMessageAttachment" ma ON ma."messageId" = m.id
+ WHERE m.id = ANY($1)
+ ORDER BY m."createdAt" ASC
+ "#,
+ )
+ .bind(message_ids)
+ .fetch_all(db)
+ .await?;
+
+ Ok(build_chat_history(rows))
+}
+
+fn build_chat_history(rows: Vec<ChatHistoryRow>) -> ChatHistory {
+ type Chats = HashMap<String, (String, Vec<(String, DateTime<Utc>, Vec<String>)>)>;
+ let mut chats: Chats = HashMap::new();
+
+ for row in rows {
+ let chat_entry = chats
+ .entry(row.chat_id.clone())
+ .or_insert_with(|| (row.chat_title.unwrap_or_default(), Vec::new()));
+
+ // Find or create message entry
+ let message_key = (row.message_content.clone(), row.message_created_at);
+ let message_idx = chat_entry
+ .1
+ .iter()
+ .position(|(content, date, _)| *content == message_key.0 && *date == message_key.1);
+
+ match message_idx {
+ Some(idx) => {
+ if let Some(att_id) = row.attachment_id {
+ chat_entry.1[idx].2.push(att_id);
+ }
+ }
+ None => {
+ let attachments = row.attachment_id.into_iter().collect();
+ chat_entry
+ .1
+ .push((row.message_content, row.message_created_at, attachments));
+ }
+ }
+ }
+
+ let conversation: Vec<ConversationRecord> = chats
+ .into_iter()
+ .map(|(chat_id, (title, messages))| {
+ let messages = messages
+ .into_iter()
+ .map(|(content, date, attachment_ids)| MessageWithAttachments {
+ content,
+ date,
+ attachment_ids,
+ })
+ .collect();
+
+ ConversationRecord {
+ chat_id,
+ title,
+ messages,
+ }
+ })
+ .collect();
+
+ ChatHistory { conversation }
+}
diff --git a/rust/cloud-storage/macro_db_client/src/insight/chat_insight_context/get_chat_context.rs b/rust/cloud-storage/macro_db_client/src/insight/chat_insight_context/get_chat_context.rs
deleted file mode 100644
index 5b24117fb0..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/chat_insight_context/get_chat_context.rs
+++ /dev/null
@@ -1,411 +0,0 @@
-use ai::types::ChatMessageContent;
-use anyhow::Error;
-use chrono::{DateTime, Utc};
-use model::chat::{ChatHistory, ConversationRecord, MessageWithAttachmentSummary, Summary};
-use model::insight_context::document::DocumentSummary;
-use sqlx::{Executor, FromRow, Postgres};
-use std::collections::HashMap;
-
-// Struct to represent the query result row
-#[derive(FromRow)]
-struct ChatQueryRecord {
- message_id: String,
- content: serde_json::Value,
- date: DateTime<Utc>,
- conversation_title: String,
- attachment_id: Option<String>,
- ds_summary: Option<String>,
- ds_version_id: Option<String>,
- ds_created_at: Option<DateTime<Utc>>,
- ds_document_id: Option<String>,
- ds_id: Option<String>,
- chat_id: String,
-}
-
-fn process_chat_records(records: Vec<ChatQueryRecord>) -> Result<ChatHistory, Error> {
- // map message id to summaries
- let mut attachments: HashMap<String, Vec<_>> = HashMap::new();
-
- for record in records.iter() {
- if let Some(ref attachment_id) = record.attachment_id {
- let summary = if record.ds_id.is_some() {
- if record.ds_document_id.is_none()
- || record.ds_summary.is_none()
- || record.ds_version_id.is_none()
- {
- panic!("unexpected null");
- }
-
- Summary::Summary(DocumentSummary {
- created_at: record.ds_created_at,
- document_id: record.ds_document_id.clone().expect("document id"),
- summary: record.ds_summary.clone().expect("summary"),
- id: record.ds_id.clone(),
- version_id: record.ds_version_id.clone().expect("version_id"),
- })
- } else {
- Summary::NoSummary {
- document_id: attachment_id.clone(),
- }
- };
- attachments
- .entry(record.message_id.clone())
- .or_default()
- .push(summary);
- }
- }
-
- // map chat id to messages
- let mut message_map: HashMap<String, Vec<MessageWithAttachmentSummary>> = HashMap::new();
- // map chat id to title
- let mut title_map: HashMap<String, String> = HashMap::new();
-
- records
- .into_iter()
- // dedup records by message_id
- .map(|record| (record.message_id.clone(), record))
- .collect::<HashMap<_, _>>()
- .values()
- // iterating over messages
- .for_each(|record| {
- // let date = DateTime::from_naive_utc_and_offset(record.date, Utc);
- let attachment_list = attachments
- .get(&record.message_id)
- .map(|c| c.to_owned())
- .unwrap_or_default();
- let content = serde_json::from_value::<ChatMessageContent>(record.content.clone());
- if content.is_err() {
- return;
- }
- let content = content.unwrap();
- let text = content.message_text_with_tools();
- let message = MessageWithAttachmentSummary {
- attachment_summaries: attachment_list,
- content: text,
- date: record.date,
- };
- message_map
- .entry(record.chat_id.clone())
- .or_default()
- .push(message);
- title_map.insert(record.chat_id.clone(), record.conversation_title.clone());
- });
-
- let mut conversations = message_map
- .into_iter()
- .map(|(chat_id, mut messages)| {
- messages.sort_by(|a, b| a.date.cmp(&b.date));
- let title = title_map.get(&chat_id).unwrap_or(&"".to_string()).clone();
- ConversationRecord {
- chat_id,
- title,
- messages,
- }
- })
- .collect::<Vec<_>>();
-
- // Sort conversations by chat_id to ensure consistent ordering
- conversations.sort_by(|a, b| a.chat_id.cmp(&b.chat_id));
- Ok(ChatHistory {
- conversation: conversations,
- })
-}
-
-#[tracing::instrument(skip(db))]
-pub async fn get_chat_history_for_messages<'e, E>(
- db: E,
- messages: &[String],
-) -> Result<ChatHistory, Error>
-where
- E: Executor<'e, Database = Postgres>,
-{
- let records = sqlx::query_as!(
- ChatQueryRecord,
- r#"
- SELECT
- m."id" as message_id,
- m."content",
- m."createdAt" as "date!: DateTime<Utc>",
- c."name" as conversation_title,
- a."attachmentId" as "attachment_id?",
- d."summary" as "ds_summary?",
- d."version_id" as "ds_version_id?",
- d."createdAt" as "ds_created_at?: DateTime<Utc>",
- d."document_id" as "ds_document_id?",
- d."id" as "ds_id?",
- m."chatId" as "chat_id"
- FROM "ChatMessage" m
- LEFT JOIN "Chat" c
- ON c."id" = m."chatId"
- LEFT JOIN "ChatAttachment" a
- ON m.id = a."messageId"
- LEFT JOIN LATERAL (
- SELECT DISTINCT ON (ds."document_id")
- ds.*
- FROM "DocumentSummary" ds
- WHERE ds."document_id" = a."attachmentId"
- ORDER BY ds."document_id", ds."createdAt" DESC
- ) d ON true
- WHERE
- m."id" = ANY($1)
- ORDER BY m."createdAt" DESC;
- "#,
- &messages
- )
- .fetch_all(db)
- .await?;
-
- process_chat_records(records)
-}
-
-#[tracing::instrument(skip(db))]
-pub async fn get_chat_history<'e, E>(db: E, chat_id: &str) -> Result<ChatHistory, Error>
-where
- E: Executor<'e, Database = Postgres>,
-{
- let records = sqlx::query_as!(
- ChatQueryRecord,
- r#"
- SELECT
- m."id" as message_id,
- m."content",
- m."createdAt" as "date!: DateTime<Utc>",
- c."name" as conversation_title,
- a."attachmentId" as "attachment_id?",
- d."summary" as "ds_summary?",
- d."version_id" as "ds_version_id?",
- d."createdAt" as "ds_created_at?: DateTime<Utc>",
- d."document_id" as "ds_document_id?",
- d."id" as "ds_id?",
- m."chatId" as "chat_id"
- FROM "ChatMessage" m
- LEFT JOIN "Chat" c
- ON c."id" = m."chatId"
- LEFT JOIN "ChatAttachment" a
- ON m.id = a."messageId"
- LEFT JOIN LATERAL (
- SELECT DISTINCT ON (ds."document_id")
- ds.*
- FROM "DocumentSummary" ds
- WHERE ds."document_id" = a."attachmentId"
- ORDER BY ds."document_id", ds."createdAt" DESC
- ) d ON true
- WHERE
- m."chatId" = $1
- ORDER BY m."createdAt" DESC;
- "#,
- chat_id
- )
- .fetch_all(db)
- .await?;
-
- process_chat_records(records)
-}
-
-#[cfg(test)]
-mod test {
- use super::*;
- use sqlx::{Pool, Postgres};
- use std::collections::HashMap;
-
- const USER_ID: &str = "test-userid";
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("chat_with_attachment_summaries")))]
- async fn test_get_a(db: Pool<Postgres>) {
- let history = get_chat_history_for_messages(&db, &["c0m0".to_string()])
- .await
- .expect("messages");
-
- assert!(!history.conversation.is_empty());
- assert_eq!(history.conversation.len(), 1);
- assert_eq!(
- history.conversation.first().expect("first").messages.len(),
- 1
- );
-
- let message = history
- .conversation
- .first()
- .expect("first")
- .messages
- .first()
- .expect("first_message");
- assert_eq!(message.content.as_str(), "m0-content");
-
- let summaries = message
- .clone()
- .attachment_summaries
- .into_iter()
- .filter_map(|sum| match sum {
- Summary::Summary(s) => Some(s),
- _ => None,
- })
- .collect::<Vec<_>>();
-
- assert_eq!(summaries.len(), 1);
-
- let i0 = summaries.first().expect("summary").clone();
-
- assert_eq!(i0.document_id, "document-id-0".to_string());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("chat_with_attachment_summaries")))]
- async fn test_get_b(db: Pool<Postgres>) {
- let history = get_chat_history_for_messages(
- &db,
- &["c0m0", "c0m1", "c0m2"]
- .into_iter()
- .map(&str::to_string)
- .collect::<Vec<_>>(),
- )
- .await
- .expect("messages");
- assert_eq!(history.conversation.len(), 1);
- assert_eq!(
- history.conversation.first().expect("first").messages.len(),
- 3
- );
-
- let history = get_chat_history_for_messages(
- &db,
- &["c0m0", "c0m1", "c0m2", "c1m0", "c1m1"]
- .into_iter()
- .map(&str::to_string)
- .collect::<Vec<_>>(),
- )
- .await
- .expect("messages");
- assert_eq!(history.conversation.len(), 2);
- assert_eq!(history.conversation[0].messages.len(), 3);
- assert_eq!(history.conversation[1].messages.len(), 2);
-
- let history = get_chat_history_for_messages(
- &db,
- &["c0m0", "c0m1", "c0m2", "c0m0", "c0m0", "c0m0"]
- .into_iter()
- .map(&str::to_string)
- .collect::<Vec<_>>(),
- )
- .await
- .expect("messages");
- assert_eq!(history.conversation.len(), 1);
- assert_eq!(
- history.conversation.first().expect("first").messages.len(),
- 3
- );
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("chat_with_attachment_summaries")))]
- async fn test_get_c(db: Pool<Postgres>) {
- let history = get_chat_history_for_messages(
- &db,
- &["c0m0", "c0m1", "c0m2", "c1m0", "c1m1"]
- .into_iter()
- .map(&str::to_string)
- .collect::<Vec<_>>(),
- )
- .await
- .expect("messages");
- assert_eq!(history.conversation.len(), 2);
- assert_eq!(history.conversation[0].messages.len(), 3);
- assert_eq!(history.conversation[1].messages.len(), 2);
-
- let all_insights = history
- .conversation
- .into_iter()
- .flat_map(|c| {
- c.messages
- .into_iter()
- .flat_map(|m| m.attachment_summaries.into_iter())
- })
- .collect::<Vec<_>>();
- let mut messages_without_insight = 0;
- for i in &all_insights {
- if let Summary::NoSummary { document_id } = i {
- messages_without_insight += 1;
- assert!(
- document_id.as_str() == "document-id-img"
- || document_id.as_str() == "document-id-2"
- )
- }
- }
- assert_eq!(messages_without_insight, 2);
- let deduped = all_insights
- .into_iter()
- .filter_map(|i| match i {
- Summary::NoSummary { .. } => None,
- Summary::Summary(a) => Some((a.document_id.clone(), a)),
- })
- .collect::<HashMap<_, _>>();
- assert_eq!(deduped.len(), 2);
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("chat_with_attachment_summaries")))]
- async fn test_stable_order_and_chronology(db: Pool<Postgres>) {
- const USER_ID: &str = "test-userid";
-
- // Every message-id in the fixture in one shot.
- let all_ids: Vec<String> = ["c0m0", "c0m1", "c0m2", "c1m0", "c1m1"]
- .iter()
- .map(|s| s.to_string())
- .collect();
-
- // A single “canonical” run whose order we’ll treat as ground truth.
- let baseline = get_chat_history_for_messages(&db, &all_ids)
- .await
- .expect("baseline history");
-
- // Extract (conversation title, Vec<DateTime>) from the baseline.
- let baseline_timeline: Vec<(String, Vec<DateTime<Utc>>)> = baseline
- .conversation
- .iter()
- .map(|conv| {
- let dates = conv.messages.iter().map(|m| m.date).collect::<Vec<_>>();
- (conv.title.clone(), dates)
- })
- .collect();
-
- // Run the query many times to flush out any nondeterminism.
- for _ in 0..100 {
- let history = get_chat_history_for_messages(&db, &all_ids)
- .await
- .expect("history");
-
- // 1️⃣ conversation order must match baseline
- assert_eq!(
- history.conversation.len(),
- baseline_timeline.len(),
- "conversation count changed"
- );
-
- for (idx, conv) in history.conversation.iter().enumerate() {
- let (ref expected_title, ref expected_dates) = baseline_timeline[idx];
-
- assert_eq!(
- &conv.title, expected_title,
- "conversation order changed at index {idx}"
- );
-
- // 2️⃣ message dates must match baseline *and* be ascending
- let dates = conv.messages.iter().map(|m| m.date).collect::<Vec<_>>();
- assert_eq!(
- &dates, expected_dates,
- "message order changed in conversation `{}`",
- conv.title
- );
-
- let mut sorted = dates.clone();
- sorted.sort();
-
- assert!(
- sorted.first().expect("first") < sorted.last().expect("last"),
- "latest last"
- );
- assert_eq!(
- dates, sorted,
- "messages in `{}` not sorted earliest → latest",
- conv.title
- );
- }
- }
- }
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insight/chat_insight_context/mod.rs b/rust/cloud-storage/macro_db_client/src/insight/chat_insight_context/mod.rs
deleted file mode 100644
index 88b87fdd15..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/chat_insight_context/mod.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-mod get_chat_context;
-
-pub use get_chat_context::*;
diff --git a/rust/cloud-storage/macro_db_client/src/insight/context/create.rs b/rust/cloud-storage/macro_db_client/src/insight/context/create.rs
deleted file mode 100644
index 2501aefdae..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/context/create.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-use model::insight_context::ProvidedContext;
-use sqlx::{Executor, Postgres};
-
-#[tracing::instrument(skip(db))]
-pub async fn create_insight_context<'e, E>(
- db: E,
- context: &ProvidedContext,
-) -> Result<(), sqlx::Error>
-where
- E: Executor<'e, Database = Postgres>,
-{
- sqlx::query!(
- r#"
- INSERT INTO "InsightContext" ("providerSource", "userId", "resourceId")
- VALUES ($1, $2, $3)
- "#,
- context.provider_source,
- context.user_id,
- context.resource_id
- )
- .execute(db)
- .await?;
- Ok(())
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insight/context/mod.rs b/rust/cloud-storage/macro_db_client/src/insight/context/mod.rs
deleted file mode 100644
index 36f113fc10..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/context/mod.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-mod create;
-mod read;
-mod update;
-
-pub use create::*;
-pub use read::*;
-pub use update::*;
diff --git a/rust/cloud-storage/macro_db_client/src/insight/context/read.rs b/rust/cloud-storage/macro_db_client/src/insight/context/read.rs
deleted file mode 100644
index da0582405d..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/context/read.rs
+++ /dev/null
@@ -1,55 +0,0 @@
-use model::insight_context::ProvidedContext;
-use sqlx::{Executor, Postgres};
-
-#[tracing::instrument(skip(db))]
-pub async fn read_pending_context<'e, E>(
- db: E,
- source_name: &str,
- user_id: &str,
- limit: i64,
-) -> Result<Vec<(String, ProvidedContext)>, sqlx::Error>
-where
- E: Executor<'e, Database = Postgres>,
-{
- let context_records = sqlx::query!(
- r#"
- SELECT
- "id",
- "providerSource" as provider_source,
- "userId" as user_id,
- "resourceId" as resource_id
- FROM "InsightContext"
- WHERE
- "userId" = $1
- AND
- "providerSource" = $2
- AND
- "consumed" = false
- ORDER BY
- "createdAt" DESC
- LIMIT
- $3
- "#,
- user_id,
- source_name,
- limit
- )
- .fetch_all(db)
- .await?;
-
- let context = context_records
- .into_iter()
- .map(|record| {
- (
- record.id,
- ProvidedContext {
- provider_source: record.provider_source,
- resource_id: record.resource_id,
- user_id: record.user_id,
- },
- )
- })
- .collect::<Vec<_>>();
-
- Ok(context)
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insight/context/update.rs b/rust/cloud-storage/macro_db_client/src/insight/context/update.rs
deleted file mode 100644
index 47ba45bb5a..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/context/update.rs
+++ /dev/null
@@ -1,19 +0,0 @@
-use sqlx::{Executor, Postgres};
-
-#[tracing::instrument(skip(db))]
-pub async fn mark_consumed<'e, E>(db: E, ids: &[String]) -> Result<(), sqlx::Error>
-where
- E: Executor<'e, Database = Postgres>,
-{
- sqlx::query!(
- r#"
- UPDATE "InsightContext"
- SET consumed=true
- WHERE id = ANY($1)
- "#,
- ids
- )
- .execute(db)
- .await?;
- Ok(())
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insight/document/create.rs b/rust/cloud-storage/macro_db_client/src/insight/document/create.rs
deleted file mode 100644
index b470a2a75e..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/document/create.rs
+++ /dev/null
@@ -1,46 +0,0 @@
-use anyhow::{Context, Error};
-use chrono::{DateTime, Utc};
-use model::insight_context::document::DocumentSummary;
-use sqlx::{Executor, Postgres};
-
-#[tracing::instrument(skip(db))]
-pub async fn create_document_summaries<'e, E>(
- db: E,
- summaries: Vec<DocumentSummary>,
-) -> Result<Vec<DocumentSummary>, Error>
-where
- E: Executor<'e, Database = Postgres>,
-{
- let (document_ids, version_ids, summaries) = summaries
- .into_iter()
- .map(|summary| (summary.document_id, summary.version_id, summary.summary))
- .collect::<(Vec<_>, Vec<_>, Vec<_>)>();
-
- sqlx::query_as!(
- DocumentSummary,
- r#"
- INSERT INTO "DocumentSummary" (
- document_id,
- version_id,
- summary
- )
- SELECT
- u.document_id, u.version_id, u.summary
- FROM
- UNNEST($1::text[], $2::text[], $3::text[])
- AS u(document_id, version_id, summary)
- RETURNING
- id as "id?",
- "createdAt" as "created_at?: DateTime<Utc>",
- document_id,
- version_id,
- summary
- "#,
- &document_ids,
- &version_ids,
- &summaries
- )
- .fetch_all(db)
- .await
- .context("failed to insert into document summaries")
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insight/document/delete.rs b/rust/cloud-storage/macro_db_client/src/insight/document/delete.rs
deleted file mode 100644
index 58d64f4d6e..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/document/delete.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-use anyhow::{Context, Error};
-use sqlx::{Executor, Postgres};
-
-pub async fn delete_document_summaries<'e, E>(db: E, ids: &[String]) -> Result<Vec<String>, Error>
-where
- E: Executor<'e, Database = Postgres>,
-{
- let ids = sqlx::query!(
- r#"
- DELETE FROM "DocumentSummary" WHERE id = ANY($1)
- RETURNING id
- "#,
- &ids,
- )
- .fetch_all(db)
- .await
- .context("failed to delete insights")?;
-
- Ok(ids.into_iter().map(|r| r.id).collect())
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use sqlx::{Pool, Postgres};
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("basic_document_summary")))]
- async fn test_delete_document_summaries(pool: Pool<Postgres>) {
- let ids = vec!["delete-one".to_string(), "delete-two".to_string()];
- let ids = delete_document_summaries(&pool, &ids)
- .await
- .expect("failed to delete insights");
- println!("DELETED {:?}", ids);
- assert_eq!(ids.len(), 2);
- assert!(ids.contains(&"delete-one".to_string()));
- assert!(ids.contains(&"delete-two".to_string()));
- }
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insight/document/mod.rs b/rust/cloud-storage/macro_db_client/src/insight/document/mod.rs
deleted file mode 100644
index 28b5ac6ad0..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/document/mod.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-mod create;
-mod delete;
-mod read;
-mod update;
-
-pub use create::*;
-pub use delete::*;
-pub use read::*;
-pub use update::*;
diff --git a/rust/cloud-storage/macro_db_client/src/insight/document/read.rs b/rust/cloud-storage/macro_db_client/src/insight/document/read.rs
deleted file mode 100644
index 86c3e9efa9..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/document/read.rs
+++ /dev/null
@@ -1,32 +0,0 @@
-use anyhow::{Context, Error};
-use chrono::{DateTime, Utc};
-use model::insight_context::document::DocumentSummary;
-use sqlx::{Executor, Postgres};
-
-#[tracing::instrument(skip(db))]
-pub async fn get_document_summaries<'e, E>(
- db: E,
- document_ids: &[String],
-) -> Result<Vec<DocumentSummary>, Error>
-where
- E: Executor<'e, Database = Postgres>,
-{
- sqlx::query_as!(
- DocumentSummary,
- r#"
- SELECT DISTINCT ON("document_id")
- "id" as "id?",
- "document_id",
- "version_id",
- "createdAt" as "created_at?: DateTime<Utc>",
- "summary"
- FROM "DocumentSummary"
- WHERE document_id = ANY($1)
- ORDER BY "document_id", "createdAt" DESC
- "#,
- document_ids
- )
- .fetch_all(db)
- .await
- .context("failed to fetch document summaries")
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insight/document/update.rs b/rust/cloud-storage/macro_db_client/src/insight/document/update.rs
deleted file mode 100644
index 733c9e2755..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/document/update.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-use anyhow::Error;
-use model::insight_context::document::DocumentSummary;
-use sqlx::{Executor, Postgres};
-
-// TODO: implement
-#[tracing::instrument]
-pub async fn update_document_summary<'e, E, D, T>(_: E) -> Result<Vec<DocumentSummary>, Error>
-where
- E: Executor<'e, Database = Postgres> + Clone,
- T: std::fmt::Debug + Sized,
-{
- unimplemented!()
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insight/fixtures/user_insights.sql b/rust/cloud-storage/macro_db_client/src/insight/fixtures/user_insights.sql
deleted file mode 100644
index 8a3326c4c6..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/fixtures/user_insights.sql
+++ /dev/null
@@ -1,9 +0,0 @@
--- Insert a test user (required for foreign key constraint)
-INSERT INTO "User" (id, email) VALUES ('macro|[email protected]', '[email protected]');
-
--- Insert two user insights for the test user
-INSERT INTO "UserInsights" (
- id, "userId", content, source, generated, confidence
-) VALUES
- ('insight1', 'macro|[email protected]', 'Insight content 1', 'test_source', true, 5),
- ('insight2', 'macro|[email protected]', 'Insight content 2', 'test_source', false, 1);
\ No newline at end of file
diff --git a/rust/cloud-storage/macro_db_client/src/insight/mod.rs b/rust/cloud-storage/macro_db_client/src/insight/mod.rs
deleted file mode 100644
index 9ecfaab945..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/mod.rs
+++ /dev/null
@@ -1,4 +0,0 @@
-pub mod chat_insight_context;
-pub mod context;
-pub mod document;
-pub mod user;
diff --git a/rust/cloud-storage/macro_db_client/src/insight/user/batch.rs b/rust/cloud-storage/macro_db_client/src/insight/user/batch.rs
deleted file mode 100644
index bba14d5d7a..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/user/batch.rs
+++ /dev/null
@@ -1,335 +0,0 @@
-use anyhow::Result;
-use chrono::{DateTime, Utc};
-use model::insight_context::UserInsightRecord;
-use sqlx::Executor;
-use sqlx::postgres::Postgres;
-use sqlx::types::Json;
-use thiserror::Error;
-
-#[derive(Error, Debug)]
-pub enum BatchError {
- #[error(
- "Expected {expected} insights for user {user_id}, but got {actual}. Some insights may have been deleted."
- )]
- IncompleteInsights {
- expected: usize,
- actual: usize,
- user_id: String,
- },
- #[error("Database error: {0}")]
- Database(#[from] sqlx::Error),
- #[error("Other error: {0}")]
- Other(#[from] anyhow::Error),
-}
-
-#[derive(Debug, sqlx::FromRow)]
-pub struct UserInsightBatchRow {
- pub id: String,
- pub user_id: String,
- pub insight_ids: Option<Vec<String>>,
- pub total_chars: i32,
- pub estimated_tokens: i32,
- pub ranking_context: Option<serde_json::Value>,
- pub created_at: DateTime<Utc>,
- pub expires_at: DateTime<Utc>,
- pub version: i32,
-}
-
-/// Get the current cached insight batch for a user
-#[tracing::instrument(skip(db))]
-pub async fn get_user_insight_batch<'e, E>(
- db: E,
- user_id: &str,
-) -> Result<Option<UserInsightBatchRow>>
-where
- E: Executor<'e, Database = Postgres>,
-{
- let batch = sqlx::query_as!(
- UserInsightBatchRow,
- r#"
- SELECT
- "id",
- "userId" as "user_id",
- "insightIds" as "insight_ids",
- "totalChars" as "total_chars",
- "estimatedTokens" as "estimated_tokens",
- "rankingContext" as "ranking_context",
- "createdAt"::timestamptz as "created_at!",
- "expiresAt"::timestamptz as "expires_at!",
- "version"
- FROM
- "UserInsightBatch"
- WHERE
- "userId" = $1
- AND
- "expiresAt" > NOW()
- "#,
- user_id
- )
- .fetch_optional(db)
- .await?;
-
- Ok(batch)
-}
-
-/// Create or update a user's cached insight batch
-#[tracing::instrument(skip(db))]
-pub async fn upsert_user_insight_batch<'e, E>(
- db: E,
- user_id: &str,
- insight_ids: &[String],
- total_chars: i32,
- estimated_tokens: i32,
- expires_at: DateTime<Utc>,
- ranking_context: Option<&serde_json::Value>,
-) -> Result<String>
-where
- E: Executor<'e, Database = Postgres>,
-{
- let batch_id = sqlx::query_scalar!(
- r#"
- INSERT INTO "UserInsightBatch" (
- "userId",
- "insightIds",
- "totalChars",
- "estimatedTokens",
- "expiresAt",
- "rankingContext"
- )
- VALUES ($1, $2, $3, $4, $5, $6)
- ON CONFLICT ("userId")
- DO UPDATE SET
- "insightIds" = EXCLUDED."insightIds",
- "totalChars" = EXCLUDED."totalChars",
- "estimatedTokens" = EXCLUDED."estimatedTokens",
- "expiresAt" = EXCLUDED."expiresAt",
- "rankingContext" = EXCLUDED."rankingContext",
- "version" = "UserInsightBatch"."version" + 1,
- "createdAt" = NOW()
- RETURNING "id"
- "#,
- user_id,
- insight_ids,
- total_chars,
- estimated_tokens,
- expires_at.naive_utc(),
- ranking_context
- )
- .fetch_one(db)
- .await?;
-
- Ok(batch_id)
-}
-
-/// Get insights for a cached batch by insight IDs
-#[tracing::instrument(skip(db))]
-pub async fn get_insights_by_batch<'e, E>(
- db: E,
- user_id: &str,
- insight_ids: &[String],
-) -> Result<Vec<UserInsightRecord>, BatchError>
-where
- E: Executor<'e, Database = Postgres>,
-{
- use model::insight_context::{InsightType, SourceLocation, UserInsightRow};
-
- let records = sqlx::query_as!(
- UserInsightRow,
- r#"
- SELECT
- "id",
- "userId" as "user_id",
- "content",
- "source",
- "sourceLocation" as "source_location: Json<SourceLocation>",
- "generated",
- "createdAt"::timestamptz as "created_at!",
- "updatedAt"::timestamptz as "updated_at!",
- "spanStart"::timestamptz as "span_start",
- "spanEnd"::timestamptz as "span_end",
- "confidence",
- "insightType" as "insight_type: InsightType",
- "relevanceKeywords" as "relevance_keywords"
- FROM
- "UserInsights"
- WHERE
- "userId" = $1
- AND
- "id" = ANY($2)
- ORDER BY
- array_position($2, "id")
- "#,
- user_id,
- insight_ids
- )
- .fetch_all(db)
- .await?;
-
- // Validate that we got the exact number of insights requested
- if records.len() != insight_ids.len() {
- return Err(BatchError::IncompleteInsights {
- expected: insight_ids.len(),
- actual: records.len(),
- user_id: user_id.to_string(),
- });
- }
-
- Ok(records.into_iter().map(UserInsightRecord::from).collect())
-}
-
-/// Delete a specific user's insight batch
-#[tracing::instrument(skip(db))]
-pub async fn delete_user_insight_batch<'e, E>(db: E, user_id: &str) -> Result<bool>
-where
- E: Executor<'e, Database = Postgres>,
-{
- let rows_affected = sqlx::query!(
- r#"
- DELETE FROM "UserInsightBatch"
- WHERE "userId" = $1
- "#,
- user_id
- )
- .execute(db)
- .await?;
-
- Ok(rows_affected.rows_affected() > 0)
-}
-
-/// Delete expired insight batches (cleanup job)
-#[tracing::instrument(skip(db))]
-pub async fn delete_expired_insight_batches<'e, E>(db: E) -> Result<u64>
-where
- E: Executor<'e, Database = Postgres>,
-{
- let rows_affected = sqlx::query!(
- r#"
- DELETE FROM "UserInsightBatch"
- WHERE "expiresAt" <= NOW()
- "#
- )
- .execute(db)
- .await?;
-
- Ok(rows_affected.rows_affected())
-}
-
-/// Check if user has new insights since last batch creation
-#[tracing::instrument(skip(db))]
-pub async fn has_new_insights_since_batch<'e, E>(
- db: E,
- user_id: &str,
- batch_created_at: DateTime<Utc>,
-) -> Result<bool>
-where
- E: Executor<'e, Database = Postgres>,
-{
- let count = sqlx::query_scalar!(
- r#"
- SELECT COUNT(*) as "count!"
- FROM "UserInsights"
- WHERE "userId" = $1
- AND "createdAt" > $2
- AND "generated" = true
- "#,
- user_id,
- batch_created_at.naive_utc()
- )
- .fetch_one(db)
- .await?;
-
- Ok(count > 0)
-}
-
-/// Get users who need new insight batches (for daily job)
-#[tracing::instrument(skip(db))]
-pub async fn get_users_needing_batch_refresh<'e, E>(db: E, limit: i64) -> Result<Vec<String>>
-where
- E: Executor<'e, Database = Postgres>,
-{
- let user_ids = sqlx::query_scalar!(
- r#"
- SELECT DISTINCT u."id" as "user_id"
- FROM "User" u
- INNER JOIN "UserInsights" ui ON u."id" = ui."userId"
- LEFT JOIN "UserInsightBatch" uib ON u."id" = uib."userId"
- WHERE
- ui."generated" = true
- AND ui."createdAt" > COALESCE(uib."createdAt", '1970-01-01'::timestamptz)
- OR
- uib."expiresAt" <= NOW()
- ORDER BY u."id"
- LIMIT $1
- "#,
- limit
- )
- .fetch_all(db)
- .await?;
-
- Ok(user_ids)
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use sqlx::PgPool;
-
- #[sqlx::test(fixtures("../../../fixtures/users.sql"))]
- async fn test_get_insights_by_batch_validation(pool: PgPool) -> Result<()> {
- let user_id = "macro|[email protected]";
-
- // Test case: Request insights that don't exist (simulates manually deleted insights)
- let non_existent_insight_ids = vec![
- "non_existent_id_1".to_string(),
- "non_existent_id_2".to_string(),
- ];
-
- let result = get_insights_by_batch(&pool, user_id, &non_existent_insight_ids).await;
-
- // Should return an IncompleteInsights error
- assert!(result.is_err());
- match result.unwrap_err() {
- BatchError::IncompleteInsights {
- expected,
- actual,
- user_id: error_user_id,
- } => {
- assert_eq!(expected, 2);
- assert_eq!(actual, 0);
- assert_eq!(error_user_id, user_id);
- }
- _ => panic!("Expected IncompleteInsights error"),
- }
-
- Ok(())
- }
-
- #[test]
- fn test_validation_logic() {
- // Test that validation logic works correctly
- let error = BatchError::IncompleteInsights {
- expected: 3,
- actual: 1,
- user_id: "test_user".to_string(),
- };
-
- let error_msg = error.to_string();
- assert!(error_msg.contains("Expected 3 insights"));
- assert!(error_msg.contains("but got 1"));
- assert!(error_msg.contains("Some insights may have been deleted"));
- assert!(error_msg.contains("test_user"));
-
- match error {
- BatchError::IncompleteInsights {
- expected,
- actual,
- user_id,
- } => {
- assert_eq!(expected, 3);
- assert_eq!(actual, 1);
- assert_eq!(user_id, "test_user");
- }
- _ => panic!("Wrong error type"),
- }
- }
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insight/user/create.rs b/rust/cloud-storage/macro_db_client/src/insight/user/create.rs
deleted file mode 100644
index b592d9472e..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/user/create.rs
+++ /dev/null
@@ -1,430 +0,0 @@
-use model::insight_context::UserInsightRecord;
-use serde_json;
-use sqlx::Executor;
-use sqlx::error::Error;
-use sqlx::postgres::Postgres;
-
-#[tracing::instrument(skip(db))]
-pub async fn create_insights<'e, E>(
- db: E,
- insights: &Vec<UserInsightRecord>,
- user_id: &str,
-) -> Result<Vec<String>, Error>
-where
- E: Executor<'e, Database = Postgres>,
-{
- if insights.is_empty() {
- return Ok(vec![]);
- }
-
- let mut query_builder = sqlx::QueryBuilder::new(
- r#"INSERT INTO "UserInsights" ("userId", content, source, generated, confidence, "sourceLocation", "insightType", "relevanceKeywords", "spanStart", "spanEnd") "#,
- );
-
- query_builder.push_values(insights.iter(), |mut b, insight| {
- b.push_bind(user_id)
- .push_bind(&insight.content)
- .push_bind(insight.source.to_string())
- .push_bind(insight.generated)
- .push_bind(insight.confidence)
- .push_bind(
- insight
- .source_location
- .as_ref()
- .map(|loc| serde_json::to_value(loc).unwrap()),
- )
- .push_bind(insight.insight_type.as_ref().map(|it| it.to_string()))
- .push_bind(&insight.relevance_keywords)
- .push_bind(insight.span_start)
- .push_bind(insight.span_end);
- });
-
- query_builder.push(" RETURNING id");
-
- let ids = query_builder
- .build_query_scalar::<String>()
- .fetch_all(db)
- .await?;
- Ok(ids)
-}
-
-#[cfg(test)]
-mod insight_tests {
- use super::*;
- use crate::insight::user::read::get_insight;
- use chrono::Utc;
- use model::insight_context::{EmailSourceLocation, SourceLocation, UserInsightRecord};
- use sqlx::{Pool, Postgres};
- use uuid::Uuid;
-
- #[sqlx::test(fixtures(path = "../fixtures"))]
- async fn test_create_insights_with_source_location(pool: Pool<Postgres>) -> anyhow::Result<()> {
- // Insert a user for FK constraint
- sqlx::query!(
- r#"INSERT INTO "User" (id, email) VALUES ($1, $2) ON CONFLICT DO NOTHING"#,
- )
- .execute(&pool)
- .await?;
-
- let now = Utc::now();
- let insight = UserInsightRecord {
- id: None,
- user_id: "macro|[email protected]".to_string(),
- content: "Test content".to_string(),
- source: "test_source".to_string(),
- generated: true,
- created_at: now,
- updated_at: now,
- span_start: None,
- span_end: None,
- confidence: Some(5), // High confidence on 1-5 scale
- source_location: Some(SourceLocation::Email(EmailSourceLocation {
- thread_ids: vec![],
- message_ids: vec![],
- email_addresses: None,
- })),
- insight_type: Some(model::insight_context::InsightType::Actionable),
- relevance_keywords: Some(vec!["test".to_string(), "email".to_string()]),
- };
- let ids = create_insights(&pool, &vec![insight.clone()], &insight.user_id).await?;
- assert_eq!(ids.len(), 1);
- // Fetch and check
- let rec = sqlx::query!(r#"SELECT content, source, generated, confidence, "sourceLocation" FROM "UserInsights" WHERE id = $1"#, ids[0]).fetch_one(&pool).await?;
- assert_eq!(rec.content, insight.content);
- assert_eq!(rec.source, insight.source);
- assert_eq!(rec.generated, insight.generated);
- assert_eq!(rec.confidence, Some(5));
- let loc: SourceLocation = serde_json::from_value(rec.sourceLocation.unwrap()).unwrap();
- assert_eq!(loc, insight.source_location.unwrap());
- Ok(())
- }
-
- #[sqlx::test(fixtures(path = "../fixtures"))]
- async fn test_create_and_get_insight_with_source_location(
- pool: Pool<Postgres>,
- ) -> anyhow::Result<()> {
- // Insert a user for FK constraint
- sqlx::query!(
- r#"INSERT INTO "User" (id, email) VALUES ($1, $2) ON CONFLICT DO NOTHING"#,
- )
- .execute(&pool)
- .await?;
-
- let now = Utc::now();
- let insight = UserInsightRecord {
- id: None,
- user_id: "macro|[email protected]".to_string(),
- content: "Test content for get_insight".to_string(),
- source: "test_source".to_string(),
- generated: true,
- created_at: now,
- updated_at: now,
- span_start: None,
- span_end: None,
- confidence: Some(5),
- source_location: Some(SourceLocation::Email(EmailSourceLocation {
- thread_ids: vec![],
- message_ids: vec![
- Uuid::parse_str("11111111-1111-1111-1111-111111111111")
- .unwrap()
- .to_string(),
- ],
- email_addresses: None,
- })),
- insight_type: Some(model::insight_context::InsightType::Informational),
- relevance_keywords: Some(vec!["testing".to_string(), "source_location".to_string()]),
- };
- let ids = create_insights(&pool, &vec![insight.clone()], &insight.user_id).await?;
- assert_eq!(ids.len(), 1);
- let id = &ids[0];
- let found = get_insight(&pool, id, &insight.user_id).await?;
- assert!(found.is_some());
- let found = found.unwrap();
- // The DB sets id, created_at, updated_at, so update our expected record for comparison
- let mut expected = insight.clone();
- expected.id = Some(id.clone());
- expected.created_at = found.created_at;
- expected.updated_at = found.updated_at;
- assert_eq!(found, expected);
- Ok(())
- }
-
- #[sqlx::test(fixtures(path = "../fixtures"))]
- async fn test_create_insights_with_relevance_keywords_array(
- pool: Pool<Postgres>,
- ) -> anyhow::Result<()> {
- // Insert a user for FK constraint
- sqlx::query!(
- r#"INSERT INTO "User" (id, email) VALUES ($1, $2) ON CONFLICT DO NOTHING"#,
- )
- .execute(&pool)
- .await?;
-
- let now = Utc::now();
-
- // Test different array scenarios
- let insights = vec![
- // Insight with multiple keywords
- UserInsightRecord {
- id: None,
- user_id: "macro|[email protected]".to_string(),
- content: "User prefers morning meetings and uses Slack for communication"
- .to_string(),
- source: "email_analysis".to_string(),
- generated: true,
- created_at: now,
- updated_at: now,
- span_start: None,
- span_end: None,
- confidence: Some(4),
- source_location: None,
- insight_type: Some(model::insight_context::InsightType::Actionable),
- relevance_keywords: Some(vec![
- "meetings".to_string(),
- "morning".to_string(),
- "slack".to_string(),
- "communication".to_string(),
- "preferences".to_string(),
- ]),
- },
- // Insight with single keyword
- UserInsightRecord {
- id: None,
- user_id: "macro|[email protected]".to_string(),
- content: "User is a software developer".to_string(),
- source: "profile_analysis".to_string(),
- generated: true,
- created_at: now,
- updated_at: now,
- span_start: None,
- span_end: None,
- confidence: Some(5),
- source_location: None,
- insight_type: Some(model::insight_context::InsightType::Informational),
- relevance_keywords: Some(vec!["developer".to_string()]),
- },
- // Insight with no keywords (None)
- UserInsightRecord {
- id: None,
- user_id: "macro|[email protected]".to_string(),
- content: "User behavior pattern detected".to_string(),
- source: "behavior_analysis".to_string(),
- generated: true,
- created_at: now,
- updated_at: now,
- span_start: None,
- span_end: None,
- confidence: Some(3),
- source_location: None,
- insight_type: Some(model::insight_context::InsightType::Trend),
- relevance_keywords: None,
- },
- // Insight with empty array
- UserInsightRecord {
- id: None,
- user_id: "macro|[email protected]".to_string(),
- content: "Empty keywords test".to_string(),
- source: "test_source".to_string(),
- generated: false,
- created_at: now,
- updated_at: now,
- span_start: None,
- span_end: None,
- confidence: Some(2),
- source_location: None,
- insight_type: Some(model::insight_context::InsightType::Warning),
- relevance_keywords: Some(vec![]),
- },
- ];
-
- // Create all insights at once
- let ids = create_insights(&pool, &insights, "macro|[email protected]").await?;
- assert_eq!(ids.len(), 4);
-
- // Verify each insight was stored correctly by fetching from database
- for (i, id) in ids.iter().enumerate() {
- let stored = get_insight(&pool, id, "macro|[email protected]").await?;
- assert!(stored.is_some());
- let stored = stored.unwrap();
-
- // Verify the relevance_keywords array matches what we inserted
- match i {
- 0 => {
- // Multiple keywords case
- let keywords = stored.relevance_keywords.as_ref().unwrap();
- assert_eq!(keywords.len(), 5);
- assert!(keywords.contains(&"meetings".to_string()));
- assert!(keywords.contains(&"morning".to_string()));
- assert!(keywords.contains(&"slack".to_string()));
- assert!(keywords.contains(&"communication".to_string()));
- assert!(keywords.contains(&"preferences".to_string()));
- assert_eq!(
- stored.insight_type,
- Some(model::insight_context::InsightType::Actionable)
- );
- }
- 1 => {
- // Single keyword case
- let keywords = stored.relevance_keywords.as_ref().unwrap();
- assert_eq!(keywords.len(), 1);
- assert_eq!(keywords[0], "developer");
- assert_eq!(
- stored.insight_type,
- Some(model::insight_context::InsightType::Informational)
- );
- }
- 2 => {
- // None keywords case
- assert!(stored.relevance_keywords.is_none());
- assert_eq!(
- stored.insight_type,
- Some(model::insight_context::InsightType::Trend)
- );
- }
- 3 => {
- // Empty array case
- let keywords = stored.relevance_keywords.as_ref().unwrap();
- assert_eq!(keywords.len(), 0);
- assert_eq!(
- stored.insight_type,
- Some(model::insight_context::InsightType::Warning)
- );
- }
- _ => unreachable!(),
- }
- }
-
- // Test direct database query to verify array storage
- let raw_results = sqlx::query!(
- r#"SELECT content, "relevanceKeywords", "insightType" FROM "UserInsights" WHERE id = ANY($1) ORDER BY content"#,
- &ids
- )
- .fetch_all(&pool)
- .await?;
-
- assert_eq!(raw_results.len(), 4);
-
- // Verify the first result (multiple keywords) directly from DB
- let first_result = &raw_results[3]; // "User prefers morning meetings..." (sorted by content)
- assert!(first_result.relevanceKeywords.is_some());
- let db_keywords = first_result.relevanceKeywords.as_ref().unwrap();
- assert_eq!(db_keywords.len(), 5);
- assert_eq!(first_result.insightType.as_ref().unwrap(), "actionable");
-
- Ok(())
- }
-
- #[sqlx::test(fixtures(path = "../fixtures"))]
- async fn test_create_insights_with_span_data(pool: Pool<Postgres>) -> anyhow::Result<()> {
- // Insert a user for FK constraint
- sqlx::query!(
- r#"INSERT INTO "User" (id, email) VALUES ($1, $2) ON CONFLICT DO NOTHING"#,
- )
- .execute(&pool)
- .await?;
-
- let now = Utc::now();
- let span_start_time = now - chrono::Duration::hours(2);
- let span_end_time = now - chrono::Duration::hours(1);
- let insight = UserInsightRecord {
- id: None,
- user_id: "macro|[email protected]".to_string(),
- content: "Test content with span data".to_string(),
- source: "test_source".to_string(),
- generated: true,
- created_at: now,
- updated_at: now,
- span_start: Some(span_start_time),
- span_end: Some(span_end_time),
- confidence: Some(4),
- source_location: None,
- insight_type: Some(model::insight_context::InsightType::Actionable),
- relevance_keywords: Some(vec!["span".to_string(), "test".to_string()]),
- };
-
- let ids = create_insights(&pool, &vec![insight.clone()], &insight.user_id).await?;
- assert_eq!(ids.len(), 1);
-
- // Verify span data was stored correctly
- let rec = sqlx::query!(
- r#"SELECT content, "spanStart", "spanEnd" FROM "UserInsights" WHERE id = $1"#,
- ids[0]
- )
- .fetch_one(&pool)
- .await?;
-
- assert_eq!(rec.content, insight.content);
- assert!(rec.spanStart.is_some());
- assert!(rec.spanEnd.is_some());
-
- // Test with get_insight to ensure round-trip works
- let found = get_insight(&pool, &ids[0], &insight.user_id).await?;
- assert!(found.is_some());
- let found = found.unwrap();
- assert!(found.span_start.is_some());
- assert!(found.span_end.is_some());
-
- Ok(())
- }
-
- #[sqlx::test(fixtures(path = "../fixtures"))]
- async fn test_create_insights_with_null_span_data(pool: Pool<Postgres>) -> anyhow::Result<()> {
- // Insert a user for FK constraint
- sqlx::query!(
- r#"INSERT INTO "User" (id, email) VALUES ($1, $2) ON CONFLICT DO NOTHING"#,
- )
- .execute(&pool)
- .await?;
-
- let now = Utc::now();
- let insight = UserInsightRecord {
- id: None,
- user_id: "macro|[email protected]".to_string(),
- content: "Test content without span data".to_string(),
- source: "test_source".to_string(),
- generated: true,
- created_at: now,
- updated_at: now,
- span_start: None,
- span_end: None,
- confidence: Some(3),
- source_location: None,
- insight_type: Some(model::insight_context::InsightType::Informational),
- relevance_keywords: Some(vec!["no_span".to_string()]),
- };
-
- let ids = create_insights(&pool, &vec![insight.clone()], &insight.user_id).await?;
- assert_eq!(ids.len(), 1);
-
- // Verify NULL span data was stored correctly
- let rec = sqlx::query!(
- r#"SELECT content, "spanStart", "spanEnd" FROM "UserInsights" WHERE id = $1"#,
- ids[0]
- )
- .fetch_one(&pool)
- .await?;
-
- assert_eq!(rec.content, insight.content);
- assert!(rec.spanStart.is_none());
- assert!(rec.spanEnd.is_none());
-
- // Test with get_insight to ensure round-trip works
- let found = get_insight(&pool, &ids[0], &insight.user_id).await?;
- assert!(found.is_some());
- let found = found.unwrap();
- assert!(found.span_start.is_none());
- assert!(found.span_end.is_none());
-
- Ok(())
- }
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insight/user/delete.rs b/rust/cloud-storage/macro_db_client/src/insight/user/delete.rs
deleted file mode 100644
index d60f77e0ee..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/user/delete.rs
+++ /dev/null
@@ -1,49 +0,0 @@
-use sqlx::Executor;
-use sqlx::error::Error;
-use sqlx::postgres::Postgres;
-
-#[tracing::instrument(skip(db))]
-pub async fn delete_insights<'e, E>(db: E, ids: &Vec<String>) -> Result<(), Error>
-where
- E: Executor<'e, Database = Postgres>,
-{
- sqlx::query(
- r#"
- DELETE FROM "UserInsights"
- WHERE "id" = ANY($1)
- "#,
- )
- .bind(ids)
- .execute(db)
- .await?;
- Ok(())
-}
-
-pub async fn delete_user_insights<'e, E>(
- db: E,
- ids: &[String],
- user_id: &str,
-) -> Result<Vec<String>, anyhow::Error>
-where
- E: Executor<'e, Database = Postgres>,
-{
- let records = sqlx::query!(
- r#"
- DELETE FROM "UserInsights"
- WHERE
- "userId" = $1
- AND
- "id" = ANY($2)
- RETURNING
- "id"
- "#,
- user_id,
- ids
- )
- .fetch_all(db)
- .await?;
-
- let ids = records.into_iter().map(|r| r.id).collect();
-
- Ok(ids)
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insight/user/mod.rs b/rust/cloud-storage/macro_db_client/src/insight/user/mod.rs
deleted file mode 100644
index 65d733fb4a..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/user/mod.rs
+++ /dev/null
@@ -1,11 +0,0 @@
-mod batch;
-mod create;
-mod delete;
-mod read;
-mod update;
-
-pub use batch::*;
-pub use create::*;
-pub use delete::*;
-pub use read::*;
-pub use update::*;
diff --git a/rust/cloud-storage/macro_db_client/src/insight/user/read.rs b/rust/cloud-storage/macro_db_client/src/insight/user/read.rs
deleted file mode 100644
index 332f6da830..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/user/read.rs
+++ /dev/null
@@ -1,383 +0,0 @@
-use anyhow::Result;
-use model::insight_context::{InsightType, SourceLocation, UserInsightRecord, UserInsightRow};
-use sqlx::Executor;
-use sqlx::postgres::Postgres;
-use sqlx::types::Json;
-
-#[tracing::instrument(skip(db))]
-pub async fn read_recent_insights<'e, E>(
- db: E,
- user_id: &str,
- limit: i64,
- source: String,
-) -> Result<Vec<UserInsightRecord>>
-where
- E: Executor<'e, Database = Postgres>,
-{
- let records = sqlx::query_as!(
- UserInsightRow,
- r#"
- SELECT
- "id",
- "userId" as "user_id",
- "content",
- "source",
- "sourceLocation" as "source_location: Json<SourceLocation>",
- "generated",
- "createdAt"::timestamptz as "created_at!",
- "updatedAt"::timestamptz as "updated_at!",
- "spanStart"::timestamptz as "span_start",
- "spanEnd"::timestamptz as "span_end",
- "confidence",
- "insightType" as "insight_type: InsightType",
- "relevanceKeywords" as "relevance_keywords"
- FROM
- "UserInsights" u
- WHERE
- u."userId" = $1
- AND
- u."source" = $2
- ORDER BY
- u."createdAt" DESC
- LIMIT $3
- "#,
- user_id,
- source,
- limit,
- )
- .fetch_all(db)
- .await?;
-
- let insights = records.into_iter().map(|r| r.into()).collect();
-
- Ok(insights)
-}
-
-/// Read insights with smart ranking for LLM context selection
-#[tracing::instrument(skip(db))]
-pub async fn read_insights_for_context<'e, E>(
- db: E,
- user_id: &str,
- source: String,
- query_keywords: Option<Vec<String>>,
- prefer_actionable: bool,
- max_insights: usize,
-) -> Result<Vec<UserInsightRecord>>
-where
- E: Executor<'e, Database = Postgres>,
-{
- // First, get all insights for the user and source (with a reasonable limit)
- let all_insights = read_recent_insights(db, user_id, 1000, source).await?;
-
- // Then apply smart ranking
- // Note: This would need to import from insight_service crate
- // For now, we'll just return the insights ordered by confidence and recency
- let mut ranked_insights = all_insights;
- ranked_insights.sort_by(|a, b| {
- // Sort by confidence (desc) then by created_at (desc)
- let conf_a = a.confidence.unwrap_or(0);
- let conf_b = b.confidence.unwrap_or(0);
- match conf_b.cmp(&conf_a) {
- std::cmp::Ordering::Equal => b.created_at.cmp(&a.created_at),
- other => other,
- }
- });
-
- ranked_insights.truncate(max_insights);
-
- Ok(ranked_insights)
-}
-
-#[tracing::instrument(skip(db))]
-pub async fn get_user_insights<'e, E>(
- db: E,
- user_id: &str,
- generated: Option<bool>,
- limit: u32,
- offset: u32,
-) -> Result<Vec<UserInsightRecord>>
-where
- E: Executor<'e, Database = Postgres>,
-{
- match generated {
- Some(filter) => {
- let records = sqlx::query_as!(
- UserInsightRow,
- r#"
- SELECT
- "id",
- "userId" as "user_id",
- "content",
- "source",
- "sourceLocation" as "source_location: Json<SourceLocation>",
- "generated",
- "createdAt"::timestamptz as "created_at!",
- "updatedAt"::timestamptz as "updated_at!",
- "spanStart"::timestamptz as "span_start",
- "spanEnd"::timestamptz as "span_end",
- "confidence",
- "insightType" as "insight_type: InsightType",
- "relevanceKeywords" as "relevance_keywords"
- FROM
- "UserInsights"
- WHERE
- "userId" = $1
- AND
- generated = $2
- ORDER BY
- "updatedAt" DESC
- LIMIT
- $3
- OFFSET
- $4
- "#,
- user_id,
- filter,
- limit as i64,
- offset as i64
- )
- .fetch_all(db)
- .await?;
-
- let records = records.into_iter().map(|r| r.into()).collect();
- Ok(records)
- }
-
- None => {
- let records = sqlx::query_as!(
- UserInsightRow,
- r#"
- SELECT
- "id",
- "userId" as "user_id",
- "content",
- "source",
- "sourceLocation" as "source_location: Json<SourceLocation>",
- "generated",
- "createdAt"::timestamptz as "created_at!",
- "updatedAt"::timestamptz as "updated_at!",
- "spanStart"::timestamptz as "span_start",
- "spanEnd"::timestamptz as "span_end",
- "confidence",
- "insightType" as "insight_type: InsightType",
- "relevanceKeywords" as "relevance_keywords"
- FROM
- "UserInsights"
- WHERE
- "userId" = $1
- ORDER BY
- "updatedAt" DESC
- LIMIT
- $2
- OFFSET
- $3
- "#,
- user_id,
- limit as i64,
- offset as i64
- )
- .fetch_all(db)
- .await?;
-
- let records = records.into_iter().map(|r| r.into()).collect();
- Ok(records)
- }
- }
-}
-
-#[tracing::instrument(skip(db))]
-pub async fn get_insight<'e, E>(db: E, id: &str, user_id: &str) -> Result<Option<UserInsightRecord>>
-where
- E: Executor<'e, Database = Postgres>,
-{
- let record = sqlx::query_as!(
- UserInsightRow,
- r#"
- SELECT
- "id",
- "userId" as "user_id",
- "content",
- "source",
- "sourceLocation" as "source_location: Json<SourceLocation>",
- "generated",
- "createdAt"::timestamptz as "created_at!",
- "updatedAt"::timestamptz as "updated_at!",
- "spanStart"::timestamptz as "span_start",
- "spanEnd"::timestamptz as "span_end",
- "confidence",
- "insightType" as "insight_type: InsightType",
- "relevanceKeywords" as "relevance_keywords"
- FROM
- "UserInsights"
- WHERE
- "userId" = $1
- AND
- "id" = $2
- "#,
- user_id,
- id
- )
- .fetch_optional(db)
- .await?;
-
- let record = record.map(|r| r.into());
-
- Ok(record)
-}
-
-pub async fn count_total<'e, E>(db: E, generated: Option<bool>, user_id: &str) -> Result<i64>
-where
- E: Executor<'e, Database = Postgres>,
-{
- if let Some(generated) = generated {
- let count = sqlx::query!(
- r#"
- SELECT
- COUNT(id) as count
- FROM
- "UserInsights" i
- WHERE
- i."userId" = $1
- AND
- i."generated" = $2
- "#,
- user_id,
- generated
- )
- .fetch_one(db)
- .await?;
-
- Ok(count.count.ok_or_else(|| sqlx::Error::RowNotFound)?)
- } else {
- let count = sqlx::query!(
- r#"
- SELECT
- COUNT(id) as count
- FROM
- "UserInsights" i
- WHERE
- i."userId" = $1
- "#,
- user_id,
- )
- .fetch_one(db)
- .await?;
- Ok(count.count.ok_or_else(|| sqlx::Error::RowNotFound)?)
- }
-}
-
-#[cfg(test)]
-mod insight_tests {
- use super::*;
- use sqlx::{Pool, Postgres};
-
- #[sqlx::test(fixtures(path = "../fixtures", scripts("user_insights")))]
- async fn test_read_recent_insights(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = "macro|[email protected]";
- let source = "test_source";
- let results = read_recent_insights(&pool, user_id, 10, source.to_string()).await?;
- assert_eq!(results.len(), 2);
- let expected1 = UserInsightRecord {
- id: Some("insight1".to_string()),
- user_id: user_id.to_string(),
- content: "Insight content 1".to_string(),
- source: source.to_string(),
- generated: true,
- created_at: results[0].created_at,
- updated_at: results[0].updated_at,
- span_start: results[0].span_start,
- span_end: results[0].span_end,
- confidence: Some(5),
- source_location: results[0].source_location.clone(),
- insight_type: results[0].insight_type,
- relevance_keywords: results[0].relevance_keywords.clone(),
- };
- let expected2 = UserInsightRecord {
- id: Some("insight2".to_string()),
- user_id: user_id.to_string(),
- content: "Insight content 2".to_string(),
- source: source.to_string(),
- generated: false,
- created_at: results[1].created_at,
- updated_at: results[1].updated_at,
- span_start: results[1].span_start,
- span_end: results[1].span_end,
- confidence: Some(1),
- source_location: results[1].source_location.clone(),
- insight_type: results[1].insight_type,
- relevance_keywords: results[1].relevance_keywords.clone(),
- };
- assert_eq!(results[0], expected1);
- assert_eq!(results[1], expected2);
- Ok(())
- }
-
- #[sqlx::test(fixtures(path = "../fixtures", scripts("user_insights")))]
- async fn test_get_user_insights(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = "macro|[email protected]";
- let all = get_user_insights(&pool, user_id, None, 10, 0).await?;
- assert_eq!(all.len(), 2);
- let expected1 = UserInsightRecord {
- id: Some("insight1".to_string()),
- user_id: user_id.to_string(),
- content: "Insight content 1".to_string(),
- source: "test_source".to_string(),
- generated: true,
- created_at: all[0].created_at,
- updated_at: all[0].updated_at,
- span_start: all[0].span_start,
- span_end: all[0].span_end,
- confidence: Some(5),
- source_location: all[0].source_location.clone(),
- insight_type: all[0].insight_type,
- relevance_keywords: all[0].relevance_keywords.clone(),
- };
- let expected2 = UserInsightRecord {
- id: Some("insight2".to_string()),
- user_id: user_id.to_string(),
- content: "Insight content 2".to_string(),
- source: "test_source".to_string(),
- generated: false,
- created_at: all[1].created_at,
- updated_at: all[1].updated_at,
- span_start: all[1].span_start,
- span_end: all[1].span_end,
- confidence: Some(1),
- source_location: all[1].source_location.clone(),
- insight_type: all[1].insight_type,
- relevance_keywords: all[1].relevance_keywords.clone(),
- };
- assert_eq!(all[0], expected1);
- assert_eq!(all[1], expected2);
- let generated = get_user_insights(&pool, user_id, Some(true), 10, 0).await?;
- assert_eq!(generated.len(), 1);
- assert_eq!(generated[0], expected1);
- Ok(())
- }
-
- #[sqlx::test(fixtures(path = "../fixtures", scripts("user_insights")))]
- async fn test_get_insight(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = "macro|[email protected]";
- let id = "insight1";
- let found = get_insight(&pool, id, user_id).await?;
- assert!(found.is_some());
- let record = found.unwrap();
- let expected = UserInsightRecord {
- id: Some(id.to_string()),
- user_id: user_id.to_string(),
- content: "Insight content 1".to_string(),
- source: "test_source".to_string(),
- generated: true,
- created_at: record.created_at,
- updated_at: record.updated_at,
- span_start: record.span_start,
- span_end: record.span_end,
- confidence: Some(5),
- source_location: record.source_location.clone(),
- insight_type: record.insight_type,
- relevance_keywords: record.relevance_keywords.clone(),
- };
- assert_eq!(record, expected);
- Ok(())
- }
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insight/user/update.rs b/rust/cloud-storage/macro_db_client/src/insight/user/update.rs
deleted file mode 100644
index bb7f7eb9a9..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insight/user/update.rs
+++ /dev/null
@@ -1,121 +0,0 @@
-use super::create_insights;
-use anyhow::Result;
-use chrono::Utc;
-use model::insight_context::UserInsightRecord;
-use sqlx::Executor;
-use sqlx::Pool;
-use sqlx::postgres::Postgres;
-
-#[tracing::instrument(skip(db))]
-pub async fn update_insights<'e, E>(
- db: E,
- user_id: &str,
- insights: Vec<UserInsightRecord>,
-) -> Result<Vec<String>>
-where
- E: Executor<'e, Database = Postgres>,
-{
- if insights.iter().any(|insight| insight.id.is_none()) {
- return Err(anyhow::anyhow!("expected all updates to have ids"));
- }
-
- let now = Utc::now().naive_utc();
- let (id, c, g, created, s, e, confidence, source) = insights
- .into_iter()
- .map(|i| {
- (
- i.id.unwrap(),
- i.content,
- i.generated,
- i.created_at.naive_utc(),
- i.span_start.map(|t| t.naive_utc()),
- i.span_end.map(|t| t.naive_utc()),
- i.confidence,
- i.source.to_string(),
- )
- })
- .collect::<(
- Vec<_>,
- Vec<_>,
- Vec<_>,
- Vec<_>,
- Vec<_>,
- Vec<_>,
- Vec<_>,
- Vec<_>,
- )>();
-
- let records = sqlx::query!(
- r#"
- UPDATE "UserInsights" ui
- SET
- content = d.content,
- generated = d.generated,
- "updatedAt" = $10,
- "createdAt" = d.created_at,
- "spanStart" = d.span_start,
- "spanEnd" = d.span_end,
- source = d.source,
- confidence = d.confidence
- FROM (
- SELECT
- UNNEST($1::TEXT[]) as id,
- UNNEST($2::TEXT[]) as content,
- UNNEST($3::BOOLEAN[]) as generated,
- UNNEST($4::TIMESTAMP[]) as created_at,
- UNNEST($5::TIMESTAMP[]) as span_start,
- UNNEST($6::TIMESTAMP[]) as span_end,
- UNNEST($7::INT[]) as confidence,
- UNNEST($8::TEXT[]) as source
- ) AS d
- WHERE
- ui.id = d.id
- AND
- ui."userId" = $9
- RETURNING
- ui.id
- "#,
- &id,
- &c,
- &g,
- &created,
- s.as_slice() as _,
- e.as_slice() as _,
- confidence.as_slice() as _,
- &source,
- user_id,
- now
- )
- .fetch_all(db)
- .await?;
-
- let updated_ids = records.into_iter().map(|rec| rec.id).collect();
-
- Ok(updated_ids)
-}
-
-#[tracing::instrument(skip(db))]
-pub async fn replace_insights(
- db: &Pool<Postgres>,
- ids: &[String],
- insights: &Vec<UserInsightRecord>,
- user_id: &str,
-) -> Result<(), sqlx::Error> {
- let mut tsx = db.begin().await?;
- sqlx::query!(
- r#"
- DELETE FROM
- "UserInsights"
- WHERE
- id = ANY($1)
- "#,
- ids
- )
- .execute(&mut *tsx)
- .await?;
-
- create_insights(&mut *tsx, insights, user_id).await?;
-
- tsx.commit().await?;
- Ok(())
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insights_backfill/batch/get.rs b/rust/cloud-storage/macro_db_client/src/insights_backfill/batch/get.rs
deleted file mode 100644
index f1e134fff7..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insights_backfill/batch/get.rs
+++ /dev/null
@@ -1,124 +0,0 @@
-use anyhow::Result;
-use model::insight_context::insights_backfill::{
- EmailInsightsBackfillBatch, InsightsBackfillBatchStatus,
-};
-use sqlx::PgPool;
-
-pub async fn get_insights_backfill_batch_by_id(
- pool: &PgPool,
- batch_id: &str,
-) -> Result<Option<EmailInsightsBackfillBatch>> {
- let batch = sqlx::query_as!(
- EmailInsightsBackfillBatch,
- r#"
- SELECT
- id,
- "insightsBackfillJobId" as insights_backfill_job_id,
- "sqsMessageId" as sqs_message_id,
- "threadIds" as thread_ids,
- "totalThreads" as total_threads,
- status as "status!: InsightsBackfillBatchStatus",
- "insightsGeneratedCount" as insights_generated_count,
- "insightIds" as insight_ids,
- "errorMessage" as error_message,
- "queuedAt"::timestamptz as queued_at,
- "startedAt"::timestamptz as started_at,
- "completedAt"::timestamptz as completed_at,
- "createdAt"::timestamptz as "created_at!",
- "updatedAt"::timestamptz as "updated_at!"
- FROM "EmailInsightsBackfillBatch"
- WHERE id = $1
- "#,
- batch_id
- )
- .fetch_optional(pool)
- .await?;
-
- Ok(batch)
-}
-
-#[cfg(test)]
-mod insight_backfill_tests {
- use super::*;
- use model::insight_context::insights_backfill::InsightsBackfillBatchStatus;
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_get_insights_backfill_batch_by_id_exists(pool: sqlx::PgPool) {
- let result = get_insights_backfill_batch_by_id(&pool, "test-batch-1").await;
-
- assert!(result.is_ok());
- let batch = result.unwrap();
- assert!(batch.is_some());
-
- let batch = batch.unwrap();
- assert_eq!(batch.id, "test-batch-1");
- assert_eq!(batch.insights_backfill_job_id, "test-job-1");
- assert_eq!(batch.total_threads, 3);
- assert_eq!(batch.status, InsightsBackfillBatchStatus::Complete);
- assert_eq!(batch.insights_generated_count, 5);
- assert!(batch.thread_ids.is_some());
- assert_eq!(batch.thread_ids.as_ref().unwrap().len(), 3);
- assert!(batch.completed_at.is_some());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_get_insights_backfill_batch_by_id_in_progress(pool: sqlx::PgPool) {
- let result = get_insights_backfill_batch_by_id(&pool, "test-batch-2").await;
-
- assert!(result.is_ok());
- let batch = result.unwrap();
- assert!(batch.is_some());
-
- let batch = batch.unwrap();
- assert_eq!(batch.id, "test-batch-2");
- assert_eq!(batch.status, InsightsBackfillBatchStatus::InProgress);
- assert_eq!(batch.insights_generated_count, 0);
- assert!(batch.started_at.is_some());
- assert!(batch.completed_at.is_none());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_get_insights_backfill_batch_by_id_failed(pool: sqlx::PgPool) {
- let result = get_insights_backfill_batch_by_id(&pool, "test-batch-failed").await;
-
- assert!(result.is_ok());
- let batch = result.unwrap();
- assert!(batch.is_some());
-
- let batch = batch.unwrap();
- assert_eq!(batch.id, "test-batch-failed");
- assert_eq!(batch.status, InsightsBackfillBatchStatus::Failed);
- assert!(batch.error_message.is_some());
- assert_eq!(
- batch.error_message.as_ref().unwrap(),
- "Processing error occurred"
- );
- assert!(batch.completed_at.is_some());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_get_insights_backfill_batch_by_id_queued(pool: sqlx::PgPool) {
- let result = get_insights_backfill_batch_by_id(&pool, "test-batch-queued").await;
-
- assert!(result.is_ok());
- let batch = result.unwrap();
- assert!(batch.is_some());
-
- let batch = batch.unwrap();
- assert_eq!(batch.id, "test-batch-queued");
- assert_eq!(batch.status, InsightsBackfillBatchStatus::Queued);
- assert_eq!(batch.insights_generated_count, 0);
- assert!(batch.queued_at.is_none());
- assert!(batch.started_at.is_none());
- assert!(batch.completed_at.is_none());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_get_insights_backfill_batch_by_id_not_found(pool: sqlx::PgPool) {
- let result = get_insights_backfill_batch_by_id(&pool, "non-existent-batch").await;
-
- assert!(result.is_ok());
- let batch = result.unwrap();
- assert!(batch.is_none());
- }
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insights_backfill/batch/insert.rs b/rust/cloud-storage/macro_db_client/src/insights_backfill/batch/insert.rs
deleted file mode 100644
index 1ffcd3c2ba..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insights_backfill/batch/insert.rs
+++ /dev/null
@@ -1,128 +0,0 @@
-use anyhow::Result;
-use sqlx::PgPool;
-
-pub async fn create_insights_backfill_batch_with_id(
- pool: &PgPool,
- batch_id: &str,
- job_id: &str,
- thread_ids: &[String],
- sqs_message_id: Option<&str>,
-) -> Result<()> {
- let total_threads = thread_ids.len() as i32;
-
- sqlx::query!(
- r#"
- INSERT INTO "EmailInsightsBackfillBatch" (
- id,
- "insightsBackfillJobId",
- "sqsMessageId",
- "threadIds",
- "totalThreads",
- status,
- "queuedAt",
- "createdAt",
- "updatedAt"
- ) VALUES (
- $1, $2, $3, $4, $5, 'Queued'::"insights_backfill_batch_status", NOW(), NOW(), NOW()
- )
- "#,
- batch_id,
- job_id,
- sqs_message_id,
- thread_ids,
- total_threads,
- )
- .execute(pool)
- .await?;
-
- Ok(())
-}
-
-#[cfg(test)]
-mod insight_backfill_tests {
- use super::*;
- use crate::insights_backfill::batch::get::get_insights_backfill_batch_by_id;
- use model::insight_context::insights_backfill::InsightsBackfillBatchStatus;
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_create_insights_backfill_batch_with_id(pool: sqlx::PgPool) {
- let batch_id = "new-test-batch";
- let job_id = "test-job-1";
- let thread_ids = vec![
- "thread10".to_string(),
- "thread11".to_string(),
- "thread12".to_string(),
- ];
-
- let result =
- create_insights_backfill_batch_with_id(&pool, batch_id, job_id, &thread_ids, None)
- .await;
- assert!(result.is_ok());
-
- // Verify the batch was created
- let batch = get_insights_backfill_batch_by_id(&pool, batch_id)
- .await
- .unwrap();
- assert!(batch.is_some());
-
- let batch = batch.unwrap();
- assert_eq!(batch.id, batch_id);
- assert_eq!(batch.insights_backfill_job_id, job_id);
- assert_eq!(batch.total_threads, 3);
- assert_eq!(batch.status, InsightsBackfillBatchStatus::Queued);
- assert_eq!(batch.insights_generated_count, 0);
- assert!(batch.thread_ids.is_some());
- assert_eq!(batch.thread_ids.unwrap(), thread_ids);
- assert!(batch.queued_at.is_some());
- assert!(batch.started_at.is_none());
- assert!(batch.completed_at.is_none());
- assert!(batch.error_message.is_none());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_create_insights_backfill_batch_empty_threads(pool: sqlx::PgPool) {
- let batch_id = "empty-batch";
- let job_id = "test-job-1";
- let thread_ids: Vec<String> = vec![];
-
- let result =
- create_insights_backfill_batch_with_id(&pool, batch_id, job_id, &thread_ids, None)
- .await;
- assert!(result.is_ok());
-
- // Verify the batch was created with zero threads
- let batch = get_insights_backfill_batch_by_id(&pool, batch_id)
- .await
- .unwrap();
- assert!(batch.is_some());
-
- let batch = batch.unwrap();
- assert_eq!(batch.total_threads, 0);
- assert!(batch.thread_ids.is_some());
- assert!(batch.thread_ids.unwrap().is_empty());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_create_insights_backfill_batch_duplicate_id_fails(pool: sqlx::PgPool) {
- let batch_id = "test-batch-1"; // This ID already exists in fixture
- let job_id = "test-job-1";
- let thread_ids = vec!["thread20".to_string()];
-
- let result =
- create_insights_backfill_batch_with_id(&pool, batch_id, job_id, &thread_ids, None)
- .await;
- assert!(result.is_err());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_create_insights_backfill_batch_invalid_job_id_fails(pool: sqlx::PgPool) {
- let batch_id = "invalid-job-batch";
- let job_id = "non-existent-job";
- let thread_ids = vec!["thread30".to_string()];
-
- let result =
- create_insights_backfill_batch_with_id(&pool, batch_id, job_id, &thread_ids, None)
- .await;
- assert!(result.is_err()); // Should fail due to foreign key constraint
- }
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insights_backfill/batch/mod.rs b/rust/cloud-storage/macro_db_client/src/insights_backfill/batch/mod.rs
deleted file mode 100644
index 39f1088731..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insights_backfill/batch/mod.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-pub mod get;
-pub mod insert;
-pub mod update;
diff --git a/rust/cloud-storage/macro_db_client/src/insights_backfill/batch/update.rs b/rust/cloud-storage/macro_db_client/src/insights_backfill/batch/update.rs
deleted file mode 100644
index 118245fdec..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insights_backfill/batch/update.rs
+++ /dev/null
@@ -1,223 +0,0 @@
-use anyhow::Result;
-use chrono::{DateTime, Utc};
-use model::insight_context::insights_backfill::InsightsBackfillBatchStatus;
-use sqlx::PgPool;
-
-pub async fn update_insights_backfill_batch_status(
- pool: &PgPool,
- batch_id: &str,
- status: InsightsBackfillBatchStatus,
- error_message: Option<&str>,
- sqs_message_id: Option<&str>,
-) -> Result<()> {
- let now = Utc::now();
-
- let completed_at = match status {
- InsightsBackfillBatchStatus::Complete | InsightsBackfillBatchStatus::Failed => Some(now),
- _ => None,
- };
-
- let started_at = match status {
- InsightsBackfillBatchStatus::InProgress => Some(now),
- _ => None,
- };
-
- sqlx::query!(
- r#"
- UPDATE "EmailInsightsBackfillBatch"
- SET
- status = $2::"insights_backfill_batch_status",
- "errorMessage" = $3,
- "sqsMessageId" = COALESCE("sqsMessageId", $4),
- "startedAt" = COALESCE("startedAt", $5),
- "completedAt" = $6,
- "updatedAt" = $7
- WHERE id = $1
- "#,
- batch_id,
- status as _,
- error_message,
- sqs_message_id,
- started_at as Option<DateTime<Utc>>,
- completed_at as Option<DateTime<Utc>>,
- now as DateTime<Utc>
- )
- .execute(pool)
- .await?;
-
- Ok(())
-}
-
-/// Update insights generated count and insight IDs for batch
-pub async fn update_insights_backfill_batch_results(
- pool: &PgPool,
- batch_id: &str,
- insights_generated_count: i32,
- insight_ids: Vec<String>,
-) -> Result<()> {
- let now = Utc::now();
-
- sqlx::query!(
- r#"
- UPDATE "EmailInsightsBackfillBatch"
- SET
- "insightsGeneratedCount" = $2,
- "insightIds" = $3,
- "updatedAt" = $4
- WHERE id = $1
- "#,
- batch_id,
- insights_generated_count,
- &insight_ids,
- now as DateTime<Utc>
- )
- .execute(pool)
- .await?;
-
- Ok(())
-}
-
-#[cfg(test)]
-mod insight_backfill_tests {
- use super::*;
- use crate::insights_backfill::batch::get::get_insights_backfill_batch_by_id;
- use model::insight_context::insights_backfill::InsightsBackfillBatchStatus;
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_update_insights_backfill_batch_status_to_in_progress(pool: sqlx::PgPool) {
- let batch_id = "test-batch-queued";
-
- // Verify initial state
- let batch = get_insights_backfill_batch_by_id(&pool, batch_id)
- .await
- .unwrap()
- .unwrap();
- assert_eq!(batch.status, InsightsBackfillBatchStatus::Queued);
- assert!(batch.started_at.is_none());
-
- // Update to InProgress
- let result = update_insights_backfill_batch_status(
- &pool,
- batch_id,
- InsightsBackfillBatchStatus::InProgress,
- None,
- None,
- )
- .await;
- assert!(result.is_ok());
-
- // Verify the update
- let batch = get_insights_backfill_batch_by_id(&pool, batch_id)
- .await
- .unwrap()
- .unwrap();
- assert_eq!(batch.status, InsightsBackfillBatchStatus::InProgress);
- assert!(batch.started_at.is_some());
- assert!(batch.completed_at.is_none());
- assert!(batch.error_message.is_none());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_update_insights_backfill_batch_status_to_complete(pool: sqlx::PgPool) {
- let batch_id = "test-batch-2";
-
- // Verify initial state (InProgress)
- let batch = get_insights_backfill_batch_by_id(&pool, batch_id)
- .await
- .unwrap()
- .unwrap();
- assert_eq!(batch.status, InsightsBackfillBatchStatus::InProgress);
- assert!(batch.completed_at.is_none());
-
- // Update to Complete
- let result = update_insights_backfill_batch_status(
- &pool,
- batch_id,
- InsightsBackfillBatchStatus::Complete,
- None,
- None,
- )
- .await;
- assert!(result.is_ok());
-
- // Verify the update
- let batch = get_insights_backfill_batch_by_id(&pool, batch_id)
- .await
- .unwrap()
- .unwrap();
- assert_eq!(batch.status, InsightsBackfillBatchStatus::Complete);
- assert!(batch.completed_at.is_some());
- assert!(batch.error_message.is_none());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_update_insights_backfill_batch_status_to_failed_with_error(pool: sqlx::PgPool) {
- let batch_id = "test-batch-2";
- let error_msg = "Test processing error";
-
- // Update to Failed with error message
- let result = update_insights_backfill_batch_status(
- &pool,
- batch_id,
- InsightsBackfillBatchStatus::Failed,
- Some(error_msg),
- None,
- )
- .await;
- assert!(result.is_ok());
-
- // Verify the update
- let batch = get_insights_backfill_batch_by_id(&pool, batch_id)
- .await
- .unwrap()
- .unwrap();
- assert_eq!(batch.status, InsightsBackfillBatchStatus::Failed);
- assert!(batch.completed_at.is_some());
- assert!(batch.error_message.is_some());
- assert_eq!(batch.error_message.unwrap(), error_msg);
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_update_insights_backfill_batch_results(pool: sqlx::PgPool) {
- let batch_id = "test-batch-2";
- let new_count = 15;
- let insight_ids = vec!["insight-1".to_string(), "insight-2".to_string()];
-
- // Verify initial count
- let batch = get_insights_backfill_batch_by_id(&pool, batch_id)
- .await
- .unwrap()
- .unwrap();
- let initial_count = batch.insights_generated_count;
- assert_ne!(initial_count, new_count);
-
- // Update insights count and IDs
- let result =
- update_insights_backfill_batch_results(&pool, batch_id, new_count, insight_ids.clone())
- .await;
- assert!(result.is_ok());
-
- // Verify the update
- let batch = get_insights_backfill_batch_by_id(&pool, batch_id)
- .await
- .unwrap()
- .unwrap();
- assert_eq!(batch.insights_generated_count, new_count);
- assert_eq!(batch.insight_ids, Some(insight_ids));
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_update_insights_backfill_batch_status_nonexistent_batch(pool: sqlx::PgPool) {
- let result = update_insights_backfill_batch_status(
- &pool,
- "non-existent-batch",
- InsightsBackfillBatchStatus::Complete,
- None,
- None,
- )
- .await;
-
- // Should succeed even if no rows are affected
- assert!(result.is_ok());
- }
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insights_backfill/job/get.rs b/rust/cloud-storage/macro_db_client/src/insights_backfill/job/get.rs
deleted file mode 100644
index fb4b6334b9..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insights_backfill/job/get.rs
+++ /dev/null
@@ -1,96 +0,0 @@
-use anyhow::Result;
-use model::insight_context::insights_backfill::{
- EmailInsightsBackfillJob, InsightsBackfillJobStatus,
-};
-use sqlx::PgPool;
-
-pub async fn get_insights_backfill_job_by_id(
- pool: &PgPool,
- job_id: &str,
-) -> Result<Option<EmailInsightsBackfillJob>> {
- let job = sqlx::query_as!(
- EmailInsightsBackfillJob,
- r#"
- SELECT
- id,
- "userId" as user_id,
- "threadsProcessedCount" as threads_processed_count,
- "insightsGeneratedCount" as insights_generated_count,
- status as "status: InsightsBackfillJobStatus",
- "completedAt"::timestamptz as completed_at,
- "createdAt"::timestamptz as "created_at!",
- "updatedAt"::timestamptz as "updated_at!"
- FROM "EmailInsightsBackfillJob"
- WHERE id = $1
- "#,
- job_id
- )
- .fetch_optional(pool)
- .await?;
-
- Ok(job)
-}
-
-#[cfg(test)]
-mod insight_backfill_tests {
- use super::*;
- use model::insight_context::insights_backfill::InsightsBackfillJobStatus;
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_get_insights_backfill_job_by_id_in_progress(pool: sqlx::PgPool) {
- let result = get_insights_backfill_job_by_id(&pool, "test-job-1").await;
-
- assert!(result.is_ok());
- let job = result.unwrap();
- assert!(job.is_some());
-
- let job = job.unwrap();
- assert_eq!(job.id, "test-job-1");
- assert_eq!(job.user_id, "test-user-1");
- assert_eq!(job.threads_processed_count, 25);
- assert_eq!(job.insights_generated_count, 10);
- assert_eq!(job.status, Some(InsightsBackfillJobStatus::InProgress));
- assert!(job.completed_at.is_none());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_get_insights_backfill_job_by_id_init(pool: sqlx::PgPool) {
- let result = get_insights_backfill_job_by_id(&pool, "test-job-2").await;
-
- assert!(result.is_ok());
- let job = result.unwrap();
- assert!(job.is_some());
-
- let job = job.unwrap();
- assert_eq!(job.id, "test-job-2");
- assert_eq!(job.status, Some(InsightsBackfillJobStatus::Init));
- assert_eq!(job.threads_processed_count, 0);
- assert_eq!(job.insights_generated_count, 0);
- assert!(job.completed_at.is_none());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_get_insights_backfill_job_by_id_complete(pool: sqlx::PgPool) {
- let result = get_insights_backfill_job_by_id(&pool, "test-job-complete").await;
-
- assert!(result.is_ok());
- let job = result.unwrap();
- assert!(job.is_some());
-
- let job = job.unwrap();
- assert_eq!(job.id, "test-job-complete");
- assert_eq!(job.status, Some(InsightsBackfillJobStatus::Complete));
- assert_eq!(job.threads_processed_count, 10);
- assert_eq!(job.insights_generated_count, 5);
- assert!(job.completed_at.is_some());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_get_insights_backfill_job_by_id_not_found(pool: sqlx::PgPool) {
- let result = get_insights_backfill_job_by_id(&pool, "non-existent-job").await;
-
- assert!(result.is_ok());
- let job = result.unwrap();
- assert!(job.is_none());
- }
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insights_backfill/job/insert.rs b/rust/cloud-storage/macro_db_client/src/insights_backfill/job/insert.rs
deleted file mode 100644
index a5b3999a05..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insights_backfill/job/insert.rs
+++ /dev/null
@@ -1,96 +0,0 @@
-use anyhow::Result;
-use sqlx::PgPool;
-
-/// Create a new insights backfill job with specific job ID
-pub async fn create_insights_backfill_job_with_id(
- pool: &PgPool,
- job_id: &str,
- user_id: &str,
-) -> Result<()> {
- sqlx::query!(
- r#"
- INSERT INTO "EmailInsightsBackfillJob" (
- id, "userId", status, "createdAt", "updatedAt"
- ) VALUES (
- $1, $2, 'InProgress'::"insights_backfill_job_status", NOW(), NOW()
- )
- "#,
- job_id,
- user_id,
- )
- .execute(pool)
- .await?;
-
- Ok(())
-}
-
-#[cfg(test)]
-mod insight_backfill_tests {
- use super::*;
- use crate::insights_backfill::job::get::get_insights_backfill_job_by_id;
- use model::insight_context::insights_backfill::InsightsBackfillJobStatus;
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_create_insights_backfill_job_with_id_basic(pool: sqlx::PgPool) {
- let job_id = "new-test-job";
- let user_id = "test-user-1";
-
- let result = create_insights_backfill_job_with_id(&pool, job_id, user_id).await;
- assert!(result.is_ok());
-
- // Verify the job was created
- let job = get_insights_backfill_job_by_id(&pool, job_id)
- .await
- .unwrap();
- assert!(job.is_some());
-
- let job = job.unwrap();
- assert_eq!(job.id, job_id);
- assert_eq!(job.user_id, user_id);
- assert_eq!(job.status, Some(InsightsBackfillJobStatus::InProgress));
- assert_eq!(job.threads_processed_count, 0);
- assert_eq!(job.insights_generated_count, 0);
- assert!(job.completed_at.is_none());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_create_insights_backfill_job_with_id_minimal(pool: sqlx::PgPool) {
- let job_id = "minimal-job";
- let user_id = "test-user-1";
-
- let result = create_insights_backfill_job_with_id(&pool, job_id, user_id).await;
- if let Err(e) = &result {
- println!("Create job error: {:?}", e);
- }
- assert!(result.is_ok());
-
- // Verify the job was created
- let job = get_insights_backfill_job_by_id(&pool, job_id)
- .await
- .unwrap();
- assert!(job.is_some());
-
- let job = job.unwrap();
- assert_eq!(job.id, job_id);
- assert_eq!(job.user_id, user_id);
- assert_eq!(job.status, Some(InsightsBackfillJobStatus::InProgress));
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_create_insights_backfill_job_duplicate_id_fails(pool: sqlx::PgPool) {
- let job_id = "test-job-1"; // This ID already exists in fixture
- let user_id = "test-user-1";
-
- let result = create_insights_backfill_job_with_id(&pool, job_id, user_id).await;
- assert!(result.is_err()); // Should fail due to unique constraint
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_create_insights_backfill_job_with_non_existent_user_fails(pool: sqlx::PgPool) {
- let job_id = "non-existent-user-job";
- let user_id = "non-existent-user";
-
- let result = create_insights_backfill_job_with_id(&pool, job_id, user_id).await;
- assert!(result.is_err()); // Should fail due to foreign key constraint
- }
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insights_backfill/job/mod.rs b/rust/cloud-storage/macro_db_client/src/insights_backfill/job/mod.rs
deleted file mode 100644
index 39f1088731..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insights_backfill/job/mod.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-pub mod get;
-pub mod insert;
-pub mod update;
diff --git a/rust/cloud-storage/macro_db_client/src/insights_backfill/job/update.rs b/rust/cloud-storage/macro_db_client/src/insights_backfill/job/update.rs
deleted file mode 100644
index d3a1441168..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insights_backfill/job/update.rs
+++ /dev/null
@@ -1,285 +0,0 @@
-use anyhow::Result;
-use chrono::{DateTime, Utc};
-use model::insight_context::insights_backfill::InsightsBackfillJobStatus;
-use sqlx::PgPool;
-
-pub async fn update_insights_backfill_job_status(
- pool: &PgPool,
- job_id: &str,
- status: InsightsBackfillJobStatus,
-) -> Result<()> {
- let now = Utc::now();
-
- // Set completed_at if status is terminal
- let completed_at = match status {
- InsightsBackfillJobStatus::Complete
- | InsightsBackfillJobStatus::Failed
- | InsightsBackfillJobStatus::Cancelled => Some(now),
- _ => None,
- };
-
- sqlx::query!(
- r#"
- UPDATE "EmailInsightsBackfillJob"
- SET
- status = $2::"insights_backfill_job_status",
- "completedAt" = $3,
- "updatedAt" = $4
- WHERE id = $1
- "#,
- job_id,
- status as _,
- completed_at as Option<DateTime<Utc>>,
- now as DateTime<Utc>,
- )
- .execute(pool)
- .await?;
-
- Ok(())
-}
-
-/// Increment thread and insight counters for a job
-pub async fn increment_insights_backfill_job_results(
- pool: &PgPool,
- job_id: &str,
- threads_processed_increment: i32,
- insights_generated_increment: i32,
-) -> Result<()> {
- let now = Utc::now();
-
- sqlx::query!(
- r#"
- UPDATE "EmailInsightsBackfillJob"
- SET
- "threadsProcessedCount" = "threadsProcessedCount" + $2,
- "insightsGeneratedCount" = "insightsGeneratedCount" + $3,
- "updatedAt" = $4
- WHERE id = $1
- "#,
- job_id,
- threads_processed_increment,
- insights_generated_increment,
- now as DateTime<Utc>
- )
- .execute(pool)
- .await?;
-
- Ok(())
-}
-
-#[cfg(test)]
-mod insight_backfill_tests {
- use super::*;
- use crate::insights_backfill::job::get::get_insights_backfill_job_by_id;
- use model::insight_context::insights_backfill::InsightsBackfillJobStatus;
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_update_insights_backfill_job_status_to_complete(pool: sqlx::PgPool) {
- let job_id = "test-job-1";
-
- // Verify initial state (InProgress)
- let job = get_insights_backfill_job_by_id(&pool, job_id)
- .await
- .unwrap()
- .unwrap();
- assert_eq!(job.status, Some(InsightsBackfillJobStatus::InProgress));
- assert!(job.completed_at.is_none());
-
- // Update to Complete
- let result =
- update_insights_backfill_job_status(&pool, job_id, InsightsBackfillJobStatus::Complete)
- .await;
- if let Err(e) = &result {
- println!("Update job status error: {:?}", e);
- }
- assert!(result.is_ok());
-
- // Verify the update
- let job = get_insights_backfill_job_by_id(&pool, job_id)
- .await
- .unwrap()
- .unwrap();
- assert_eq!(job.status, Some(InsightsBackfillJobStatus::Complete));
- assert!(job.completed_at.is_some());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_update_insights_backfill_job_status_to_failed(pool: sqlx::PgPool) {
- let job_id = "test-job-2";
-
- // Update to Failed
- let result =
- update_insights_backfill_job_status(&pool, job_id, InsightsBackfillJobStatus::Failed)
- .await;
- assert!(result.is_ok());
-
- // Verify the update
- let job = get_insights_backfill_job_by_id(&pool, job_id)
- .await
- .unwrap()
- .unwrap();
- assert_eq!(job.status, Some(InsightsBackfillJobStatus::Failed));
- assert!(job.completed_at.is_some());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_update_insights_backfill_job_status_to_cancelled(pool: sqlx::PgPool) {
- let job_id = "test-job-2";
-
- // Update to Cancelled
- let result = update_insights_backfill_job_status(
- &pool,
- job_id,
- InsightsBackfillJobStatus::Cancelled,
- )
- .await;
- assert!(result.is_ok());
-
- // Verify the update
- let job = get_insights_backfill_job_by_id(&pool, job_id)
- .await
- .unwrap()
- .unwrap();
- assert_eq!(job.status, Some(InsightsBackfillJobStatus::Cancelled));
- assert!(job.completed_at.is_some());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_update_insights_backfill_job_status_to_in_progress(pool: sqlx::PgPool) {
- let job_id = "test-job-2";
-
- // Verify initial state (Init)
- let job = get_insights_backfill_job_by_id(&pool, job_id)
- .await
- .unwrap()
- .unwrap();
- assert_eq!(job.status, Some(InsightsBackfillJobStatus::Init));
-
- // Update to InProgress (non-terminal status)
- let result = update_insights_backfill_job_status(
- &pool,
- job_id,
- InsightsBackfillJobStatus::InProgress,
- )
- .await;
- assert!(result.is_ok());
-
- // Verify the update (should not set completed_at for non-terminal status)
- let job = get_insights_backfill_job_by_id(&pool, job_id)
- .await
- .unwrap()
- .unwrap();
- assert_eq!(job.status, Some(InsightsBackfillJobStatus::InProgress));
- assert!(job.completed_at.is_none());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_increment_insights_backfill_job_results(pool: sqlx::PgPool) {
- let job_id = "test-job-1";
- let threads_increment = 5;
- let insights_increment = 8;
-
- // Get initial counts
- let initial_job = get_insights_backfill_job_by_id(&pool, job_id)
- .await
- .unwrap()
- .unwrap();
- let initial_threads = initial_job.threads_processed_count;
- let initial_insights = initial_job.insights_generated_count;
-
- // Increment the counters
- let result = increment_insights_backfill_job_results(
- &pool,
- job_id,
- threads_increment,
- insights_increment,
- )
- .await;
- assert!(result.is_ok());
-
- // Verify the increment
- let job = get_insights_backfill_job_by_id(&pool, job_id)
- .await
- .unwrap()
- .unwrap();
- assert_eq!(
- job.threads_processed_count,
- initial_threads + threads_increment
- );
- assert_eq!(
- job.insights_generated_count,
- initial_insights + insights_increment
- );
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_increment_insights_backfill_job_results_zero_increment(pool: sqlx::PgPool) {
- let job_id = "test-job-1";
-
- // Get initial counts
- let initial_job = get_insights_backfill_job_by_id(&pool, job_id)
- .await
- .unwrap()
- .unwrap();
- let initial_threads = initial_job.threads_processed_count;
- let initial_insights = initial_job.insights_generated_count;
-
- // Increment with zero (should not change values)
- let result = increment_insights_backfill_job_results(&pool, job_id, 0, 0).await;
- assert!(result.is_ok());
-
- // Verify no change
- let job = get_insights_backfill_job_by_id(&pool, job_id)
- .await
- .unwrap()
- .unwrap();
- assert_eq!(job.threads_processed_count, initial_threads);
- assert_eq!(job.insights_generated_count, initial_insights);
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_increment_insights_backfill_job_results_negative_increment(pool: sqlx::PgPool) {
- let job_id = "test-job-1";
-
- // Get initial counts
- let initial_job = get_insights_backfill_job_by_id(&pool, job_id)
- .await
- .unwrap()
- .unwrap();
- let initial_threads = initial_job.threads_processed_count;
- let initial_insights = initial_job.insights_generated_count;
-
- // Increment with negative values (should decrease)
- let result = increment_insights_backfill_job_results(&pool, job_id, -2, -1).await;
- assert!(result.is_ok());
-
- // Verify the decrement
- let job = get_insights_backfill_job_by_id(&pool, job_id)
- .await
- .unwrap()
- .unwrap();
- assert_eq!(job.threads_processed_count, initial_threads - 2);
- assert_eq!(job.insights_generated_count, initial_insights - 1);
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_update_insights_backfill_job_status_nonexistent_job(pool: sqlx::PgPool) {
- let result = update_insights_backfill_job_status(
- &pool,
- "non-existent-job",
- InsightsBackfillJobStatus::Complete,
- )
- .await;
-
- // Should succeed even if no rows are affected
- assert!(result.is_ok());
- }
-
- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("insights_backfill")))]
- async fn test_increment_insights_backfill_job_results_nonexistent_job(pool: sqlx::PgPool) {
- let result = increment_insights_backfill_job_results(&pool, "non-existent-job", 5, 3).await;
-
- // Should succeed even if no rows are affected
- assert!(result.is_ok());
- }
-}
diff --git a/rust/cloud-storage/macro_db_client/src/insights_backfill/mod.rs b/rust/cloud-storage/macro_db_client/src/insights_backfill/mod.rs
deleted file mode 100644
index a1991484c5..0000000000
--- a/rust/cloud-storage/macro_db_client/src/insights_backfill/mod.rs
+++ /dev/null
@@ -1,2 +0,0 @@
-pub mod batch;
-pub mod job;
diff --git a/rust/cloud-storage/macro_db_client/src/lib.rs b/rust/cloud-storage/macro_db_client/src/lib.rs
index 31c97d7995..4e3e95179b 100644
--- a/rust/cloud-storage/macro_db_client/src/lib.rs
+++ b/rust/cloud-storage/macro_db_client/src/lib.rs
@@ -4,6 +4,7 @@ pub mod activity;
pub mod annotations;
pub mod blocked_email;
pub mod chat;
+pub mod chat_history;
pub mod convert;
pub mod dcs;
pub mod document;
@@ -15,8 +16,6 @@ pub mod experiment_log;
pub mod history;
pub mod in_progress_email_link;
pub mod in_progress_user_link;
-pub mod insight;
-pub mod insights_backfill;
pub mod instructions;
pub mod item_access;
pub mod items;
diff --git a/rust/cloud-storage/model/src/chat/mod.rs b/rust/cloud-storage/model/src/chat/mod.rs
index 7cf232663b..df27270654 100644
--- a/rust/cloud-storage/model/src/chat/mod.rs
+++ b/rust/cloud-storage/model/src/chat/mod.rs
@@ -5,14 +5,12 @@ pub mod utils;
use chrono::serde::ts_seconds_option;
use macro_user_id::user_id::MacroUserIdStr;
pub use message::*;
-use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use strum::Display;
use utoipa::ToSchema;
use crate::comms::ChannelType;
use crate::document::FileType;
-use crate::insight_context::document::DocumentSummary;
#[derive(sqlx::FromRow, Serialize, Deserialize, Eq, PartialEq, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
@@ -158,42 +156,28 @@ pub struct NewMessageAttachment {
pub attachment_id: String,
}
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
+#[derive(Serialize, Deserialize, Debug, ToSchema, Eq, PartialEq, Clone)]
+pub struct NewAttachment {
+ pub attachment_type: AttachmentType,
+ pub attachment_id: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, schemars::JsonSchema)]
pub struct ChatHistory {
pub conversation: Vec<ConversationRecord>,
}
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, schemars::JsonSchema)]
pub struct ConversationRecord {
pub chat_id: String,
pub title: String,
- pub messages: Vec<MessageWithAttachmentSummary>,
+ pub messages: Vec<MessageWithAttachments>,
}
-#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, ToSchema)]
-pub struct MessageWithAttachmentSummary {
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, schemars::JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct MessageWithAttachments {
pub content: String,
pub date: chrono::DateTime<chrono::Utc>,
- pub attachment_summaries: Vec<Summary>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, ToSchema)]
-pub enum Summary {
- Summary(DocumentSummary),
- NoSummary { document_id: String },
-}
-
-impl Summary {
- pub fn document_id(&self) -> &str {
- match self {
- Self::NoSummary { document_id } => document_id.as_str(),
- Self::Summary(summary) => summary.document_id.as_str(),
- }
- }
-}
-
-#[derive(Serialize, Deserialize, Debug, ToSchema, Eq, PartialEq, Clone)]
-pub struct NewAttachment {
- pub attachment_type: AttachmentType,
- pub attachment_id: String,
+ pub attachment_ids: Vec<String>,
}
diff --git a/rust/cloud-storage/model/src/insight_context/chat.rs b/rust/cloud-storage/model/src/insight_context/chat.rs
deleted file mode 100644
index 3a85a409bf..0000000000
--- a/rust/cloud-storage/model/src/insight_context/chat.rs
+++ /dev/null
@@ -1,306 +0,0 @@
-use ai_format::insight_context_log::InsightContextLog;
-use ai_format::util::{Indent, Truncate, format_date};
-use chrono::{DateTime, Utc};
-
-#[derive(Debug, Clone)]
-pub struct ChatContext(pub Vec<Conversation>);
-
-#[derive(Debug, Clone)]
-pub struct Conversation {
- pub conversation_title: String,
- pub messages: Vec<UserMessage>,
-}
-
-#[derive(Debug, Clone)]
-pub struct UserMessage {
- pub content: String,
- pub date: DateTime<Utc>,
- pub attachment_insights: Vec<AttachmentInsight>,
-}
-
-#[derive(Debug, Clone)]
-pub enum AttachmentInsight {
- Document {
- title: String,
- file_type: String,
- summary: String,
- },
-}
-
-const INDENT_LEVEL: usize = 2;
-impl From<ChatContext> for InsightContextLog<String> {
- fn from(value: ChatContext) -> Self {
- let content = value
- .0
- .into_iter()
- .map(Into::into)
- .collect::<Vec<InsightContextLog<_>>>()
- .into_iter()
- .map(|log| Indent(log, INDENT_LEVEL).to_string())
- .collect::<Vec<_>>()
- .join("\n");
- InsightContextLog {
- content,
- metadata: vec![],
- name: "ChatBot Conversations".to_string(),
- }
- }
-}
-
-impl From<Conversation> for InsightContextLog<String> {
- fn from(value: Conversation) -> Self {
- let content = value
- .messages
- .into_iter()
- .map(Into::into)
- .collect::<Vec<InsightContextLog<_>>>()
- .into_iter()
- .map(|log| Indent(log, INDENT_LEVEL).to_string())
- .collect::<Vec<_>>()
- .join("\n");
-
- InsightContextLog {
- content,
- metadata: vec![("conversation_title".to_string(), value.conversation_title)],
- name: "ChatBot Conversation".to_string(),
- }
- }
-}
-
-impl From<UserMessage> for InsightContextLog<String> {
- fn from(value: UserMessage) -> Self {
- let attachments = value
- .attachment_insights
- .into_iter()
- .map(|attachment| attachment.into())
- .collect::<Vec<InsightContextLog<_>>>()
- .into_iter()
- .map(|log| log.to_string())
- .collect::<Vec<_>>()
- .join("");
-
- let content = format!(
- "{}\n{}",
- Truncate(value.content, 5000),
- Indent(attachments, INDENT_LEVEL)
- );
-
- InsightContextLog {
- name: "User Message".to_string(),
- metadata: vec![("date".to_string(), format_date(value.date))],
- content,
- }
- }
-}
-
-impl From<AttachmentInsight> for InsightContextLog<Truncate<String>> {
- fn from(value: AttachmentInsight) -> Self {
- match value {
- AttachmentInsight::Document {
- title,
- file_type,
- summary,
- ..
- } => InsightContextLog {
- name: "Document Attachment".to_string(),
- metadata: vec![
- ("title".to_string(), title),
- ("file_type".to_string(), file_type),
- ],
- content: Truncate(summary, 400),
- },
- }
- }
-}
-
-#[cfg(test)]
-mod test {
- use crate::insight_context::chat::*;
- use chrono::{DateTime, TimeZone, Utc};
-
- fn now() -> DateTime<Utc> {
- Utc.ymd(2025, 5, 9).and_hms(10, 48, 30)
- }
-
- #[test]
- fn test_format_attachment() {
- let attachment = AttachmentInsight::Document {
- file_type: "md".to_string(),
- summary: "a file".to_string(),
- title: "stuff todo".to_string(),
- };
- let log = InsightContextLog::from(attachment).to_string();
- assert_eq!(
- r#"[Document Attachment]
-title: stuff todo, file_type: md
-a file
-[END Document Attachment]
-"#
- .to_string(),
- log
- );
- }
-
- #[test]
- fn test_format_user_message() {
- let attachment = AttachmentInsight::Document {
- file_type: "md".to_string(),
- summary: "a file".to_string(),
- title: "stuff todo".to_string(),
- };
- let user_message = UserMessage {
- attachment_insights: vec![attachment.clone(), attachment],
- content: "compare these documents".to_string(),
- date: now(),
- };
- let log = InsightContextLog::from(user_message);
- assert_eq!(
- r#"[User Message]
-date: 2025-05-09
-compare these documents
- [Document Attachment]
- title: stuff todo, file_type: md
- a file
- [END Document Attachment]
- [Document Attachment]
- title: stuff todo, file_type: md
- a file
- [END Document Attachment]
-[END User Message]
-"#
- .to_string(),
- log.to_string()
- )
- }
- #[test]
- fn test_format_conversation() {
- let attachment = AttachmentInsight::Document {
- file_type: "md".to_string(),
- summary: "a file".to_string(),
- title: "stuff todo".to_string(),
- };
- let user_message = UserMessage {
- attachment_insights: vec![attachment.clone(), attachment],
- content: "compare these documents".to_string(),
- date: now(),
- };
- let conversation = Conversation {
- conversation_title: "text convo".to_string(),
- messages: vec![user_message.clone(), user_message],
- };
- let log = InsightContextLog::from(conversation);
- assert_eq!(
- r#"[ChatBot Conversation]
-conversation_title: text convo
- [User Message]
- date: 2025-05-09
- compare these documents
- [Document Attachment]
- title: stuff todo, file_type: md
- a file
- [END Document Attachment]
- [Document Attachment]
- title: stuff todo, file_type: md
- a file
- [END Document Attachment]
- [END User Message]
- [User Message]
- date: 2025-05-09
- compare these documents
- [Document Attachment]
- title: stuff todo, file_type: md
- a file
- [END Document Attachment]
- [Document Attachment]
- title: stuff todo, file_type: md
- a file
- [END Document Attachment]
- [END User Message]
-[END ChatBot Conversation]
-"#
- .to_string(),
- log.to_string()
- );
- }
-
- #[test]
- fn test_format_context() {
- let attachment = AttachmentInsight::Document {
- file_type: "md".to_string(),
- summary: "a file".to_string(),
- title: "stuff todo".to_string(),
- };
- let user_message = UserMessage {
- attachment_insights: vec![attachment.clone(), attachment],
- content: "compare these documents".to_string(),
- date: now(),
- };
- let conversation = Conversation {
- conversation_title: "text convo".to_string(),
- messages: vec![user_message.clone(), user_message],
- };
- let context = ChatContext(vec![conversation.clone(), conversation]);
- let log = InsightContextLog::from(context);
- assert_eq!(
- r#"[ChatBot Conversations]
- [ChatBot Conversation]
- conversation_title: text convo
- [User Message]
- date: 2025-05-09
- compare these documents
- [Document Attachment]
- title: stuff todo, file_type: md
- a file
- [END Document Attachment]
- [Document Attachment]
- title: stuff todo, file_type: md
- a file
- [END Document Attachment]
- [END User Message]
- [User Message]
- date: 2025-05-09
- compare these documents
- [Document Attachment]
- title: stuff todo, file_type: md
- a file
- [END Document Attachment]
- [Document Attachment]
- title: stuff todo, file_type: md
- a file
- [END Document Attachment]
- [END User Message]
- [END ChatBot Conversation]
- [ChatBot Conversation]
- conversation_title: text convo
- [User Message]
- date: 2025-05-09
- compare these documents
- [Document Attachment]
- title: stuff todo, file_type: md
- a file
- [END Document Attachment]
- [Document Attachment]
- title: stuff todo, file_type: md
- a file
- [END Document Attachment]
- [END User Message]
- [User Message]
- date: 2025-05-09
- compare these documents
- [Document Attachment]
- title: stuff todo, file_type: md
- a file
- [END Document Attachment]
- [Document Attachment]
- title: stuff todo, file_type: md
- a file
- [END Document Attachment]
- [END User Message]
- [END ChatBot Conversation]
-[END ChatBot Conversations]
-"#
- .to_string(),
- log.to_string()
- );
- }
-}
diff --git a/rust/cloud-storage/model/src/insight_context/document.rs b/rust/cloud-storage/model/src/insight_context/document.rs
deleted file mode 100644
index 7895ae062d..0000000000
--- a/rust/cloud-storage/model/src/insight_context/document.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-use chrono::{DateTime, Utc};
-use schemars::JsonSchema;
-use serde::{Deserialize, Serialize};
-use utoipa::ToSchema;
-
-#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, ToSchema)]
-pub struct DocumentSummary {
- pub document_id: String,
- pub summary: String,
- pub version_id: String,
- pub created_at: Option<DateTime<Utc>>,
- pub id: Option<String>,
-}
diff --git a/rust/cloud-storage/model/src/insight_context/email_insights.rs b/rust/cloud-storage/model/src/insight_context/email_insights.rs
deleted file mode 100644
index e6e2a0f63e..0000000000
--- a/rust/cloud-storage/model/src/insight_context/email_insights.rs
+++ /dev/null
@@ -1,69 +0,0 @@
-use serde::{Deserialize, Serialize};
-use uuid::Uuid;
-
-pub static EMAIL_INSIGHT_PROVIDER_SOURCE_NAME: &str = "email";
-
-/// Default batch size for email insight backfill operations
-pub const EMAIL_INSIGHT_BATCH_SIZE: i64 = 50;
-
-#[derive(Serialize, Deserialize, Debug, Clone)]
-#[serde(tag = "type", content = "payload")]
-pub enum EmailInfo {
- Backfill(BackfillBatchPayload),
- NewMessages(NewMessagesPayload),
- LinkDeleted(LinkDeletedPayload),
-}
-
-#[derive(Serialize, Deserialize, Debug, Clone)]
-// NOTE: batches are grouped by user id
-pub struct BackfillBatchPayload {
- // we will need to batch by user id
- pub thread_ids: Vec<String>,
- // Size of each batch (threads)
- pub batch_size: i64,
- // True if this is the last batch for the user
- pub is_complete: bool,
- // List of user email addresses
- pub user_emails: Vec<String>,
- // Insights backfill job ID (for tracking)
- pub job_id: String,
- // Insights backfill batch ID (for tracking)
- pub batch_id: String,
-}
-
-#[derive(Serialize, Deserialize, Debug, Clone, Default)]
-pub struct NewMessagesPayload {
- pub messages: Vec<NewMessagePayload>,
- // uuid v4 for the batch deduplication id
- #[serde(skip)]
- pub batch_id: String,
-}
-
-#[derive(Serialize, Deserialize, Debug, Clone)]
-pub struct NewMessagePayload {
- pub thread_id: Uuid,
- pub message_id: Uuid,
- pub user_email: String,
-}
-
-#[derive(Serialize, Deserialize, Debug, Clone)]
-pub struct LinkDeletedPayload {
- pub link_id: String,
- pub email_address: String,
-}
-
-#[derive(Serialize, Deserialize, Debug, Clone)]
-pub struct GenerateEmailInsightContext {
- pub macro_user_id: String,
- #[serde(flatten)]
- pub info: EmailInfo,
-}
-
-#[derive(Serialize, Deserialize, Debug, Clone)]
-pub struct BackfillEmailInsightsFilter {
- /// The user ids to backfill
- /// If not provided, all users will be backfilled
- pub user_ids: Option<Vec<String>>,
- /// Optional limit on the total number of threads to get for a user
- pub user_thread_limit: Option<i64>,
-}
diff --git a/rust/cloud-storage/model/src/insight_context/insights_backfill.rs b/rust/cloud-storage/model/src/insight_context/insights_backfill.rs
deleted file mode 100644
index 336a5aff30..0000000000
--- a/rust/cloud-storage/model/src/insight_context/insights_backfill.rs
+++ /dev/null
@@ -1,226 +0,0 @@
-use chrono::{DateTime, Utc};
-use serde::{Deserialize, Serialize};
-use sqlx::FromRow;
-use strum::{AsRefStr, Display, EnumString};
-use utoipa::ToSchema;
-
-#[derive(
- Debug,
- Clone,
- Copy,
- PartialEq,
- Eq,
- Serialize,
- Deserialize,
- Display,
- AsRefStr,
- EnumString,
- ToSchema,
- sqlx::Type,
-)]
-#[serde(rename_all = "snake_case")]
-#[strum(serialize_all = "PascalCase")]
-#[sqlx(type_name = "insights_backfill_job_status", rename_all = "PascalCase")]
-pub enum InsightsBackfillJobStatus {
- Init,
- InProgress,
- Complete,
- Cancelled,
- Failed,
-}
-
-#[derive(
- Debug,
- Clone,
- Copy,
- PartialEq,
- Eq,
- Serialize,
- Deserialize,
- Display,
- AsRefStr,
- EnumString,
- ToSchema,
- sqlx::Type,
-)]
-#[serde(rename_all = "snake_case")]
-#[strum(serialize_all = "PascalCase")]
-#[sqlx(
- type_name = "insights_backfill_batch_status",
- rename_all = "PascalCase"
-)]
-pub enum InsightsBackfillBatchStatus {
- Queued,
- InProgress,
- Complete,
- Failed,
-}
-
-/// Main insights backfill job record
-#[derive(Debug, Clone, Serialize, Deserialize, FromRow, ToSchema)]
-pub struct EmailInsightsBackfillJob {
- pub id: String,
- pub user_id: String,
-
- // Progress counters
- pub threads_processed_count: i32,
- pub insights_generated_count: i32,
-
- // Status tracking
- pub status: Option<InsightsBackfillJobStatus>,
-
- // Metadata
- pub completed_at: Option<DateTime<Utc>>,
- pub created_at: DateTime<Utc>,
- pub updated_at: DateTime<Utc>,
-}
-
-/// Individual batch tracking record
-#[derive(Debug, Clone, Serialize, Deserialize, FromRow, ToSchema)]
-pub struct EmailInsightsBackfillBatch {
- pub id: String,
- pub insights_backfill_job_id: String,
-
- // SQS tracking
- pub sqs_message_id: Option<String>,
-
- // Thread tracking
- pub thread_ids: Option<Vec<String>>,
- pub total_threads: i32,
-
- // Processing status
- pub status: InsightsBackfillBatchStatus,
- pub insights_generated_count: i32,
- pub insight_ids: Option<Vec<String>>,
-
- // Error handling
- pub error_message: Option<String>,
-
- // Timing
- pub queued_at: Option<DateTime<Utc>>,
- pub started_at: Option<DateTime<Utc>>,
- pub completed_at: Option<DateTime<Utc>>,
- pub created_at: DateTime<Utc>,
- pub updated_at: DateTime<Utc>,
-}
-
-/// Parameters for creating a new insights backfill job
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
-pub struct NewInsightsBackfillJob {
- pub user_id: String,
- pub user_thread_limit: Option<i32>,
- pub status: InsightsBackfillJobStatus,
- pub total_threads: i32,
- pub processed_threads: i32,
- pub total_batches: i32,
- pub processed_batches: i32,
- pub error_message: Option<String>,
-}
-
-/// Request to create a new insights backfill job
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
-pub struct CreateInsightsBackfillJobRequest {
- pub user_ids: Option<Vec<String>>,
- pub user_thread_limit: Option<i32>,
-}
-
-/// Response when creating a new insights backfill job
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
-pub struct CreateInsightsBackfillJobResponse {
- pub job_id: String,
- pub status: InsightsBackfillJobStatus,
- pub total_users: i32,
- pub created_at: DateTime<Utc>,
-}
-
-/// Progress summary for an insights backfill job
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
-pub struct InsightsBackfillJobProgress {
- pub job_id: String,
- pub user_id: String,
- pub status: InsightsBackfillJobStatus,
-
- // Progress percentages
- pub batches_completion_percentage: f32,
- pub threads_completion_percentage: f32,
-
- // Counts
- pub total_threads: i32,
- pub batches_created: i32,
- pub batches_completed: i32,
- pub threads_processed: i32,
- pub insights_generated: i32,
-
- // Timing
- pub started_at: Option<DateTime<Utc>>,
- pub completed_at: Option<DateTime<Utc>>,
- pub estimated_completion_at: Option<DateTime<Utc>>,
- pub created_at: DateTime<Utc>,
- pub updated_at: DateTime<Utc>,
-}
-
-impl EmailInsightsBackfillJob {
- /// Check if the job is complete
- pub fn is_complete(&self) -> bool {
- self.status == Some(InsightsBackfillJobStatus::Complete)
- }
-
- /// Check if the job is in a terminal state
- pub fn is_terminal(&self) -> bool {
- matches!(
- self.status,
- Some(
- InsightsBackfillJobStatus::Complete
- | InsightsBackfillJobStatus::Failed
- | InsightsBackfillJobStatus::Cancelled
- )
- )
- }
-
- /// Convert to progress summary
- pub fn to_progress(&self) -> InsightsBackfillJobProgress {
- InsightsBackfillJobProgress {
- job_id: self.id.clone(),
- user_id: self.user_id.clone(),
- status: self.status.unwrap_or(InsightsBackfillJobStatus::Init),
- batches_completion_percentage: 0.0,
- threads_completion_percentage: 0.0,
- total_threads: 0,
- batches_created: 0,
- batches_completed: 0,
- threads_processed: self.threads_processed_count,
- insights_generated: self.insights_generated_count,
- started_at: None,
- completed_at: self.completed_at,
- estimated_completion_at: self.estimate_completion_time(),
- created_at: self.created_at,
- updated_at: self.updated_at,
- }
- }
-
- /// Estimate completion time based on current progress
- fn estimate_completion_time(&self) -> Option<DateTime<Utc>> {
- if self.is_terminal() {
- return self.completed_at;
- }
- None
- }
-}
-
-/// Parameters for creating a new insights backfill batch
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
-pub struct NewInsightsBackfillBatch {
- pub job_id: String,
- pub thread_count: i32,
- pub sqs_message_id: Option<String>,
- pub status: InsightsBackfillBatchStatus,
-}
-
-/// Thread processing result
-#[derive(Debug, Clone)]
-pub struct ThreadProcessingResult {
- pub thread_id: String,
- pub insights_generated_count: i32,
- pub processing_time_ms: Option<i32>,
- pub error_message: Option<String>,
-}
diff --git a/rust/cloud-storage/model/src/insight_context/mod.rs b/rust/cloud-storage/model/src/insight_context/mod.rs
deleted file mode 100644
index 8e275d0b6d..0000000000
--- a/rust/cloud-storage/model/src/insight_context/mod.rs
+++ /dev/null
@@ -1,249 +0,0 @@
-pub mod chat;
-pub mod document;
-pub mod email_insights;
-pub mod insights_backfill;
-
-use ai_format::util::format_date;
-use chrono::serde::{ts_seconds, ts_seconds_option};
-use chrono::{DateTime, Utc};
-use email_insights::{EmailInfo, GenerateEmailInsightContext};
-use serde::{Deserialize, Serialize};
-use sqlx::Type;
-use sqlx::{FromRow, types::Json};
-use std::fmt::Display;
-use strum::{Display, EnumString};
-use utoipa::ToSchema;
-use uuid::Uuid;
-
-const MAX_MESSAGE_DEDUPLICATION_ID_LEN: usize = 128;
-const MAX_MESSAGE_GROUP_ID_LEN: usize = 128;
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(tag = "type")]
-pub enum InsightContextQueueMessage {
- #[serde(rename = "context")]
- Context(ProvidedContext),
- #[serde(rename = "test")]
- Test { content: String },
- #[serde(rename = "email")]
- Email {
- context: GenerateEmailInsightContext,
- },
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
-pub struct ProvidedContext {
- /// the context provider source name: "chat" | "channels" | ...
- pub provider_source: String,
- /// user id context was created for
- pub user_id: String,
- /// database key of item
- pub resource_id: String,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Eq, PartialEq)]
-#[serde(rename_all = "camelCase")]
-pub struct UserInsightRecord {
- pub id: Option<String>,
- pub user_id: String,
- pub content: String,
- pub generated: bool,
- #[serde(with = "ts_seconds")]
- #[schema(value_type = i64, nullable=false)]
- pub created_at: DateTime<Utc>,
- #[serde(with = "ts_seconds")]
- #[schema(value_type = i64, nullable=false)]
- pub updated_at: DateTime<Utc>,
- #[serde(skip_serializing_if = "Option::is_none")]
- #[serde(with = "ts_seconds_option")]
- pub span_start: Option<DateTime<Utc>>,
- #[serde(skip_serializing_if = "Option::is_none")]
- #[serde(with = "ts_seconds_option")]
- pub span_end: Option<DateTime<Utc>>,
- pub source: String,
- pub source_location: Option<SourceLocation>,
- pub confidence: Option<i32>,
- pub insight_type: Option<InsightType>,
- pub relevance_keywords: Option<Vec<String>>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Eq, PartialEq)]
-#[serde(rename_all = "camelCase")]
-pub struct EmailSourceLocation {
- // this is a uuid
- pub thread_ids: Vec<String>,
- // this is a uuid
- pub message_ids: Vec<String>,
- // email addresses from the messages (from, to, cc, bcc)
- #[serde(skip_serializing_if = "Option::is_none")]
- pub email_addresses: Option<Vec<String>>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Eq, PartialEq)]
-#[serde(untagged)]
-#[serde(rename_all = "camelCase")]
-pub enum SourceLocation {
- Email(EmailSourceLocation),
-}
-
-#[derive(Debug, Clone, FromRow)]
-pub struct UserInsightRow {
- pub id: Option<String>,
- pub user_id: String,
- pub content: String,
- pub generated: bool,
- pub created_at: DateTime<Utc>,
- pub updated_at: DateTime<Utc>,
- pub span_start: Option<DateTime<Utc>>,
- pub span_end: Option<DateTime<Utc>>,
- pub source: String,
- pub source_location: Option<Json<SourceLocation>>,
- pub confidence: Option<i32>,
- pub insight_type: Option<InsightType>,
- pub relevance_keywords: Option<Vec<String>>,
-}
-
-impl UserInsightRecord {
- pub fn user_created(content: String, user_id: &str) -> Self {
- let now = Utc::now();
- Self {
- id: None,
- user_id: user_id.to_string(),
- content,
- generated: false,
- created_at: now,
- updated_at: now,
- confidence: None,
- source: "user_created".to_string(),
- source_location: None,
- span_end: None,
- span_start: None,
- insight_type: None,
- relevance_keywords: None,
- }
- }
-}
-
-#[derive(
- Type, EnumString, Debug, Clone, Copy, Serialize, Deserialize, ToSchema, Display, Eq, PartialEq,
-)]
-#[strum(serialize_all = "lowercase")]
-#[sqlx(rename_all = "lowercase")]
-#[serde(rename_all = "lowercase")]
-pub enum Confidence {
- Low,
- Medium,
- High,
-}
-
-#[derive(
- Type, EnumString, Debug, Clone, Copy, Serialize, Deserialize, ToSchema, Display, Eq, PartialEq,
-)]
-#[strum(serialize_all = "lowercase")]
-#[sqlx(rename_all = "lowercase")]
-#[serde(rename_all = "lowercase")]
-pub enum InsightType {
- Actionable, // Requires user action
- Informational, // Background information
- Warning, // Potential issues to watch
- Trend, // Pattern or trend analysis
-}
-
-impl Display for UserInsightRecord {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let date_string = match (self.span_start, self.span_end) {
- (Some(start), Some(end)) => {
- format!("from {} to {}, ", format_date(start), format_date(end))
- }
- (Some(start), None) => format!("starting in {}, ", format_date(start)),
- _ => String::new(),
- };
- let confidence = self
- .confidence
- .map(|c| format!("Confidence: {}, ", c))
- .unwrap_or_default();
-
- write!(
- f,
- r#"
-{}
-{confidence}{date_string}{}
-"#,
- self.content, self.source
- )
- }
-}
-
-impl From<UserInsightRow> for UserInsightRecord {
- fn from(row: UserInsightRow) -> Self {
- Self {
- id: row.id,
- user_id: row.user_id,
- content: row.content,
- generated: row.generated,
- created_at: row.created_at,
- updated_at: row.updated_at,
- span_start: row.span_start,
- span_end: row.span_end,
- source: row.source,
- confidence: row.confidence,
- source_location: row.source_location.map(|json| json.0),
- insight_type: row.insight_type,
- relevance_keywords: row.relevance_keywords,
- }
- }
-}
-
-impl InsightContextQueueMessage {
- pub fn deduplication_id(&self) -> String {
- let mut deduplication_id = match self {
- InsightContextQueueMessage::Email { context } => match &context.info {
- EmailInfo::Backfill(batch) => {
- format!("backfill:{}", batch.job_id)
- }
- EmailInfo::NewMessages(msgs) => {
- format!("newmessages:{}", msgs.batch_id)
- }
- EmailInfo::LinkDeleted(link_info) => {
- format!(
- "linkdeleted:{}:{}",
- context.macro_user_id, link_info.email_address
- )
- }
- },
- InsightContextQueueMessage::Context(context) => {
- format!(
- "context:{}:{}",
- context.provider_source, context.resource_id
- )
- }
- InsightContextQueueMessage::Test { .. } => {
- format!("test:{}", Uuid::new_v4())
- }
- };
- deduplication_id.truncate(MAX_MESSAGE_DEDUPLICATION_ID_LEN);
- deduplication_id
- }
-
- pub fn group_id(&self) -> String {
- let mut group_id = match self {
- InsightContextQueueMessage::Email { context } => match &context.info {
- EmailInfo::Backfill(batch) => {
- format!("backfill:{}", batch.job_id)
- }
- EmailInfo::NewMessages(_) => {
- format!("newmessages:{}", context.macro_user_id)
- }
- EmailInfo::LinkDeleted(_) => {
- format!("linkdeleted:{}", context.macro_user_id)
- }
- },
- InsightContextQueueMessage::Context(context) => context.provider_source.clone(),
- InsightContextQueueMessage::Test { .. } => {
- format!("testgroup:{}", Uuid::new_v4())
- }
- };
- group_id.truncate(MAX_MESSAGE_GROUP_ID_LEN);
- group_id
- }
-}
diff --git a/rust/cloud-storage/model/src/lib.rs b/rust/cloud-storage/model/src/lib.rs
index 7c9a8411c5..b390ff6e8a 100644
--- a/rust/cloud-storage/model/src/lib.rs
+++ b/rust/cloud-storage/model/src/lib.rs
@@ -12,7 +12,6 @@ pub mod document;
pub mod document_storage_service_internal;
pub mod experiment;
pub mod folder;
-pub mod insight_context;
pub mod item;
pub mod macros;
pub mod organization;
diff --git a/rust/cloud-storage/sqs_client/Cargo.toml b/rust/cloud-storage/sqs_client/Cargo.toml
index 0af06bae65..f0a95c9cbd 100644
--- a/rust/cloud-storage/sqs_client/Cargo.toml
+++ b/rust/cloud-storage/sqs_client/Cargo.toml
@@ -16,7 +16,6 @@ default = [
"document_text_extractor",
"email",
"gmail",
- "insight_context",
"organization_retention",
"search",
"sfs_uploader",
@@ -26,7 +25,6 @@ document = []
document_text_extractor = []
email = ["model", "models_email"]
gmail = ["model", "uuid"]
-insight_context = ["model"]
organization_retention = []
search = ["chrono", "model", "models_opensearch", "uuid", "futures"]
sfs_uploader = []
diff --git a/rust/cloud-storage/sqs_client/src/insight_context.rs b/rust/cloud-storage/sqs_client/src/insight_context.rs
deleted file mode 100644
index 598d77cc70..0000000000
--- a/rust/cloud-storage/sqs_client/src/insight_context.rs
+++ /dev/null
@@ -1,47 +0,0 @@
-use model::insight_context::InsightContextQueueMessage;
-
-use crate::SQS;
-
-impl SQS {
- pub fn insight_context_queue(mut self, context_queue: &str) -> Self {
- self.insight_context_queue = Some(context_queue.to_string());
- self
- }
-
- #[tracing::instrument(err, skip(self))]
- pub async fn enqueue_insight_context(
- &self,
- message: InsightContextQueueMessage,
- ) -> Result<(), anyhow::Error> {
- if let Some(insight_context_queue) = &self.insight_context_queue {
- return enqueue_insight_context(&self.inner, insight_context_queue, message).await;
- }
-
- Err(anyhow::anyhow!("insight_context_queue is not configured"))
- }
-}
-
-#[tracing::instrument(skip(sqs_client))]
-pub async fn enqueue_insight_context(
- sqs_client: &aws_sdk_sqs::Client,
- queue_url: &str,
- message: InsightContextQueueMessage,
-) -> Result<(), anyhow::Error> {
- let message_str = serde_json::to_string(&message)?;
- let group_id = message.group_id();
- let dedup_id = message.deduplication_id();
- tracing::debug!(
- "enqueue insight context for group_id {} with dedup_id {}",
- group_id,
- dedup_id
- );
- sqs_client
- .send_message()
- .queue_url(queue_url)
- .message_body(message_str)
- .message_group_id(group_id)
- .message_deduplication_id(dedup_id)
- .send()
- .await?;
- Ok(())
-}
diff --git a/rust/cloud-storage/sqs_client/src/lib.rs b/rust/cloud-storage/sqs_client/src/lib.rs
index 480f4083a0..ce72851f9f 100644
--- a/rust/cloud-storage/sqs_client/src/lib.rs
+++ b/rust/cloud-storage/sqs_client/src/lib.rs
@@ -21,9 +21,6 @@ pub mod email;
#[cfg(feature = "gmail")]
pub mod gmail;
-#[cfg(feature = "insight_context")]
-pub mod insight_context;
-
#[cfg(feature = "organization_retention")]
mod organization_retention;
@@ -72,8 +69,6 @@ pub struct SQS {
upload_extractor_queue: Option<String>,
#[cfg(feature = "convert")]
convert_queue: Option<String>,
- #[cfg(feature = "insight_context")]
- insight_context_queue: Option<String>,
#[cfg(feature = "gmail")]
gmail_inbox_sync_queue: Option<String>,
#[cfg(feature = "gmail")]
@@ -108,8 +103,6 @@ impl SQS {
upload_extractor_queue: None,
#[cfg(feature = "convert")]
convert_queue: None,
- #[cfg(feature = "insight_context")]
- insight_context_queue: None,
#[cfg(feature = "gmail")]
gmail_inbox_sync_queue: None,
#[cfg(feature = "gmail")]