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.

fix(search): repair broken OpenSearch delete path + surface deleted_at (#3074)

gbirman06f380eceb64
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
index 214151613f..89bb8236bd 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
@@ -170,6 +170,9 @@ export const SearchToolResponse = z.object({
created_at: z
.union([z.string().datetime({ offset: true }), z.null()])
.optional(),
+ deleted_at: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
highlight: z.object({
bcc: z.array(z.string()).optional(),
cc: z.array(z.string()).optional(),
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
index 2b7f7fd56c..227ad9b7b8 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
@@ -485,6 +485,10 @@ export interface ChannelSearchResult {
* This is only prsent if the search result is on the message content
*/
created_at?: string | null;
+ /**
+ * When the channel message was deleted, if it has been
+ */
+ deleted_at?: string | null;
highlight: SearchHighlight;
/**
* The channel message id
diff --git a/js/app/packages/service-clients/service-search/generated/models/channelSearchResult.ts b/js/app/packages/service-clients/service-search/generated/models/channelSearchResult.ts
index 9eff9baabb..b2e87af7fa 100644
--- a/js/app/packages/service-clients/service-search/generated/models/channelSearchResult.ts
+++ b/js/app/packages/service-clients/service-search/generated/models/channelSearchResult.ts
@@ -5,6 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
import type { ChannelSearchResultCreatedAt } from './channelSearchResultCreatedAt';
+import type { ChannelSearchResultDeletedAt } from './channelSearchResultDeletedAt';
import type { ChannelSearchResultMessageId } from './channelSearchResultMessageId';
import type { ChannelSearchResultScore } from './channelSearchResultScore';
import type { ChannelSearchResultSenderId } from './channelSearchResultSenderId';
@@ -19,6 +20,8 @@ export interface ChannelSearchResult {
/** When the channel message was created
This is only prsent if the search result is on the message content */
created_at?: ChannelSearchResultCreatedAt;
+ /** When the channel message was deleted, if it has been */
+ deleted_at?: ChannelSearchResultDeletedAt;
/** The highlights for the channel message */
highlight: SearchHighlight;
/** The channel message id
diff --git a/js/app/packages/service-clients/service-search/generated/models/channelSearchResultDeletedAt.ts b/js/app/packages/service-clients/service-search/generated/models/channelSearchResultDeletedAt.ts
new file mode 100644
index 0000000000..3929cbfe1a
--- /dev/null
+++ b/js/app/packages/service-clients/service-search/generated/models/channelSearchResultDeletedAt.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * When the channel message was deleted, if it has been
+ */
+export type ChannelSearchResultDeletedAt = string | null;
diff --git a/js/app/packages/service-clients/service-search/generated/models/index.ts b/js/app/packages/service-clients/service-search/generated/models/index.ts
index db298f93de..db3b850a94 100644
--- a/js/app/packages/service-clients/service-search/generated/models/index.ts
+++ b/js/app/packages/service-clients/service-search/generated/models/index.ts
@@ -42,6 +42,7 @@ export * from './channelSearchResponseItemWithMetadataAllOf';
export * from './channelSearchResponseItemWithMetadataAllOfMetadata';
export * from './channelSearchResult';
export * from './channelSearchResultCreatedAt';
+export * from './channelSearchResultDeletedAt';
export * from './channelSearchResultMessageId';
export * from './channelSearchResultScore';
export * from './channelSearchResultSenderId';
diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.json
index 0051b3b62c..e3c7c28a37 100644
--- a/js/app/packages/service-clients/service-search/openapi.json
+++ b/js/app/packages/service-clients/service-search/openapi.json
@@ -550,6 +550,11 @@
"format": "date-time",
"description": "When the channel message was created\nThis is only prsent if the search result is on the message content"
},
+ "deleted_at": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When the channel message was deleted, if it has been"
+ },
"highlight": {
"$ref": "#/components/schemas/SearchHighlight",
"description": "The highlights for the channel message"
diff --git a/rust/cloud-storage/.sqlx/query-26b3b2da3cc2f75ee37842ebe33e1bda1e5b15a490bd8aa3a2a3c27afa728348.json b/rust/cloud-storage/.sqlx/query-13a3a2c05506fe36d0420c3ed6eb711ece07b50c77690ce7ef2336c9390896d4.json
similarity index 83%
rename from rust/cloud-storage/.sqlx/query-26b3b2da3cc2f75ee37842ebe33e1bda1e5b15a490bd8aa3a2a3c27afa728348.json
rename to rust/cloud-storage/.sqlx/query-13a3a2c05506fe36d0420c3ed6eb711ece07b50c77690ce7ef2336c9390896d4.json
index d5b85b3456..33afb88352 100644
--- a/rust/cloud-storage/.sqlx/query-26b3b2da3cc2f75ee37842ebe33e1bda1e5b15a490bd8aa3a2a3c27afa728348.json
+++ b/rust/cloud-storage/.sqlx/query-13a3a2c05506fe36d0420c3ed6eb711ece07b50c77690ce7ef2336c9390896d4.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n c.\"id\" as \"chat_id\",\n m.id as \"message_id\",\n c.\"userId\" as \"user_id\",\n c.\"createdAt\" as \"created_at\",\n c.\"updatedAt\" as \"updated_at\"\n FROM\n \"ChatMessage\" m\n JOIN\n \"Chat\" c on c.\"id\" = m.\"chatId\"\n WHERE\n m.\"chatId\" = ANY($1) AND c.\"deletedAt\" IS NULL\n ORDER BY\n m.\"createdAt\" DESC\n LIMIT $2\n OFFSET $3\n ",
+ "query": "\n SELECT\n c.\"id\" as \"chat_id\",\n m.id as \"message_id\",\n c.\"userId\" as \"user_id\",\n c.\"createdAt\" as \"created_at\",\n c.\"updatedAt\" as \"updated_at\"\n FROM\n \"ChatMessage\" m\n JOIN\n \"Chat\" c on c.\"id\" = m.\"chatId\"\n WHERE\n m.\"chatId\" = ANY($1)\n ORDER BY\n m.\"createdAt\" DESC\n LIMIT $2\n OFFSET $3\n ",
"describe": {
"columns": [
{
@@ -44,5 +44,5 @@
false
]
},
- "hash": "26b3b2da3cc2f75ee37842ebe33e1bda1e5b15a490bd8aa3a2a3c27afa728348"
+ "hash": "13a3a2c05506fe36d0420c3ed6eb711ece07b50c77690ce7ef2336c9390896d4"
}
diff --git a/rust/cloud-storage/.sqlx/query-317f05707fdc73269f3017a3bb96d55b7327338bf5e52dfaad106b4b492cbb8e.json b/rust/cloud-storage/.sqlx/query-317f05707fdc73269f3017a3bb96d55b7327338bf5e52dfaad106b4b492cbb8e.json
deleted file mode 100644
index b17b203167..0000000000
--- a/rust/cloud-storage/.sqlx/query-317f05707fdc73269f3017a3bb96d55b7327338bf5e52dfaad106b4b492cbb8e.json
+++ /dev/null
@@ -1,98 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n un.user_id as owner_id,\n un.notification_id,\n n.event_item_id,\n n.event_item_type,\n un.sent,\n un.done,\n un.created_at::timestamptz as \"created_at!\",\n un.seen_at::timestamptz as viewed_at,\n un.created_at::timestamptz as \"updated_at!\",\n un.deleted_at::timestamptz,\n n.metadata as \"notification_metadata: serde_json::Value\",\n n.notification_event_type as notification_event_type,\n n.sender_id as sender_id\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND n.event_item_id = ANY($2)\n AND un.deleted_at IS NULL\n AND un.done = false\n AND (($4::timestamptz IS NULL)\n OR (un.created_at, un.notification_id) < ($4, $5))\n ORDER BY un.created_at DESC, un.notification_id DESC\n LIMIT $3\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "owner_id",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "notification_id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 2,
- "name": "event_item_id",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "event_item_type",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "sent",
- "type_info": "Bool"
- },
- {
- "ordinal": 5,
- "name": "done",
- "type_info": "Bool"
- },
- {
- "ordinal": 6,
- "name": "created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "viewed_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 8,
- "name": "updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 9,
- "name": "deleted_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 10,
- "name": "notification_metadata: serde_json::Value",
- "type_info": "Jsonb"
- },
- {
- "ordinal": 11,
- "name": "notification_event_type",
- "type_info": "Varchar"
- },
- {
- "ordinal": 12,
- "name": "sender_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "TextArray",
- "Int8",
- "Timestamptz",
- "Uuid"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- false,
- false,
- false,
- null,
- null,
- null,
- null,
- false,
- false,
- true
- ]
- },
- "hash": "317f05707fdc73269f3017a3bb96d55b7327338bf5e52dfaad106b4b492cbb8e"
-}
diff --git a/rust/cloud-storage/.sqlx/query-c09f00249c17f61948c81a3e7b679b3d1f9ac387ba98d351ff4e99995e3e783f.json b/rust/cloud-storage/.sqlx/query-7e30c2f23eec4e4131e6463f0b05722b1dd8b220025c72ec4c70772251b03656.json
similarity index 55%
rename from rust/cloud-storage/.sqlx/query-c09f00249c17f61948c81a3e7b679b3d1f9ac387ba98d351ff4e99995e3e783f.json
rename to rust/cloud-storage/.sqlx/query-7e30c2f23eec4e4131e6463f0b05722b1dd8b220025c72ec4c70772251b03656.json
index 31d66f5bc3..08aebb0dbc 100644
--- a/rust/cloud-storage/.sqlx/query-c09f00249c17f61948c81a3e7b679b3d1f9ac387ba98d351ff4e99995e3e783f.json
+++ b/rust/cloud-storage/.sqlx/query-7e30c2f23eec4e4131e6463f0b05722b1dd8b220025c72ec4c70772251b03656.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n m.content as \"content\",\n c.name as \"name\",\n m.role as \"role\"\n FROM\n \"ChatMessage\" m\n JOIN\n \"Chat\" c on c.\"id\" = m.\"chatId\"\n WHERE\n m.id = $1 AND m.\"chatId\" = $2 AND c.\"deletedAt\" IS NULL AND c.\"isPersistent\" = false\n ",
+ "query": "\n SELECT\n m.content as \"content\",\n c.name as \"name\",\n m.role as \"role\",\n c.\"deletedAt\"::timestamptz as \"deleted_at\"\n FROM\n \"ChatMessage\" m\n JOIN\n \"Chat\" c on c.\"id\" = m.\"chatId\"\n WHERE\n m.id = $1 AND m.\"chatId\" = $2 AND c.\"isPersistent\" = false\n ",
"describe": {
"columns": [
{
@@ -17,6 +17,11 @@
"ordinal": 2,
"name": "role",
"type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "deleted_at",
+ "type_info": "Timestamptz"
}
],
"parameters": {
@@ -28,8 +33,9 @@
"nullable": [
false,
false,
- false
+ false,
+ null
]
},
- "hash": "c09f00249c17f61948c81a3e7b679b3d1f9ac387ba98d351ff4e99995e3e783f"
+ "hash": "7e30c2f23eec4e4131e6463f0b05722b1dd8b220025c72ec4c70772251b03656"
}
diff --git a/rust/cloud-storage/.sqlx/query-929e8e21a0b181340c4d74adbb26e14ec0c63b5f7da47d260f84eb0cfb15c575.json b/rust/cloud-storage/.sqlx/query-8a64d1a5859b13c18516410d4fd512dd8b1359893d3e414b18f082fb48bfd907.json
similarity index 79%
rename from rust/cloud-storage/.sqlx/query-929e8e21a0b181340c4d74adbb26e14ec0c63b5f7da47d260f84eb0cfb15c575.json
rename to rust/cloud-storage/.sqlx/query-8a64d1a5859b13c18516410d4fd512dd8b1359893d3e414b18f082fb48bfd907.json
index 352ba12ced..3e3560d659 100644
--- a/rust/cloud-storage/.sqlx/query-929e8e21a0b181340c4d74adbb26e14ec0c63b5f7da47d260f84eb0cfb15c575.json
+++ b/rust/cloud-storage/.sqlx/query-8a64d1a5859b13c18516410d4fd512dd8b1359893d3e414b18f082fb48bfd907.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n d.id as document_id,\n d.owner as owner,\n d.\"fileType\" as \"file_type!\",\n COALESCE(db.id, di.id, dipdf.id) as \"document_version_id!\",\n d.\"createdAt\"::timestamptz as \"created_at\"\n FROM\n \"Document\" d\n LEFT JOIN document_sub_type dst ON dst.document_id = d.id\n LEFT JOIN LATERAL (\n SELECT\n b.id\n FROM\n \"DocumentBom\" b\n WHERE\n b.\"documentId\" = d.id\n ORDER BY\n b.\"createdAt\" DESC\n LIMIT 1\n ) db ON d.\"fileType\" = 'docx'\n LEFT JOIN LATERAL (\n SELECT\n i.id\n FROM\n \"DocumentInstance\" i\n WHERE\n i.\"documentId\" = d.id\n ORDER BY\n i.\"updatedAt\" ASC\n LIMIT 1\n ) dipdf ON d.\"fileType\" = 'pdf'\n LEFT JOIN LATERAL (\n SELECT\n i.id\n FROM\n \"DocumentInstance\" i\n WHERE\n i.\"documentId\" = d.id\n ORDER BY\n i.\"createdAt\" DESC\n LIMIT 1\n ) di ON d.\"fileType\" IS DISTINCT FROM 'docx' AND d.\"fileType\" IS DISTINCT FROM 'pdf'\n WHERE\n d.\"deletedAt\" IS NULL\n AND d.\"fileType\" IS NOT NULL\n AND ($3::text[] IS NULL OR d.\"fileType\" = ANY($3))\n AND ($4::text IS NULL OR dst.sub_type::text = $4)\n AND ($5::timestamptz IS NULL OR d.\"createdAt\" >= $5)\n AND ($6::timestamptz IS NULL OR d.\"createdAt\" < $6)\n ORDER BY d.\"createdAt\" ASC, d.id ASC\n LIMIT $1 OFFSET $2\n ",
+ "query": "\n SELECT\n d.id as document_id,\n d.owner as owner,\n d.\"fileType\" as \"file_type!\",\n COALESCE(db.id, di.id, dipdf.id) as \"document_version_id!\",\n d.\"createdAt\"::timestamptz as \"created_at\"\n FROM\n \"Document\" d\n LEFT JOIN document_sub_type dst ON dst.document_id = d.id\n LEFT JOIN LATERAL (\n SELECT\n b.id\n FROM\n \"DocumentBom\" b\n WHERE\n b.\"documentId\" = d.id\n ORDER BY\n b.\"createdAt\" DESC\n LIMIT 1\n ) db ON d.\"fileType\" = 'docx'\n LEFT JOIN LATERAL (\n SELECT\n i.id\n FROM\n \"DocumentInstance\" i\n WHERE\n i.\"documentId\" = d.id\n ORDER BY\n i.\"updatedAt\" ASC\n LIMIT 1\n ) dipdf ON d.\"fileType\" = 'pdf'\n LEFT JOIN LATERAL (\n SELECT\n i.id\n FROM\n \"DocumentInstance\" i\n WHERE\n i.\"documentId\" = d.id\n ORDER BY\n i.\"createdAt\" DESC\n LIMIT 1\n ) di ON d.\"fileType\" IS DISTINCT FROM 'docx' AND d.\"fileType\" IS DISTINCT FROM 'pdf'\n WHERE\n d.\"fileType\" IS NOT NULL\n AND ($3::text[] IS NULL OR d.\"fileType\" = ANY($3))\n AND ($4::text IS NULL OR dst.sub_type::text = $4)\n AND ($5::timestamptz IS NULL OR d.\"createdAt\" >= $5)\n AND ($6::timestamptz IS NULL OR d.\"createdAt\" < $6)\n ORDER BY d.\"createdAt\" ASC, d.id ASC\n LIMIT $1 OFFSET $2\n ",
"describe": {
"columns": [
{
@@ -47,5 +47,5 @@
null
]
},
- "hash": "929e8e21a0b181340c4d74adbb26e14ec0c63b5f7da47d260f84eb0cfb15c575"
+ "hash": "8a64d1a5859b13c18516410d4fd512dd8b1359893d3e414b18f082fb48bfd907"
}
diff --git a/rust/cloud-storage/.sqlx/query-a7546aa6e8594ac3e66cd708f033fab241312305c74f1bcdb32b96e924030b1d.json b/rust/cloud-storage/.sqlx/query-a7546aa6e8594ac3e66cd708f033fab241312305c74f1bcdb32b96e924030b1d.json
new file mode 100644
index 0000000000..ab2522aa98
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-a7546aa6e8594ac3e66cd708f033fab241312305c74f1bcdb32b96e924030b1d.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id,\n deleted_at::timestamptz as \"deleted_at\"\n FROM comms_messages\n WHERE id = ANY($1)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "deleted_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ null
+ ]
+ },
+ "hash": "a7546aa6e8594ac3e66cd708f033fab241312305c74f1bcdb32b96e924030b1d"
+}
diff --git a/rust/cloud-storage/.sqlx/query-a9822aca7429a3fd0c2ab83450b7e23bac9bcae5ebd973db3ef6016100721bb7.json b/rust/cloud-storage/.sqlx/query-b4610bd3a0c3e13755b2f9500f9ee6c70139ba5411aae2fe0bb67040ff4060ba.json
similarity index 83%
rename from rust/cloud-storage/.sqlx/query-a9822aca7429a3fd0c2ab83450b7e23bac9bcae5ebd973db3ef6016100721bb7.json
rename to rust/cloud-storage/.sqlx/query-b4610bd3a0c3e13755b2f9500f9ee6c70139ba5411aae2fe0bb67040ff4060ba.json
index 0fd2576284..f0901e8538 100644
--- a/rust/cloud-storage/.sqlx/query-a9822aca7429a3fd0c2ab83450b7e23bac9bcae5ebd973db3ef6016100721bb7.json
+++ b/rust/cloud-storage/.sqlx/query-b4610bd3a0c3e13755b2f9500f9ee6c70139ba5411aae2fe0bb67040ff4060ba.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n c.\"id\" as \"chat_id\",\n m.id as \"message_id\",\n c.\"userId\" as \"user_id\",\n c.\"createdAt\" as \"created_at\",\n c.\"updatedAt\" as \"updated_at\"\n FROM\n \"ChatMessage\" m\n JOIN\n \"Chat\" c on c.\"id\" = m.\"chatId\"\n WHERE\n c.\"userId\" = ANY($1) AND c.\"deletedAt\" IS NULL\n ORDER BY\n m.\"createdAt\" DESC\n LIMIT $2\n OFFSET $3\n ",
+ "query": "\n SELECT\n c.\"id\" as \"chat_id\",\n m.id as \"message_id\",\n c.\"userId\" as \"user_id\",\n c.\"createdAt\" as \"created_at\",\n c.\"updatedAt\" as \"updated_at\"\n FROM\n \"ChatMessage\" m\n JOIN\n \"Chat\" c on c.\"id\" = m.\"chatId\"\n WHERE\n c.\"userId\" = ANY($1)\n ORDER BY\n m.\"createdAt\" DESC\n LIMIT $2\n OFFSET $3\n ",
"describe": {
"columns": [
{
@@ -44,5 +44,5 @@
false
]
},
- "hash": "a9822aca7429a3fd0c2ab83450b7e23bac9bcae5ebd973db3ef6016100721bb7"
+ "hash": "b4610bd3a0c3e13755b2f9500f9ee6c70139ba5411aae2fe0bb67040ff4060ba"
}
diff --git a/rust/cloud-storage/.sqlx/query-d20bc5b5dfecf0a2ef4b7d77b9090ad28584cd0a1fd24460096b6a5097a870ac.json b/rust/cloud-storage/.sqlx/query-d20bc5b5dfecf0a2ef4b7d77b9090ad28584cd0a1fd24460096b6a5097a870ac.json
deleted file mode 100644
index f3780614e0..0000000000
--- a/rust/cloud-storage/.sqlx/query-d20bc5b5dfecf0a2ef4b7d77b9090ad28584cd0a1fd24460096b6a5097a870ac.json
+++ /dev/null
@@ -1,97 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n un.user_id as owner_id,\n un.notification_id,\n n.event_item_id,\n n.event_item_type,\n un.sent,\n un.done,\n un.created_at::timestamptz as \"created_at!\",\n un.seen_at::timestamptz as viewed_at,\n un.created_at::timestamptz as \"updated_at!\",\n un.deleted_at::timestamptz,\n n.metadata as \"notification_metadata: serde_json::Value\",\n n.notification_event_type as notification_event_type,\n n.sender_id as sender_id\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND un.deleted_at IS NULL\n AND un.done = false\n AND (($3::timestamptz IS NULL)\n OR (un.created_at, un.notification_id) < ($3, $4))\n ORDER BY un.created_at DESC, un.notification_id DESC\n LIMIT $2\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "owner_id",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "notification_id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 2,
- "name": "event_item_id",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "event_item_type",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "sent",
- "type_info": "Bool"
- },
- {
- "ordinal": 5,
- "name": "done",
- "type_info": "Bool"
- },
- {
- "ordinal": 6,
- "name": "created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "viewed_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 8,
- "name": "updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 9,
- "name": "deleted_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 10,
- "name": "notification_metadata: serde_json::Value",
- "type_info": "Jsonb"
- },
- {
- "ordinal": 11,
- "name": "notification_event_type",
- "type_info": "Varchar"
- },
- {
- "ordinal": 12,
- "name": "sender_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Int8",
- "Timestamptz",
- "Uuid"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- false,
- false,
- false,
- null,
- null,
- null,
- null,
- false,
- false,
- true
- ]
- },
- "hash": "d20bc5b5dfecf0a2ef4b7d77b9090ad28584cd0a1fd24460096b6a5097a870ac"
-}
diff --git a/rust/cloud-storage/.sqlx/query-01fe7f04dbd686c1488b3e98eb9c5ed15ff504b22dce8bc1589c9a557f511dcb.json b/rust/cloud-storage/.sqlx/query-ded3c77986c957d0b5edbfb5e04cb63ffd5becc08d842380dd9f89767e139a5d.json
similarity index 80%
rename from rust/cloud-storage/.sqlx/query-01fe7f04dbd686c1488b3e98eb9c5ed15ff504b22dce8bc1589c9a557f511dcb.json
rename to rust/cloud-storage/.sqlx/query-ded3c77986c957d0b5edbfb5e04cb63ffd5becc08d842380dd9f89767e139a5d.json
index 1c540f1878..3f0dac7de0 100644
--- a/rust/cloud-storage/.sqlx/query-01fe7f04dbd686c1488b3e98eb9c5ed15ff504b22dce8bc1589c9a557f511dcb.json
+++ b/rust/cloud-storage/.sqlx/query-ded3c77986c957d0b5edbfb5e04cb63ffd5becc08d842380dd9f89767e139a5d.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n c.\"id\" as \"chat_id\",\n m.id as \"message_id\",\n c.\"userId\" as \"user_id\",\n c.\"createdAt\" as \"created_at\",\n c.\"updatedAt\" as \"updated_at\"\n FROM\n \"ChatMessage\" m\n JOIN\n \"Chat\" c on c.\"id\" = m.\"chatId\"\n WHERE c.\"deletedAt\" IS NULL\n ORDER BY\n m.\"createdAt\" DESC\n LIMIT $1\n OFFSET $2\n ",
+ "query": "\n SELECT\n c.\"id\" as \"chat_id\",\n m.id as \"message_id\",\n c.\"userId\" as \"user_id\",\n c.\"createdAt\" as \"created_at\",\n c.\"updatedAt\" as \"updated_at\"\n FROM\n \"ChatMessage\" m\n JOIN\n \"Chat\" c on c.\"id\" = m.\"chatId\"\n ORDER BY\n m.\"createdAt\" DESC\n LIMIT $1\n OFFSET $2\n ",
"describe": {
"columns": [
{
@@ -43,5 +43,5 @@
false
]
},
- "hash": "01fe7f04dbd686c1488b3e98eb9c5ed15ff504b22dce8bc1589c9a557f511dcb"
+ "hash": "ded3c77986c957d0b5edbfb5e04cb63ffd5becc08d842380dd9f89767e139a5d"
}
diff --git a/rust/cloud-storage/comms_db_client/src/messages/get_deleted_ats.rs b/rust/cloud-storage/comms_db_client/src/messages/get_deleted_ats.rs
new file mode 100644
index 0000000000..0bb0c4b054
--- /dev/null
+++ b/rust/cloud-storage/comms_db_client/src/messages/get_deleted_ats.rs
@@ -0,0 +1,36 @@
+use anyhow::{Context, Result};
+use chrono::{DateTime, Utc};
+use sqlx::{Pool, Postgres};
+use std::collections::HashMap;
+use uuid::Uuid;
+
+/// Returns a map keyed by message id for every message in `message_ids` that
+/// exists in `comms_messages`. The value is the message's `deleted_at`
+/// timestamp when soft-deleted, or `None` when active. Message ids absent
+/// from the returned map have no row in the database (e.g. hard-deleted or
+/// stale OpenSearch entries) and should be treated as not surfacable.
+#[tracing::instrument(skip(db))]
+pub async fn get_message_deletion_states(
+ db: &Pool<Postgres>,
+ message_ids: &[Uuid],
+) -> Result<HashMap<Uuid, Option<DateTime<Utc>>>> {
+ if message_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+
+ let rows = sqlx::query!(
+ r#"
+ SELECT
+ id,
+ deleted_at::timestamptz as "deleted_at"
+ FROM comms_messages
+ WHERE id = ANY($1)
+ "#,
+ message_ids,
+ )
+ .fetch_all(db)
+ .await
+ .context("unable to fetch message deletion states")?;
+
+ Ok(rows.into_iter().map(|r| (r.id, r.deleted_at)).collect())
+}
diff --git a/rust/cloud-storage/comms_db_client/src/messages/mod.rs b/rust/cloud-storage/comms_db_client/src/messages/mod.rs
index a14c665f08..cbe1893b34 100644
--- a/rust/cloud-storage/comms_db_client/src/messages/mod.rs
+++ b/rust/cloud-storage/comms_db_client/src/messages/mod.rs
@@ -4,6 +4,7 @@ pub mod create_message_mentions;
pub mod delete_message;
pub mod get_channel_message;
pub mod get_count;
+pub mod get_deleted_ats;
pub mod get_message_owner;
pub mod get_messages;
pub mod patch_message;
diff --git a/rust/cloud-storage/macro_db_client/src/chat/get.rs b/rust/cloud-storage/macro_db_client/src/chat/get.rs
index 125d499fea..4cafe618f1 100644
--- a/rust/cloud-storage/macro_db_client/src/chat/get.rs
+++ b/rust/cloud-storage/macro_db_client/src/chat/get.rs
@@ -49,7 +49,6 @@ pub async fn get_chat_messages_for_search_backfill(
"ChatMessage" m
JOIN
"Chat" c on c."id" = m."chatId"
- WHERE c."deletedAt" IS NULL
ORDER BY
m."createdAt" DESC
LIMIT $1
@@ -91,7 +90,7 @@ async fn get_chat_messages_for_search_backfill_chat_ids(
JOIN
"Chat" c on c."id" = m."chatId"
WHERE
- m."chatId" = ANY($1) AND c."deletedAt" IS NULL
+ m."chatId" = ANY($1)
ORDER BY
m."createdAt" DESC
LIMIT $2
@@ -134,7 +133,7 @@ async fn get_chat_messages_for_search_backfill_user_ids(
JOIN
"Chat" c on c."id" = m."chatId"
WHERE
- c."userId" = ANY($1) AND c."deletedAt" IS NULL
+ c."userId" = ANY($1)
ORDER BY
m."createdAt" DESC
LIMIT $2
@@ -157,42 +156,59 @@ async fn get_chat_messages_for_search_backfill_user_ids(
Ok(result)
}
-/// Gets the chat title, message content and role used for search
-/// NOTE: this does not return persistent chats
+/// Chat message info used for search indexing. `deleted_at` is set when the
+/// owning chat has been soft-deleted, allowing the indexer to remove the
+/// message from the search index instead of upserting it.
+#[derive(Debug, Clone)]
+pub struct ChatMessageInfo {
+ pub name: String,
+ pub content: String,
+ pub role: String,
+ pub deleted_at: Option<DateTime<Utc>>,
+}
+
+/// Gets the chat title, message content and role used for search.
+/// Returns `None` when the message does not exist or the owning chat is
+/// persistent (persistent chats are not indexed). Soft-deleted chats are
+/// returned with `deleted_at` populated so the caller can prune the search
+/// index entry.
#[tracing::instrument(skip(db))]
pub async fn get_chat_message_info(
db: &sqlx::Pool<sqlx::Postgres>,
chat_id: &str,
chat_message_id: &str,
-) -> anyhow::Result<Option<(String, String, String)>> {
+) -> anyhow::Result<Option<ChatMessageInfo>> {
let result = sqlx::query!(
r#"
SELECT
m.content as "content",
c.name as "name",
- m.role as "role"
+ m.role as "role",
+ c."deletedAt"::timestamptz as "deleted_at"
FROM
"ChatMessage" m
JOIN
"Chat" c on c."id" = m."chatId"
WHERE
- m.id = $1 AND m."chatId" = $2 AND c."deletedAt" IS NULL AND c."isPersistent" = false
+ m.id = $1 AND m."chatId" = $2 AND c."isPersistent" = false
"#,
chat_message_id,
chat_id
)
- .map(|row| (row.name, row.content, row.role))
.fetch_optional(db)
.await?;
- if let Some((name, content, role)) = result {
- return serde_json::from_value::<ChatMessageContent>(content)
- .map(|content| (name, content.message_text(), role))
- .map_err(anyhow::Error::from)
- .map(Some);
- }
+ let Some(row) = result else {
+ return Ok(None);
+ };
- Ok(None)
+ let content = serde_json::from_value::<ChatMessageContent>(row.content)?.message_text();
+ Ok(Some(ChatMessageInfo {
+ name: row.name,
+ content,
+ role: row.role,
+ deleted_at: row.deleted_at,
+ }))
}
/// Gets the chats metadata for updating the chat message metadata
diff --git a/rust/cloud-storage/macro_db_client/src/document/get_documents_search.rs b/rust/cloud-storage/macro_db_client/src/document/get_documents_search.rs
index f0caf969a9..3a8a17e676 100644
--- a/rust/cloud-storage/macro_db_client/src/document/get_documents_search.rs
+++ b/rust/cloud-storage/macro_db_client/src/document/get_documents_search.rs
@@ -63,8 +63,7 @@ pub async fn get_documents_for_search(
LIMIT 1
) di ON d."fileType" IS DISTINCT FROM 'docx' AND d."fileType" IS DISTINCT FROM 'pdf'
WHERE
- d."deletedAt" IS NULL
- AND d."fileType" IS NOT NULL
+ d."fileType" IS NOT NULL
AND ($3::text[] IS NULL OR d."fileType" = ANY($3))
AND ($4::text IS NULL OR dst.sub_type::text = $4)
AND ($5::timestamptz IS NULL OR d."createdAt" >= $5)
diff --git a/rust/cloud-storage/models_search/src/channel.rs b/rust/cloud-storage/models_search/src/channel.rs
index a1dd2ab8da..2f3fa52ffa 100644
--- a/rust/cloud-storage/models_search/src/channel.rs
+++ b/rust/cloud-storage/models_search/src/channel.rs
@@ -22,6 +22,8 @@ pub struct ChannelSearchResult {
/// When the channel message was last updated
/// This is only prsent if the search result is on the message content
pub updated_at: Option<DateTime<Utc>>,
+ /// When the channel message was deleted, if it has been
+ pub deleted_at: Option<DateTime<Utc>>,
/// The highlights for the channel message
pub highlight: SearchHighlight,
/// The score of the result
diff --git a/rust/cloud-storage/opensearch_client/src/delete/channel.rs b/rust/cloud-storage/opensearch_client/src/delete/channel.rs
index e6122b1762..f058fa81ab 100644
--- a/rust/cloud-storage/opensearch_client/src/delete/channel.rs
+++ b/rust/cloud-storage/opensearch_client/src/delete/channel.rs
@@ -8,7 +8,7 @@ pub async fn delete_channel_by_id(client: &opensearch::OpenSearch, channel_id: &
let query = serde_json::json!({
"query": {
"term": {
- "channel_id": channel_id
+ "entity_id": channel_id
}
},
});
@@ -66,7 +66,7 @@ pub async fn delete_channel_message_by_id(
"must": [
{
"term": {
- "channel_id": channel_id
+ "entity_id": channel_id
}
},
{
diff --git a/rust/cloud-storage/opensearch_client/src/delete/chat.rs b/rust/cloud-storage/opensearch_client/src/delete/chat.rs
index 746246a7c1..67d8b07b5d 100644
--- a/rust/cloud-storage/opensearch_client/src/delete/chat.rs
+++ b/rust/cloud-storage/opensearch_client/src/delete/chat.rs
@@ -8,7 +8,7 @@ pub async fn delete_chat_by_id(client: &opensearch::OpenSearch, chat_id: &str) -
let query = serde_json::json!({
"query": {
"term": {
- "chat_id": chat_id
+ "entity_id": chat_id
}
},
});
@@ -66,7 +66,7 @@ pub async fn delete_chat_message_by_id(
"must": [
{
"term": {
- "chat_id": chat_id
+ "entity_id": chat_id
}
},
{
diff --git a/rust/cloud-storage/opensearch_client/src/delete/document.rs b/rust/cloud-storage/opensearch_client/src/delete/document.rs
index e4dfec50d8..ac7a4a4415 100644
--- a/rust/cloud-storage/opensearch_client/src/delete/document.rs
+++ b/rust/cloud-storage/opensearch_client/src/delete/document.rs
@@ -12,7 +12,7 @@ pub async fn delete_document_by_id(
let query = serde_json::json!({
"query": {
"term": {
- "document_id": document_id
+ "entity_id": document_id
}
},
});
diff --git a/rust/cloud-storage/opensearch_client/src/delete/email.rs b/rust/cloud-storage/opensearch_client/src/delete/email.rs
index 4f74646be9..0f97c57728 100644
--- a/rust/cloud-storage/opensearch_client/src/delete/email.rs
+++ b/rust/cloud-storage/opensearch_client/src/delete/email.rs
@@ -2,60 +2,6 @@ use models_opensearch::SearchIndex;
use crate::{Result, error::OpensearchClientError};
-/// Deletes all email messages with the specified thread_id
-#[tracing::instrument(skip(client))]
-pub async fn delete_email_by_thread_id(
- client: &opensearch::OpenSearch,
- thread_id: &str,
-) -> Result<()> {
- let query = serde_json::json!({
- "query": {
- "term": {
- "thread_id": thread_id
- }
- },
- });
-
- let response = client
- .delete_by_query(opensearch::DeleteByQueryParts::Index(&[
- SearchIndex::Emails.as_ref(),
- ]))
- .body(query)
- .refresh(true) // Ensure the index reflects changes immediately
- .send()
- .await
- .map_err(|err| OpensearchClientError::Unknown {
- details: err.to_string(),
- method: Some("delete_email_by_thread_id".to_string()),
- })?;
-
- let status_code = response.status_code();
-
- if !status_code.is_success() {
- let body =
- response
- .text()
- .await
- .map_err(|err| OpensearchClientError::DeserializationFailed {
- details: err.to_string(),
- method: Some("delete_email_by_thread_id".to_string()),
- })?;
-
- tracing::error!(
- status_code = ?status_code,
- body = ?body,
- "error deleting chats by id"
- );
-
- return Err(OpensearchClientError::Unknown {
- details: body,
- method: Some("delete_email_by_thread_id".to_string()),
- });
- }
-
- Ok(())
-}
-
/// Deletes all email messages with the specified link_id
#[tracing::instrument(skip(client))]
pub async fn delete_email_by_link_id(client: &opensearch::OpenSearch, link_id: &str) -> Result<()> {
diff --git a/rust/cloud-storage/opensearch_client/src/email.rs b/rust/cloud-storage/opensearch_client/src/email.rs
index 999bcd1fd7..e8928b3247 100644
--- a/rust/cloud-storage/opensearch_client/src/email.rs
+++ b/rust/cloud-storage/opensearch_client/src/email.rs
@@ -20,11 +20,6 @@ impl OpensearchClient {
upsert::email::bulk_upsert_email_messages(&self.inner, messages, index_override).await
}
- /// Deletes all email messages with the specified thread_id
- pub async fn delete_email_by_thread_id(&self, thread_id: &str) -> Result<()> {
- delete::email::delete_email_by_thread_id(&self.inner, thread_id).await
- }
-
/// Deletes a particular email message
pub async fn delete_email_message_by_id(&self, message_id: &str) -> Result<()> {
delete::email::delete_email_message_by_id(&self.inner, message_id).await
diff --git a/rust/cloud-storage/opensearch_client/src/upsert/chat_message.rs b/rust/cloud-storage/opensearch_client/src/upsert/chat_message.rs
index 7fda820294..0cf7faef0b 100644
--- a/rust/cloud-storage/opensearch_client/src/upsert/chat_message.rs
+++ b/rust/cloud-storage/opensearch_client/src/upsert/chat_message.rs
@@ -83,7 +83,7 @@ pub(crate) async fn update_chat_metadata(
let query = json!({
"query": {
"term": {
- "chat_id": chat_id
+ "entity_id": chat_id
}
},
"script": {
diff --git a/rust/cloud-storage/opensearch_client/src/upsert/document.rs b/rust/cloud-storage/opensearch_client/src/upsert/document.rs
index accdc7dfdf..e07c8bc53a 100644
--- a/rust/cloud-storage/opensearch_client/src/upsert/document.rs
+++ b/rust/cloud-storage/opensearch_client/src/upsert/document.rs
@@ -199,7 +199,7 @@ pub(crate) async fn update_document_metadata(
let query = json!({
"query": {
"term": {
- "document_id": document_id
+ "entity_id": document_id
}
},
"script": {
diff --git a/rust/cloud-storage/search_processing_service/src/process/channel.rs b/rust/cloud-storage/search_processing_service/src/process/channel.rs
index 09fdbfe62a..3b66c8014c 100644
--- a/rust/cloud-storage/search_processing_service/src/process/channel.rs
+++ b/rust/cloud-storage/search_processing_service/src/process/channel.rs
@@ -25,7 +25,10 @@ pub async fn process_channel_message_update(
.context("unable to get channel message")?;
if channel_message_info.channel_message.deleted_at.is_some() {
- tracing::trace!("channel message is deleted, skipping");
+ tracing::trace!("channel message is deleted, removing from search index");
+ opensearch_client
+ .delete_channel_message(&message.channel_id, &message.message_id)
+ .await?;
return Ok(());
}
diff --git a/rust/cloud-storage/search_processing_service/src/process/chat.rs b/rust/cloud-storage/search_processing_service/src/process/chat.rs
index bb54da49fd..2ca793209f 100644
--- a/rust/cloud-storage/search_processing_service/src/process/chat.rs
+++ b/rust/cloud-storage/search_processing_service/src/process/chat.rs
@@ -11,7 +11,7 @@ pub async fn insert_chat_message(
db: &sqlx::Pool<sqlx::Postgres>,
chat_message: &ChatMessage,
) -> anyhow::Result<()> {
- let result = macro_db_client::chat::get::get_chat_message_info(
+ let info = macro_db_client::chat::get::get_chat_message_info(
db,
chat_message.chat_id.as_str(),
chat_message.message_id.as_str(),
@@ -19,22 +19,36 @@ pub async fn insert_chat_message(
.await
.context("failed to get chat message info")?;
- if let Some((title, content, role)) = result {
+ let Some(info) = info else {
+ return Ok(());
+ };
+
+ if info.deleted_at.is_some() {
+ tracing::trace!("chat is deleted, removing message from search index");
opensearch_client
- .upsert_chat_message(&UpsertChatMessageArgs {
- chat_id: chat_message.chat_id.clone(),
- chat_message_id: chat_message.message_id.clone(),
- user_id: chat_message.user_id.clone(),
- created_at_seconds: EpochSeconds::new(chat_message.created_at.clone().timestamp())?,
- updated_at_seconds: EpochSeconds::new(chat_message.updated_at.clone().timestamp())?,
- title,
- content,
- role,
- })
+ .delete_chat_message(
+ chat_message.chat_id.as_str(),
+ chat_message.message_id.as_str(),
+ )
.await
- .context("failed to upsert chat message")?;
+ .context("failed to delete chat message from search")?;
+ return Ok(());
}
+ opensearch_client
+ .upsert_chat_message(&UpsertChatMessageArgs {
+ chat_id: chat_message.chat_id.clone(),
+ chat_message_id: chat_message.message_id.clone(),
+ user_id: chat_message.user_id.clone(),
+ created_at_seconds: EpochSeconds::new(chat_message.created_at.timestamp())?,
+ updated_at_seconds: EpochSeconds::new(chat_message.updated_at.timestamp())?,
+ title: info.name,
+ content: info.content,
+ role: info.role,
+ })
+ .await
+ .context("failed to upsert chat message")?;
+
Ok(())
}
diff --git a/rust/cloud-storage/search_processing_service/src/process/document/document_info.rs b/rust/cloud-storage/search_processing_service/src/process/document/document_info.rs
index c71d39f191..8a7175c0d8 100644
--- a/rust/cloud-storage/search_processing_service/src/process/document/document_info.rs
+++ b/rust/cloud-storage/search_processing_service/src/process/document/document_info.rs
@@ -2,12 +2,24 @@ use model::document::DocumentMetadata;
use super::SearchExtractorMessage;
-/// Gets the document metadata (latest version of the document) from the database if it exists
+/// Result of looking up a document for indexing.
+pub enum DocumentInfo {
+ /// Active document — proceed with indexing.
+ Active(Box<DocumentMetadata>),
+ /// Document has been soft-deleted or no longer exists in the DB. The
+ /// caller should remove any matching entry from the search index.
+ Removable,
+ /// Lookup hit an unexpected absence (e.g. version metadata missing). The
+ /// caller should leave the search index untouched.
+ Skip,
+}
+
+/// Gets the document metadata (latest version of the document) from the database.
#[tracing::instrument(skip(db, search_extractor_message), fields(document_id=search_extractor_message.document_id))]
pub async fn get_document_info(
db: &sqlx::Pool<sqlx::Postgres>,
search_extractor_message: &SearchExtractorMessage,
-) -> anyhow::Result<Option<DocumentMetadata>> {
+) -> anyhow::Result<DocumentInfo> {
let document_basic = match macro_db_client::document::get_basic_document(
db,
search_extractor_message.document_id.as_str(),
@@ -15,30 +27,24 @@ pub async fn get_document_info(
.await
{
Ok(document) => document,
- Err(e) => match e {
- sqlx::Error::RowNotFound => {
- return Ok(None);
- }
- _ => {
- anyhow::bail!("unable to get basic document")
- }
- },
+ Err(sqlx::Error::RowNotFound) => return Ok(DocumentInfo::Removable),
+ Err(_) => anyhow::bail!("unable to get basic document"),
};
if document_basic.deleted_at.is_some() {
- return Ok(None);
+ return Ok(DocumentInfo::Removable);
}
match macro_db_client::document::get_document(db, search_extractor_message.document_id.as_str())
.await
{
- Ok(document) => Ok(Some(document)),
+ Ok(document) => Ok(DocumentInfo::Active(Box::new(document))),
Err(e) => {
if e.to_string()
.contains("no rows returned by a query that expected to return at least one")
{
- tracing::debug!("document not found");
- Ok(None)
+ tracing::debug!("document version not found");
+ Ok(DocumentInfo::Skip)
} else {
Err(e)
}
diff --git a/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs b/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs
index d65b23e53a..7cd4c2870b 100644
--- a/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs
+++ b/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs
@@ -15,7 +15,7 @@ use s3_key::{
use crate::{
parsers::{canvas::parse_canvas, markdown::parse_markdown_legacy, pdf::parse_pdf_pages},
- process::document::document_info::get_document_info,
+ process::document::document_info::{DocumentInfo, get_document_info},
};
use super::SearchExtractorMessage;
@@ -76,15 +76,23 @@ pub async fn update_search_with_raw_document(
}
// This ensures we only process the latest version
- let document_info = get_document_info(db, search_extractor_message)
+ let document_info = match get_document_info(db, search_extractor_message)
.await
- .context("failed to get document info")?;
-
- let document_info = if let Some(document_info) = document_info {
- document_info
- } else {
- tracing::trace!("no document info returned");
- return Ok(());
+ .context("failed to get document info")?
+ {
+ DocumentInfo::Active(info) => *info,
+ DocumentInfo::Removable => {
+ tracing::trace!("document is deleted or missing, removing from search index");
+ opensearch_client
+ .delete_document(&search_extractor_message.document_id)
+ .await
+ .context("failed to delete document from search index")?;
+ return Ok(());
+ }
+ DocumentInfo::Skip => {
+ tracing::trace!("no document info returned");
+ return Ok(());
+ }
};
let document_name = document_info.document_name;
@@ -286,15 +294,23 @@ pub async fn update_search_with_sync_document(
}
}
- let document_info = get_document_info(db, search_extractor_message)
+ let document_info = match get_document_info(db, search_extractor_message)
.await
- .context("failed to get document info")?;
-
- let document_info = if let Some(document_info) = document_info {
- document_info
- } else {
- tracing::trace!("no document info returned");
- return Ok(());
+ .context("failed to get document info")?
+ {
+ DocumentInfo::Active(info) => *info,
+ DocumentInfo::Removable => {
+ tracing::trace!("document is deleted or missing, removing from search index");
+ opensearch_client
+ .delete_document(&search_extractor_message.document_id)
+ .await
+ .context("failed to delete document from search index")?;
+ return Ok(());
+ }
+ DocumentInfo::Skip => {
+ tracing::trace!("no document info returned");
+ return Ok(());
+ }
};
let document_id = &search_extractor_message.document_id;
diff --git a/rust/cloud-storage/search_service/src/api/search/channel.rs b/rust/cloud-storage/search_service/src/api/search/channel.rs
index ccc1af1101..e636e9c4a2 100644
--- a/rust/cloud-storage/search_service/src/api/search/channel.rs
+++ b/rust/cloud-storage/search_service/src/api/search/channel.rs
@@ -1,4 +1,5 @@
use crate::api::search::simple::SearchError;
+use chrono::{DateTime, Utc};
use indexmap::IndexMap;
use std::collections::HashMap;
@@ -29,18 +30,38 @@ pub(in crate::api::search) async fn enrich_channels(
// Extract channel IDs from results
let channel_ids: Vec<Uuid> = results.iter().map(|r| r.entity_id).collect();
- // Fetch channel metadata directly from DB
- let channel_histories = comms_db_client::activity::get_activity::get_channel_history_info(
- &ctx.db,
- user_id,
- &channel_ids,
+ // Extract message IDs from results so we can flag any that have been deleted.
+ let message_ids: Vec<Uuid> = results
+ .iter()
+ .filter_map(|r| match &r.goto {
+ Some(SearchGotoContent::Channels(goto)) => Some(goto.channel_message_id),
+ _ => None,
+ })
+ .collect();
+
+ let (channel_histories, message_states) = tokio::try_join!(
+ async {
+ comms_db_client::activity::get_activity::get_channel_history_info(
+ &ctx.db,
+ user_id,
+ &channel_ids,
+ )
+ .await
+ .map_err(anyhow::Error::from)
+ },
+ async {
+ comms_db_client::messages::get_deleted_ats::get_message_deletion_states(
+ &ctx.db,
+ &message_ids,
+ )
+ .await
+ },
)
- .await
- .map_err(|e| SearchError::InternalError(e.into()))?;
+ .map_err(SearchError::InternalError)?;
// Construct enriched results
- let enriched_results =
- construct_search_result(results, channel_histories).map_err(SearchError::InternalError)?;
+ let enriched_results = construct_search_result(results, channel_histories, message_states)
+ .map_err(SearchError::InternalError)?;
Ok(enriched_results)
}
@@ -48,12 +69,17 @@ pub(in crate::api::search) async fn enrich_channels(
pub fn construct_search_result(
search_results: Vec<opensearch_client::search::model::SearchHit>,
channel_histories: HashMap<Uuid, ChannelHistoryInfo>,
+ message_states: HashMap<Uuid, Option<DateTime<Utc>>>,
) -> anyhow::Result<Vec<ChannelSearchResponseItemWithMetadata>> {
// construct entity hit map of id -> vec<hits> using IndexMap to preserve insertion order
let entity_id_hit_map: IndexMap<sqlx::types::Uuid, Vec<ChannelSearchResult>> = search_results
.into_iter()
- .map(|hit| {
+ .filter_map(|hit| {
let result = if let Some(SearchGotoContent::Channels(goto)) = hit.goto {
+ // Drop content-match hits whose underlying message no longer exists in
+ // the DB — those are stale OpenSearch entries (e.g. hard-deleted) that
+ // shouldn't surface to users.
+ let deleted_at = *message_states.get(&goto.channel_message_id)?;
ChannelSearchResult {
highlight: hit.highlight.into(),
score: hit.score,
@@ -62,6 +88,7 @@ pub fn construct_search_result(
sender_id: Some(goto.sender_id),
created_at: Some(goto.created_at),
updated_at: Some(goto.updated_at),
+ deleted_at,
}
} else {
// name match
@@ -73,9 +100,10 @@ pub fn construct_search_result(
sender_id: None,
created_at: None,
updated_at: None,
+ deleted_at: None,
}
};
- (hit.entity_id, result)
+ Some((hit.entity_id, result))
})
.fold(IndexMap::new(), |mut map, (entity_id, result)| {
map.entry(entity_id).or_insert_with(Vec::new).push(result);
diff --git a/rust/cloud-storage/search_service/src/api/search/channel/test.rs b/rust/cloud-storage/search_service/src/api/search/channel/test.rs
index ed6690f20a..53fa5f7077 100644
--- a/rust/cloud-storage/search_service/src/api/search/channel/test.rs
+++ b/rust/cloud-storage/search_service/src/api/search/channel/test.rs
@@ -1,12 +1,28 @@
-use chrono::DateTime;
+use chrono::{DateTime, Utc};
use models_opensearch::SearchEntityType;
use opensearch_client::search::model::Highlight;
use super::*;
+/// Build a message_states map that marks every content-match hit's
+/// channel_message_id as existing-and-active. Tests that want to exercise
+/// orphan filtering or soft-delete state should construct the map manually.
+fn active_states_for(
+ hits: &[opensearch_client::search::model::SearchHit],
+) -> HashMap<Uuid, Option<DateTime<Utc>>> {
+ hits.iter()
+ .filter_map(|hit| match &hit.goto {
+ Some(opensearch_client::search::model::SearchGotoContent::Channels(goto)) => {
+ Some((goto.channel_message_id, None))
+ }
+ _ => None,
+ })
+ .collect()
+}
+
#[test]
fn test_construct_search_result_empty_input() {
- let result = construct_search_result(vec![], HashMap::new());
+ let result = construct_search_result(vec![], HashMap::new(), HashMap::new());
assert!(result.is_ok());
assert_eq!(result.unwrap().len(), 0);
}
@@ -43,7 +59,8 @@ fn test_construct_search_result_single_channel() {
create_channel_history(channel_uuid.to_string().as_str()),
);
- let result = construct_search_result(search_results, channel_histories).unwrap();
+ let states = active_states_for(&search_results);
+ let result = construct_search_result(search_results, channel_histories, states).unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0].extra.channel_id, channel_uuid);
@@ -125,7 +142,8 @@ fn test_construct_search_result_multiple_messages_same_channel() {
create_channel_history(channel_uuid.to_string().as_str()),
);
- let result = construct_search_result(search_results, channel_histories).unwrap();
+ let states = active_states_for(&search_results);
+ let result = construct_search_result(search_results, channel_histories, states).unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0].extra.channel_id, channel_uuid);
@@ -207,7 +225,8 @@ fn test_construct_search_result_filters_messages_without_content() {
create_channel_history(channel_uuid.to_string().as_str()),
);
- let result = construct_search_result(search_results, channel_histories).unwrap();
+ let states = active_states_for(&search_results);
+ let result = construct_search_result(search_results, channel_histories, states).unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0].extra.channel_message_search_results.len(), 2);
@@ -221,6 +240,60 @@ fn test_construct_search_result_filters_messages_without_content() {
);
}
+#[test]
+fn test_construct_search_result_filters_orphans_and_propagates_deleted_at() {
+ let channel_uuid: Uuid = "550e8400-e29b-41d4-a716-446655440099".parse().unwrap();
+ let active_message_id: Uuid = "11111111-1111-1111-1111-111111111111".parse().unwrap();
+ let deleted_message_id: Uuid = "22222222-2222-2222-2222-222222222222".parse().unwrap();
+ let orphan_message_id: Uuid = "33333333-3333-3333-3333-333333333333".parse().unwrap();
+
+ let search_results = vec![
+ create_test_channel_response(
+ &channel_uuid.to_string(),
+ &active_message_id.to_string(),
+ "user1",
+ Some(vec!["active".to_string()]),
+ ),
+ create_test_channel_response(
+ &channel_uuid.to_string(),
+ &deleted_message_id.to_string(),
+ "user2",
+ Some(vec!["deleted".to_string()]),
+ ),
+ create_test_channel_response(
+ &channel_uuid.to_string(),
+ &orphan_message_id.to_string(),
+ "user3",
+ Some(vec!["orphan".to_string()]),
+ ),
+ ];
+
+ let mut channel_histories = HashMap::new();
+ channel_histories.insert(
+ channel_uuid,
+ create_channel_history(channel_uuid.to_string().as_str()),
+ );
+
+ let deleted_at = DateTime::from_timestamp(1700000000, 0).unwrap();
+ let mut states: HashMap<Uuid, Option<DateTime<Utc>>> = HashMap::new();
+ states.insert(active_message_id, None);
+ states.insert(deleted_message_id, Some(deleted_at));
+ // orphan_message_id intentionally omitted to simulate a hard-deleted row.
+
+ let result = construct_search_result(search_results, channel_histories, states).unwrap();
+
+ assert_eq!(result.len(), 1);
+ let hits = &result[0].extra.channel_message_search_results;
+ assert_eq!(hits.len(), 2, "orphan hit should be filtered out");
+
+ let by_id: HashMap<Uuid, &ChannelSearchResult> =
+ hits.iter().map(|h| (h.message_id.unwrap(), h)).collect();
+
+ assert_eq!(by_id[&active_message_id].deleted_at, None);
+ assert_eq!(by_id[&deleted_message_id].deleted_at, Some(deleted_at));
+ assert!(!by_id.contains_key(&orphan_message_id));
+}
+
fn create_test_channel_response(
channel_id: &str,
message_id: &str,
@@ -293,7 +366,8 @@ fn test_channel_history_timestamps() {
)];
// Call the function under test
- let result = construct_search_result(input, channel_histories).unwrap();
+ let states = active_states_for(&input);
+ let result = construct_search_result(input, channel_histories, states).unwrap();
// Verify that timestamps were copied from the channel history
assert_eq!(result.len(), 1);
@@ -334,7 +408,8 @@ fn test_channel_history_missing_entry() {
channel_histories.insert(different_channel_uuid, history);
// Call the function under test
- let result = construct_search_result(input, channel_histories).unwrap();
+ let states = active_states_for(&input);
+ let result = construct_search_result(input, channel_histories, states).unwrap();
// Channels without history info should not be returned
assert_eq!(result.len(), 0);
@@ -368,7 +443,8 @@ fn test_channel_history_null_viewed_at() {
channel_histories.insert(channel_uuid, history);
// Call the function under test
- let result = construct_search_result(input, channel_histories).unwrap();
+ let states = active_states_for(&input);
+ let result = construct_search_result(input, channel_histories, states).unwrap();
// Verify that timestamps were copied correctly and viewed_at is None
assert_eq!(result.len(), 1);
@@ -514,9 +590,13 @@ fn test_sort_stability() {
);
}
- let result1 = construct_search_result(input.clone(), channel_histories.clone()).unwrap();
- let result2 = construct_search_result(input.clone(), channel_histories.clone()).unwrap();
- let result3 = construct_search_result(input.clone(), channel_histories.clone()).unwrap();
+ let states = active_states_for(&input);
+ let result1 =
+ construct_search_result(input.clone(), channel_histories.clone(), states.clone()).unwrap();
+ let result2 =
+ construct_search_result(input.clone(), channel_histories.clone(), states.clone()).unwrap();
+ let result3 =
+ construct_search_result(input.clone(), channel_histories.clone(), states).unwrap();
assert_eq!(result1.len(), 5);
assert_eq!(result2.len(), 5);
diff --git a/rust/cloud-storage/search_service/src/api/search/unified/test.rs b/rust/cloud-storage/search_service/src/api/search/unified/test.rs
index 38d10a409f..ac5ecb79cc 100644
--- a/rust/cloud-storage/search_service/src/api/search/unified/test.rs
+++ b/rust/cloud-storage/search_service/src/api/search/unified/test.rs
@@ -169,6 +169,7 @@ fn test_channel_updated_at_uses_max_from_message_results() {
sender_id: Some("sender1".to_string()),
created_at: Some(DateTime::from_timestamp(1800, 0).unwrap()),
updated_at: Some(DateTime::from_timestamp(2000, 0).unwrap()), // Second highest
+ deleted_at: None,
highlight: SearchHighlight::default(),
score: None,
},
@@ -178,6 +179,7 @@ fn test_channel_updated_at_uses_max_from_message_results() {
sender_id: Some("sender2".to_string()),
created_at: Some(DateTime::from_timestamp(2900, 0).unwrap()),
updated_at: Some(DateTime::from_timestamp(3000, 0).unwrap()), // Highest - should be used
+ deleted_at: None,
highlight: SearchHighlight::default(),
score: None,
},
@@ -187,6 +189,7 @@ fn test_channel_updated_at_uses_max_from_message_results() {
sender_id: Some("sender3".to_string()),
created_at: Some(DateTime::from_timestamp(1400, 0).unwrap()),
updated_at: Some(DateTime::from_timestamp(1500, 0).unwrap()), // Lowest of results
+ deleted_at: None,
highlight: SearchHighlight::default(),
score: None,
},
@@ -253,6 +256,7 @@ fn test_channel_updated_at_falls_back_to_metadata_when_results_have_no_updated_a
sender_id: Some("sender1".to_string()),
created_at: Some(DateTime::from_timestamp(1800, 0).unwrap()),
updated_at: None, // No updated_at
+ deleted_at: None,
highlight: SearchHighlight::default(),
score: None,
},
@@ -262,6 +266,7 @@ fn test_channel_updated_at_falls_back_to_metadata_when_results_have_no_updated_a
sender_id: Some("sender2".to_string()),
created_at: Some(DateTime::from_timestamp(2900, 0).unwrap()),
updated_at: None, // No updated_at
+ deleted_at: None,
highlight: SearchHighlight::default(),
score: None,
},
@@ -323,6 +328,7 @@ fn test_sort_unified_search_results_with_channel() {
sender_id: Some("sender1".to_string()),
created_at: Some(DateTime::from_timestamp(2900, 0).unwrap()),
updated_at: Some(DateTime::from_timestamp(3000, 0).unwrap()), // Should make channel sort first
+ deleted_at: None,
highlight: SearchHighlight::default(),
score: None,
}],