Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(search): chats v2 parent/child join + keyset backfill (#3492)

gbirman0a148b8b5bb0
diff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.ts
index ac0ca773a1..95b8ff86fd 100644
--- a/infra/stacks/cloud-storage-service/index.ts
+++ b/infra/stacks/cloud-storage-service/index.ts
@@ -464,6 +464,12 @@ const cloudStorageService = new CloudStorageService(
name: 'DOCUMENTS_INDEX_USES_JOIN',
value: config.get('documents_index_uses_join') ?? 'false',
},
+ {
+ // Same as DOCUMENTS_INDEX_USES_JOIN, but for the chats alias
+ // (`chats_v1` flat -> `chats_v2` parent/child).
+ name: 'CHATS_INDEX_USES_JOIN',
+ value: config.get('chats_index_uses_join') ?? 'false',
+ },
{
name: 'DATABASE_URL',
value: pulumi.interpolate`${DATABASE_URL}`,
diff --git a/infra/stacks/opensearch/helpers/scripts/create_chats_v2.ts b/infra/stacks/opensearch/helpers/scripts/create_chats_v2.ts
new file mode 100644
index 0000000000..df86954f87
--- /dev/null
+++ b/infra/stacks/opensearch/helpers/scripts/create_chats_v2.ts
@@ -0,0 +1,81 @@
+/**
+ * Creates `chats_v2` with the parent/child join mapping used for the
+ * multi-term AND search migration. Does NOT touch the `chats` alias —
+ * `chats_v2` is created idle so the search_processing_service backfill
+ * can populate it (with `index_override: "chats_v2"`) while production
+ * reads/writes continue to flow through `chats` -> `chats_v1`.
+ *
+ * Swap the alias separately, once backfill is caught up and the new search
+ * query path is deployed.
+ *
+ * Usage:
+ * bun scripts/create_chats_v2.ts
+ *
+ * Idempotent — safe to re-run; if `chats_v2` already exists nothing
+ * happens.
+ */
+require('dotenv').config();
+
+import { client } from '../client';
+import { SHARD_SETTINGS } from '../constants';
+
+const INDEX = 'chats_v2';
+const RELATION_PARENT = 'chat';
+const RELATION_CHILD = 'message';
+
+const BODY = {
+ settings: {
+ ...SHARD_SETTINGS,
+ refresh_interval: '1s',
+ },
+ mappings: {
+ dynamic: 'false',
+ properties: {
+ entity_id: { type: 'keyword' },
+ // Parent-only metadata
+ title: {
+ type: 'text',
+ fields: { keyword: { type: 'keyword', ignore_above: 50 } },
+ },
+ user_id: { type: 'keyword', index: true, doc_values: true },
+ updated_at_seconds: {
+ type: 'date',
+ format: 'epoch_second',
+ index: false,
+ doc_values: true,
+ },
+ // Child-only fields
+ chat_message_id: { type: 'keyword', index: false, doc_values: true },
+ content: { type: 'text', analyzer: 'standard' },
+ role: { type: 'keyword', index: false, doc_values: true },
+ created_at_seconds: {
+ type: 'date',
+ format: 'epoch_second',
+ index: false,
+ doc_values: true,
+ },
+ // Join relationship
+ chat_relation: {
+ type: 'join',
+ relations: { [RELATION_PARENT]: RELATION_CHILD },
+ },
+ },
+ },
+};
+
+async function run() {
+ const c = client();
+ const exists = (await c.indices.exists({ index: INDEX })).body;
+ if (exists) {
+ console.log(`${INDEX} already exists; nothing to do.`);
+ return;
+ }
+ console.log(`Creating ${INDEX} (no alias)`);
+ await c.indices.create({ index: INDEX, body: BODY });
+ console.log(`${INDEX} created`);
+}
+
+run().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/infra/stacks/search-processing-service/index.ts b/infra/stacks/search-processing-service/index.ts
index 5efbdad746..5f7fccd8b0 100644
--- a/infra/stacks/search-processing-service/index.ts
+++ b/infra/stacks/search-processing-service/index.ts
@@ -150,6 +150,12 @@ const searchProcessingService = new SearchProcessingService(
name: 'DOCUMENTS_INDEX_USES_JOIN',
value: config.get('documents_index_uses_join') ?? 'false',
},
+ {
+ // Same as DOCUMENTS_INDEX_USES_JOIN, but for the chats alias
+ // (`chats_v1` flat -> `chats_v2` parent/child).
+ name: 'CHATS_INDEX_USES_JOIN',
+ value: config.get('chats_index_uses_join') ?? 'false',
+ },
{
name: 'DOCUMENT_STORAGE_BUCKET',
value: pulumi.interpolate`${documentStorageBucketId}`,
diff --git a/rust/cloud-storage/.sqlx/query-7c07eebbc4d89f86a5d9c04bcecaddeb7090d3d74ad131b9c9621373c9ccb971.json b/rust/cloud-storage/.sqlx/query-36a0d1e85cdabcc03083ebedd508372d7c83b2ffe1f393c77ceae79ba7a24199.json
similarity index 50%
rename from rust/cloud-storage/.sqlx/query-7c07eebbc4d89f86a5d9c04bcecaddeb7090d3d74ad131b9c9621373c9ccb971.json
rename to rust/cloud-storage/.sqlx/query-36a0d1e85cdabcc03083ebedd508372d7c83b2ffe1f393c77ceae79ba7a24199.json
index 4e2ac7e828..4f258d00ae 100644
--- a/rust/cloud-storage/.sqlx/query-7c07eebbc4d89f86a5d9c04bcecaddeb7090d3d74ad131b9c9621373c9ccb971.json
+++ b/rust/cloud-storage/.sqlx/query-36a0d1e85cdabcc03083ebedd508372d7c83b2ffe1f393c77ceae79ba7a24199.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 $3::bool IS NULL\n OR ($3 AND c.\"deletedAt\" IS NOT NULL)\n OR (NOT $3 AND 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 m.\"createdAt\" as \"created_at\",\n m.\"updatedAt\" as \"updated_at\"\n FROM\n \"ChatMessage\" m\n JOIN\n \"Chat\" c on c.\"id\" = m.\"chatId\"\n WHERE\n (\n $2::bool IS NULL\n OR ($2 AND c.\"deletedAt\" IS NOT NULL)\n OR (NOT $2 AND c.\"deletedAt\" IS NULL)\n )\n AND ($3::timestamptz IS NULL OR m.\"updatedAt\" >= $3)\n AND ($4::timestamptz IS NULL OR m.\"updatedAt\" < $4)\n AND (\n $5::timestamptz IS NULL\n OR (m.\"updatedAt\", m.id) > ($5, $6::text)\n )\n ORDER BY m.\"updatedAt\" ASC, m.id ASC\n LIMIT $1\n ",
"describe": {
"columns": [
{
@@ -32,8 +32,11 @@
"parameters": {
"Left": [
"Int8",
- "Int8",
- "Bool"
+ "Bool",
+ "Timestamptz",
+ "Timestamptz",
+ "Timestamptz",
+ "Text"
]
},
"nullable": [
@@ -44,5 +47,5 @@
false
]
},
- "hash": "7c07eebbc4d89f86a5d9c04bcecaddeb7090d3d74ad131b9c9621373c9ccb971"
+ "hash": "36a0d1e85cdabcc03083ebedd508372d7c83b2ffe1f393c77ceae79ba7a24199"
}
diff --git a/rust/cloud-storage/.sqlx/query-14291546e09d0832632e223b7472be044d62d501a10564bc46a13e408415fe5b.json b/rust/cloud-storage/.sqlx/query-5929a15919ba9b705c47c77ccc0ac1d7893590a8513c5d2019793598704f64fb.json
similarity index 53%
rename from rust/cloud-storage/.sqlx/query-14291546e09d0832632e223b7472be044d62d501a10564bc46a13e408415fe5b.json
rename to rust/cloud-storage/.sqlx/query-5929a15919ba9b705c47c77ccc0ac1d7893590a8513c5d2019793598704f64fb.json
index 36f32f38a6..7d59021fcd 100644
--- a/rust/cloud-storage/.sqlx/query-14291546e09d0832632e223b7472be044d62d501a10564bc46a13e408415fe5b.json
+++ b/rust/cloud-storage/.sqlx/query-5929a15919ba9b705c47c77ccc0ac1d7893590a8513c5d2019793598704f64fb.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)\n AND (\n $4::bool IS NULL\n OR ($4 AND c.\"deletedAt\" IS NOT NULL)\n OR (NOT $4 AND c.\"deletedAt\" IS NULL)\n )\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 m.\"createdAt\" as \"created_at\",\n m.\"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 AND (\n $3::bool IS NULL\n OR ($3 AND c.\"deletedAt\" IS NOT NULL)\n OR (NOT $3 AND c.\"deletedAt\" IS NULL)\n )\n AND ($4::timestamptz IS NULL OR m.\"updatedAt\" >= $4)\n AND ($5::timestamptz IS NULL OR m.\"updatedAt\" < $5)\n AND (\n $6::timestamptz IS NULL\n OR (m.\"updatedAt\", m.id) > ($6, $7::text)\n )\n ORDER BY m.\"updatedAt\" ASC, m.id ASC\n LIMIT $2\n ",
"describe": {
"columns": [
{
@@ -33,8 +33,11 @@
"Left": [
"TextArray",
"Int8",
- "Int8",
- "Bool"
+ "Bool",
+ "Timestamptz",
+ "Timestamptz",
+ "Timestamptz",
+ "Text"
]
},
"nullable": [
@@ -45,5 +48,5 @@
false
]
},
- "hash": "14291546e09d0832632e223b7472be044d62d501a10564bc46a13e408415fe5b"
+ "hash": "5929a15919ba9b705c47c77ccc0ac1d7893590a8513c5d2019793598704f64fb"
}
diff --git a/rust/cloud-storage/.sqlx/query-33d8d28ce312d4a08adb044b24dfb86936cbb07a9021854308a919bc6e363ec8.json b/rust/cloud-storage/.sqlx/query-cfc7c8a549dffd94c8d201c665e84c110d780e5be92b5e160c64189355f5f31f.json
similarity index 53%
rename from rust/cloud-storage/.sqlx/query-33d8d28ce312d4a08adb044b24dfb86936cbb07a9021854308a919bc6e363ec8.json
rename to rust/cloud-storage/.sqlx/query-cfc7c8a549dffd94c8d201c665e84c110d780e5be92b5e160c64189355f5f31f.json
index 5efac54453..1419957cba 100644
--- a/rust/cloud-storage/.sqlx/query-33d8d28ce312d4a08adb044b24dfb86936cbb07a9021854308a919bc6e363ec8.json
+++ b/rust/cloud-storage/.sqlx/query-cfc7c8a549dffd94c8d201c665e84c110d780e5be92b5e160c64189355f5f31f.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)\n AND (\n $4::bool IS NULL\n OR ($4 AND c.\"deletedAt\" IS NOT NULL)\n OR (NOT $4 AND c.\"deletedAt\" IS NULL)\n )\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 m.\"createdAt\" as \"created_at\",\n m.\"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 AND (\n $3::bool IS NULL\n OR ($3 AND c.\"deletedAt\" IS NOT NULL)\n OR (NOT $3 AND c.\"deletedAt\" IS NULL)\n )\n AND ($4::timestamptz IS NULL OR m.\"updatedAt\" >= $4)\n AND ($5::timestamptz IS NULL OR m.\"updatedAt\" < $5)\n AND (\n $6::timestamptz IS NULL\n OR (m.\"updatedAt\", m.id) > ($6, $7::text)\n )\n ORDER BY m.\"updatedAt\" ASC, m.id ASC\n LIMIT $2\n ",
"describe": {
"columns": [
{
@@ -33,8 +33,11 @@
"Left": [
"TextArray",
"Int8",
- "Int8",
- "Bool"
+ "Bool",
+ "Timestamptz",
+ "Timestamptz",
+ "Timestamptz",
+ "Text"
]
},
"nullable": [
@@ -45,5 +48,5 @@
false
]
},
- "hash": "33d8d28ce312d4a08adb044b24dfb86936cbb07a9021854308a919bc6e363ec8"
+ "hash": "cfc7c8a549dffd94c8d201c665e84c110d780e5be92b5e160c64189355f5f31f"
}
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260522130000_chat_message_updated_at_id_keyset_index.sql b/rust/cloud-storage/macro_db_client/migrations/20260522130000_chat_message_updated_at_id_keyset_index.sql
new file mode 100644
index 0000000000..1bd64f796d
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260522130000_chat_message_updated_at_id_keyset_index.sql
@@ -0,0 +1,5 @@
+-- no-transaction
+-- Supports keyset pagination over ChatMessage for the search backfill
+-- orchestrator, which sorts by ("updatedAt" ASC, id ASC).
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_chat_message_updated_at_id
+ ON "ChatMessage" ("updatedAt", id);
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 59dd5ab3bc..37682279ef 100644
--- a/rust/cloud-storage/macro_db_client/src/chat/get.rs
+++ b/rust/cloud-storage/macro_db_client/src/chat/get.rs
@@ -15,14 +15,23 @@ pub struct ChatSearchBackfill {
pub updated_at: DateTime<Utc>,
}
-/// Gets the chat messages for search backfill
+/// Gets the chat messages for search backfill.
+///
+/// Pagination is **keyset (seek-method)**: pass `cursor` as the last
+/// row's `(updated_at, message_id)` pair from the previous page (or
+/// `None` for the first page). Sorting and filtering use `updatedAt`
+/// rather than `createdAt` so incremental backfills (e.g. "anything
+/// changed since X") catch messages that were edited after the cutoff.
+#[allow(clippy::too_many_arguments)]
#[tracing::instrument(skip(db))]
pub async fn get_chat_messages_for_search_backfill(
db: &sqlx::Pool<sqlx::Postgres>,
limit: i64,
- offset: i64,
+ cursor: Option<(DateTime<Utc>, String)>,
chat_ids: Option<&Vec<String>>,
user_ids: Option<&Vec<String>>,
+ updated_after: Option<DateTime<Utc>>,
+ updated_before: Option<DateTime<Utc>>,
only_deleted: Option<bool>,
) -> anyhow::Result<Vec<ChatSearchBackfill>> {
if let Some(chat_ids) = chat_ids {
@@ -33,8 +42,10 @@ pub async fn get_chat_messages_for_search_backfill(
return get_chat_messages_for_search_backfill_chat_ids(
db,
limit,
- offset,
+ cursor,
chat_ids,
+ updated_after,
+ updated_before,
only_deleted,
)
.await;
@@ -48,37 +59,53 @@ pub async fn get_chat_messages_for_search_backfill(
return get_chat_messages_for_search_backfill_user_ids(
db,
limit,
- offset,
+ cursor,
user_ids,
+ updated_after,
+ updated_before,
only_deleted,
)
.await;
}
+ let (cursor_updated_at, cursor_id) = match cursor {
+ Some((t, id)) => (Some(t), Some(id)),
+ None => (None, None),
+ };
+
let result = sqlx::query!(
r#"
SELECT
c."id" as "chat_id",
m.id as "message_id",
c."userId" as "user_id",
- c."createdAt" as "created_at",
- c."updatedAt" as "updated_at"
+ m."createdAt" as "created_at",
+ m."updatedAt" as "updated_at"
FROM
"ChatMessage" m
JOIN
"Chat" c on c."id" = m."chatId"
WHERE
- $3::bool IS NULL
- OR ($3 AND c."deletedAt" IS NOT NULL)
- OR (NOT $3 AND c."deletedAt" IS NULL)
- ORDER BY
- m."createdAt" DESC
+ (
+ $2::bool IS NULL
+ OR ($2 AND c."deletedAt" IS NOT NULL)
+ OR (NOT $2 AND c."deletedAt" IS NULL)
+ )
+ AND ($3::timestamptz IS NULL OR m."updatedAt" >= $3)
+ AND ($4::timestamptz IS NULL OR m."updatedAt" < $4)
+ AND (
+ $5::timestamptz IS NULL
+ OR (m."updatedAt", m.id) > ($5, $6::text)
+ )
+ ORDER BY m."updatedAt" ASC, m.id ASC
LIMIT $1
- OFFSET $2
"#,
limit,
- offset,
- only_deleted,
+ only_deleted as Option<bool>,
+ updated_after as Option<DateTime<Utc>>,
+ updated_before as Option<DateTime<Utc>>,
+ cursor_updated_at as Option<DateTime<Utc>>,
+ cursor_id as Option<String>,
)
.map(|row| ChatSearchBackfill {
chat_id: row.chat_id,
@@ -94,21 +121,29 @@ pub async fn get_chat_messages_for_search_backfill(
}
/// Gets the chat messages for search backfill for specific chat ids
+#[allow(clippy::too_many_arguments)]
async fn get_chat_messages_for_search_backfill_chat_ids(
db: &sqlx::Pool<sqlx::Postgres>,
limit: i64,
- offset: i64,
+ cursor: Option<(DateTime<Utc>, String)>,
chat_ids: &[String],
+ updated_after: Option<DateTime<Utc>>,
+ updated_before: Option<DateTime<Utc>>,
only_deleted: Option<bool>,
) -> anyhow::Result<Vec<ChatSearchBackfill>> {
+ let (cursor_updated_at, cursor_id) = match cursor {
+ Some((t, id)) => (Some(t), Some(id)),
+ None => (None, None),
+ };
+
let result = sqlx::query!(
r#"
SELECT
c."id" as "chat_id",
m.id as "message_id",
c."userId" as "user_id",
- c."createdAt" as "created_at",
- c."updatedAt" as "updated_at"
+ m."createdAt" as "created_at",
+ m."updatedAt" as "updated_at"
FROM
"ChatMessage" m
JOIN
@@ -116,19 +151,26 @@ async fn get_chat_messages_for_search_backfill_chat_ids(
WHERE
m."chatId" = ANY($1)
AND (
- $4::bool IS NULL
- OR ($4 AND c."deletedAt" IS NOT NULL)
- OR (NOT $4 AND c."deletedAt" IS NULL)
+ $3::bool IS NULL
+ OR ($3 AND c."deletedAt" IS NOT NULL)
+ OR (NOT $3 AND c."deletedAt" IS NULL)
)
- ORDER BY
- m."createdAt" DESC
+ AND ($4::timestamptz IS NULL OR m."updatedAt" >= $4)
+ AND ($5::timestamptz IS NULL OR m."updatedAt" < $5)
+ AND (
+ $6::timestamptz IS NULL
+ OR (m."updatedAt", m.id) > ($6, $7::text)
+ )
+ ORDER BY m."updatedAt" ASC, m.id ASC
LIMIT $2
- OFFSET $3
"#,
chat_ids,
limit,
- offset,
- only_deleted,
+ only_deleted as Option<bool>,
+ updated_after as Option<DateTime<Utc>>,
+ updated_before as Option<DateTime<Utc>>,
+ cursor_updated_at as Option<DateTime<Utc>>,
+ cursor_id as Option<String>,
)
.map(|row| ChatSearchBackfill {
chat_id: row.chat_id,
@@ -144,21 +186,29 @@ async fn get_chat_messages_for_search_backfill_chat_ids(
}
/// Gets the chat messages for search backfill for specific user ids
+#[allow(clippy::too_many_arguments)]
async fn get_chat_messages_for_search_backfill_user_ids(
db: &sqlx::Pool<sqlx::Postgres>,
limit: i64,
- offset: i64,
+ cursor: Option<(DateTime<Utc>, String)>,
user_ids: &[String],
+ updated_after: Option<DateTime<Utc>>,
+ updated_before: Option<DateTime<Utc>>,
only_deleted: Option<bool>,
) -> anyhow::Result<Vec<ChatSearchBackfill>> {
+ let (cursor_updated_at, cursor_id) = match cursor {
+ Some((t, id)) => (Some(t), Some(id)),
+ None => (None, None),
+ };
+
let result = sqlx::query!(
r#"
SELECT
c."id" as "chat_id",
m.id as "message_id",
c."userId" as "user_id",
- c."createdAt" as "created_at",
- c."updatedAt" as "updated_at"
+ m."createdAt" as "created_at",
+ m."updatedAt" as "updated_at"
FROM
"ChatMessage" m
JOIN
@@ -166,19 +216,26 @@ async fn get_chat_messages_for_search_backfill_user_ids(
WHERE
c."userId" = ANY($1)
AND (
- $4::bool IS NULL
- OR ($4 AND c."deletedAt" IS NOT NULL)
- OR (NOT $4 AND c."deletedAt" IS NULL)
+ $3::bool IS NULL
+ OR ($3 AND c."deletedAt" IS NOT NULL)
+ OR (NOT $3 AND c."deletedAt" IS NULL)
)
- ORDER BY
- m."createdAt" DESC
+ AND ($4::timestamptz IS NULL OR m."updatedAt" >= $4)
+ AND ($5::timestamptz IS NULL OR m."updatedAt" < $5)
+ AND (
+ $6::timestamptz IS NULL
+ OR (m."updatedAt", m.id) > ($6, $7::text)
+ )
+ ORDER BY m."updatedAt" ASC, m.id ASC
LIMIT $2
- OFFSET $3
"#,
user_ids,
limit,
- offset,
- only_deleted,
+ only_deleted as Option<bool>,
+ updated_after as Option<DateTime<Utc>>,
+ updated_before as Option<DateTime<Utc>>,
+ cursor_updated_at as Option<DateTime<Utc>>,
+ cursor_id as Option<String>,
)
.map(|row| ChatSearchBackfill {
chat_id: row.chat_id,
diff --git a/rust/cloud-storage/opensearch_client/src/chats_shape.rs b/rust/cloud-storage/opensearch_client/src/chats_shape.rs
new file mode 100644
index 0000000000..892021d498
--- /dev/null
+++ b/rust/cloud-storage/opensearch_client/src/chats_shape.rs
@@ -0,0 +1,70 @@
+//! Dispatch helpers for the chats index migration from a flat
+//! one-doc-per-message shape to a parent/child join shape.
+//!
+//! Three dispatch points, mirroring [`crate::documents_shape`]:
+//!
+//! * `destination_uses_join_shape(dest)` — used by writers that take an
+//! explicit `index_override`. Returns `true` when the override names
+//! the join-shape physical index so the backfill can target it in
+//! join-shape mode while normal traffic continues writing flat docs
+//! through the alias.
+//!
+//! * `alias_uses_join_shape()` — used by callers that always target the
+//! `chats` alias (search reads, user-id deletes, title updates).
+//! Driven by the `CHATS_INDEX_USES_JOIN` env var so we can flip the
+//! alias contract atomically with the alias swap without per-call
+//! introspection.
+//!
+//! * `chats_search_alias()` — the alias name search reads target.
+//! Defaults to `chats`. The `CHATS_INDEX_NAME` env var overrides
+//! this so local end-to-end tests can read from a side alias pointing
+//! only at the join-shape index, without disturbing the shared
+//! `chats` alias on dev/prod.
+
+use std::sync::OnceLock;
+
+/// Physical name of the join-shape chats index. Used as the
+/// `index_override` value for backfills that should write in the join
+/// shape and as the trigger for `destination_uses_join_shape`.
+pub const CHATS_V2: &str = "chats_v2";
+
+/// Default alias name reads target. Production code always uses this.
+const DEFAULT_CHATS_ALIAS: &str = "chats";
+
+/// Whether writes targeting this destination should use the parent/child
+/// join shape.
+pub fn destination_uses_join_shape(destination: &str) -> bool {
+ if destination == CHATS_V2 {
+ return true;
+ }
+ if destination == DEFAULT_CHATS_ALIAS {
+ return alias_uses_join_shape();
+ }
+ false
+}
+
+/// Whether the `chats` alias currently resolves to a join-shape index.
+///
+/// Controlled by the `CHATS_INDEX_USES_JOIN` env var, cached once per
+/// process. Operators set it `true` at the alias swap; before then it
+/// defaults to `false` so the existing flat-shape paths stay active.
+pub fn alias_uses_join_shape() -> bool {
+ static ALIAS_USES_JOIN: OnceLock<bool> = OnceLock::new();
+ *ALIAS_USES_JOIN.get_or_init(|| {
+ std::env::var("CHATS_INDEX_USES_JOIN")
+ .map(|v| v == "true")
+ .unwrap_or(false)
+ })
+}
+
+/// Alias name that search reads target for chats. Returns `chats` by
+/// default; the `CHATS_INDEX_NAME` env var overrides this so local
+/// tests can point at a side alias pointing only at the join-shape
+/// index without disturbing the shared `chats` alias.
+pub fn chats_search_alias() -> &'static str {
+ static NAME: OnceLock<&'static str> = OnceLock::new();
+ NAME.get_or_init(|| match std::env::var("CHATS_INDEX_NAME") {
+ Ok(s) if !s.is_empty() => Box::leak(s.into_boxed_str()) as &'static str,
+ _ => DEFAULT_CHATS_ALIAS,
+ })
+}
diff --git a/rust/cloud-storage/opensearch_client/src/lib.rs b/rust/cloud-storage/opensearch_client/src/lib.rs
index 1bb018ee9f..18928d8ea7 100644
--- a/rust/cloud-storage/opensearch_client/src/lib.rs
+++ b/rust/cloud-storage/opensearch_client/src/lib.rs
@@ -1,3 +1,4 @@
+pub mod chats_shape;
pub mod date_format;
pub mod delete;
pub mod documents_shape;
diff --git a/rust/cloud-storage/opensearch_client/src/search/chats.rs b/rust/cloud-storage/opensearch_client/src/search/chats.rs
index 3b4954c8e7..c9334ce8c3 100644
--- a/rust/cloud-storage/opensearch_client/src/search/chats.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/chats.rs
@@ -1,20 +1,54 @@
+use std::collections::HashMap;
+
use crate::{
- Result, delegate_methods,
+ Result,
+ chats_shape::{alias_uses_join_shape, chats_search_alias},
+ delegate_methods,
search::{
builder::{SearchQueryBuilder, SearchQueryConfig},
+ model::{Highlight, SearchGotoChat, SearchGotoContent, SearchHit, parse_highlight_hit},
+ query::Keys,
utils::should_wildcard_field_query_builder,
},
};
-use models_opensearch::OpenSearchEntityType;
-use opensearch_query_builder::BoolQueryBuilder;
+use chrono::{DateTime, Utc};
+use models_opensearch::{OpenSearchEntityType, SearchEntityType};
+use opensearch_query_builder::{
+ BoolQueryBuilder, HasChildQuery, InnerHits, MatchPhrasePrefixQuery, MatchPhraseQuery,
+ QueryType, ToOpenSearchJson,
+};
+
+/// Relation names for the join field. Kept in sync with the upsert path
+/// in `upsert::chat_message`.
+const PARENT_RELATION: &str = "chat";
+const CHILD_RELATION: &str = "message";
+
+/// Minimum prefix length before we emit a `match_phrase_prefix`. Mirrors
+/// the documents threshold — shorter prefixes risk hitting
+/// `max_clause_count` on expansion.
+const MIN_PREFIX_LEN: usize = 3;
+
+/// Cap on messages returned per `has_child` clause inside `inner_hits`.
+/// OpenSearch's default is 3 which would silently drop matches on chats
+/// with many hits.
+const INNER_HITS_PER_TERM: u32 = 100;
+
+/// Cap on terms a `match_phrase_prefix` may expand the last word to.
+const MATCH_PHRASE_PREFIX_MAX_EXPANSIONS: u32 = 256;
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct ChatIndex {
pub entity_id: uuid::Uuid,
- pub chat_message_id: uuid::Uuid,
+ /// Present on flat-shape (legacy) message docs. Absent on join-shape
+ /// parent docs — those carry chat-level metadata only and the
+ /// matching message ids come via `inner_hits`.
+ #[serde(default)]
+ pub chat_message_id: Option<uuid::Uuid>,
pub user_id: String,
- pub role: String,
+ /// Present on flat-shape message docs. Absent on join-shape parents.
+ #[serde(default)]
+ pub role: Option<String>,
pub title: String,
pub updated_at_seconds: Option<i64>,
}
@@ -58,18 +92,152 @@ impl ChatQueryBuilder {
}
pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
+ if alias_uses_join_shape() {
+ return self.build_bool_query_join();
+ }
+ self.build_bool_query_flat()
+ }
+
+ /// Flat one-doc-per-message path: the whole user query is a single
+ /// phrase match on `content` and metadata filters sit on the same
+ /// doc as the content.
+ fn build_bool_query_flat<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
let mut content_bool_query = self.inner.build_content_bool_query()?;
- // CUSTOM ATTRIBUTES SECTION
- // Add role to must clause if provided
if !self.role.is_empty() {
let should_query = should_wildcard_field_query_builder("role", &self.role);
content_bool_query.filter(should_query);
}
- // END CUSTOM ATTRIBUTES SECTION
Ok(content_bool_query)
}
+
+ /// Parent/child join path: one `has_child` clause per term, ANDed
+ /// inside `bool.must` so each term must match some message in the
+ /// same chat. Parent metadata filters (user, ids) sit on
+ /// `bool.filter` because they live on the parent doc.
+ fn build_bool_query_join<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
+ if self.inner.ids_only && self.inner.ids.is_empty() {
+ return Err(crate::error::OpensearchClientError::EmptyIdsWithIdsOnly(
+ ChatSearchConfig::ENTITY_INDEX,
+ ));
+ }
+ if self.inner.terms.is_empty() {
+ return Err(crate::error::OpensearchClientError::NoTermsProvided);
+ }
+
+ let mut bool_query = BoolQueryBuilder::new();
+
+ // Restrict to parent chats in the chats alias (overridable via
+ // CHATS_INDEX_NAME for local end-to-end testing against a side
+ // alias).
+ bool_query.filter(QueryType::term("_index", chats_search_alias().to_string()));
+ bool_query.filter(QueryType::term(
+ "chat_relation",
+ PARENT_RELATION.to_string(),
+ ));
+
+ // Access control on parent fields (user_id and/or entity_id).
+ bool_query.filter(self.build_parent_filter()?);
+
+ // Role is a child-side field, so it has to live inside a
+ // `has_child` clause rather than on the outer bool. Use a
+ // dedicated clause that doesn't carry inner_hits — the
+ // term-clauses below handle highlights.
+ if !self.role.is_empty() {
+ let role_query = should_wildcard_field_query_builder("role", &self.role);
+ let role_has_child = HasChildQuery::new(CHILD_RELATION, role_query);
+ bool_query.filter(role_has_child.into());
+ }
+
+ // One has_child clause per term, ANDed via bool.must. Each
+ // carries its own inner_hits so highlights + message-nav data
+ // come back alongside the parent. Shared `highlight_query`
+ // tags every search term on a returned message regardless of
+ // which has_child clause produced it.
+ let highlight_query =
+ build_all_terms_highlight_query(&self.inner.terms, &self.inner.match_type);
+ for (idx, term) in self.inner.terms.iter().enumerate() {
+ let inner_query = build_child_content_query(term, &self.inner.match_type);
+ let inner_hits = InnerHits::new()
+ .name(format!("term_{idx}"))
+ .size(INNER_HITS_PER_TERM)
+ .highlight(inner_hits_content_highlight(&highlight_query));
+ let has_child = HasChildQuery::new(CHILD_RELATION, inner_query).inner_hits(inner_hits);
+ bool_query.must(has_child.into());
+ }
+
+ Ok(bool_query)
+ }
+
+ fn build_parent_filter<'a>(&'a self) -> Result<QueryType<'a>> {
+ let user_key = ChatSearchConfig::USER_ID_KEY.expect("chats config has user_id key");
+
+ if self.inner.ids_only {
+ return Ok(QueryType::terms("entity_id", self.inner.ids.clone()));
+ }
+ let user_query = QueryType::term(user_key.to_string(), self.inner.user_id.clone());
+ if self.inner.ids.is_empty() {
+ return Ok(user_query);
+ }
+ let mut filter = BoolQueryBuilder::new();
+ filter.minimum_should_match(1);
+ filter.should(QueryType::terms("entity_id", self.inner.ids.clone()));
+ filter.should(user_query);
+ Ok(filter.build().into())
+ }
+}
+
+/// Highlight config attached to each `has_child` inner_hits block.
+fn inner_hits_content_highlight(highlight_query: &serde_json::Value) -> serde_json::Value {
+ serde_json::json!({
+ "require_field_match": true,
+ "pre_tags": ["<macro_em>"],
+ "post_tags": ["</macro_em>"],
+ "fields": {
+ "content": {
+ "type": "plain",
+ "number_of_fragments": 1,
+ "fragment_size": 1000,
+ "highlight_query": highlight_query,
+ }
+ }
+ })
+}
+
+/// Combined OR-of-all-terms query used as the inner_hits highlight_query.
+fn build_all_terms_highlight_query(terms: &[String], match_type: &str) -> serde_json::Value {
+ let term_queries: Vec<serde_json::Value> = terms
+ .iter()
+ .map(|t| build_child_content_query(t, match_type).to_json())
+ .collect();
+ if term_queries.len() == 1 {
+ return term_queries.into_iter().next().unwrap();
+ }
+ serde_json::json!({
+ "bool": {
+ "should": term_queries,
+ "minimum_should_match": 1,
+ }
+ })
+}
+
+/// Build the per-term query that runs inside `has_child` against `content`.
+fn build_child_content_query<'a>(term: &str, match_type: &str) -> QueryType<'a> {
+ let exact = match_type == "exact"
+ || term.chars().any(|c| c.is_whitespace())
+ || term.chars().count() < MIN_PREFIX_LEN;
+ if exact {
+ QueryType::MatchPhrase(MatchPhraseQuery::new(
+ "content".to_string(),
+ term.to_string(),
+ ))
+ } else {
+ QueryType::MatchPhrasePrefix(
+ MatchPhrasePrefixQuery::new("content".to_string(), term.to_string())
+ .max_expansions(MATCH_PHRASE_PREFIX_MAX_EXPANSIONS),
+ )
+ }
}
#[derive(Debug)]
@@ -99,5 +267,92 @@ impl From<ChatSearchArgs> for ChatQueryBuilder {
}
}
+// ---------------------------------------------------------------------------
+// inner_hits → message-level SearchHits
+// ---------------------------------------------------------------------------
+
+#[derive(Debug, serde::Deserialize)]
+struct MessageInnerHit {
+ #[serde(rename = "_id")]
+ id: String,
+ #[serde(rename = "_score")]
+ score: Option<f64>,
+ #[serde(rename = "_source")]
+ source: MessageSource,
+ #[serde(default)]
+ highlight: Option<HashMap<String, Vec<String>>>,
+}
+
+#[derive(Debug, serde::Deserialize)]
+struct MessageSource {
+ chat_message_id: uuid::Uuid,
+ #[serde(default)]
+ role: Option<String>,
+}
+
+#[derive(Debug, serde::Deserialize)]
+struct InnerHitsGroup {
+ #[serde(default)]
+ hits: InnerHitsList,
+}
+
+#[derive(Debug, Default, serde::Deserialize)]
+struct InnerHitsList {
+ #[serde(default)]
+ hits: Vec<MessageInnerHit>,
+}
+
+/// Walk the `inner_hits` block from a join-shape parent hit and emit
+/// one `SearchHit` per matching child message, carrying that message's
+/// `chat_message_id`, `role`, score, and highlight.
+///
+/// A message matched by multiple `has_child` clauses (multi-term
+/// queries) appears once per term in the response; we dedup by message
+/// `_id` so a single message maps to a single `SearchHit` downstream.
+pub(crate) fn expand_inner_hits_to_search_hits(
+ entity_id: uuid::Uuid,
+ updated_at: Option<DateTime<Utc>>,
+ inner_hits: &serde_json::Value,
+) -> Vec<SearchHit> {
+ let groups: HashMap<String, InnerHitsGroup> = match serde_json::from_value(inner_hits.clone()) {
+ Ok(g) => g,
+ Err(_) => return Vec::new(),
+ };
+
+ let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
+ let mut out: Vec<SearchHit> = Vec::new();
+ for group in groups.into_values() {
+ for msg in group.hits.hits {
+ if !seen.insert(msg.id) {
+ continue;
+ }
+ let highlight: Highlight = msg
+ .highlight
+ .map(|h| {
+ parse_highlight_hit(
+ h,
+ Keys {
+ title_key: ChatSearchConfig::TITLE_KEY,
+ content_key: ChatSearchConfig::CONTENT_KEY,
+ },
+ )
+ })
+ .unwrap_or_default();
+ out.push(SearchHit {
+ entity_id,
+ entity_type: SearchEntityType::Chats,
+ score: msg.score,
+ highlight,
+ goto: Some(SearchGotoContent::Chats(SearchGotoChat {
+ chat_message_id: msg.source.chat_message_id,
+ role: msg.source.role.unwrap_or_default(),
+ })),
+ updated_at,
+ });
+ }
+ }
+ out
+}
+
#[cfg(test)]
mod test;
diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rs
index 6d2d6b4470..42e5bd6a1f 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs
@@ -282,32 +282,47 @@ where
/// Expand one OpenSearch hit into one or more `SearchHit`s.
///
-/// For the documents join shape, OpenSearch returns one parent hit per
-/// matching document with the matching chunks nested under
-/// `inner_hits`. The documents module knows how to unpack that into
-/// chunk-level hits; everything else (flat indices, non-document hits)
-/// takes the 1:1 conversion.
+/// For join-shape parents (documents, chats), OpenSearch returns one
+/// parent hit per matching root with the matching children nested
+/// under `inner_hits`. Each entity's search module knows how to unpack
+/// those into child-level hits; everything else (flat indices) takes
+/// the 1:1 conversion.
fn expand_hit_into_search_hits(hit: Hit<UnifiedSearchIndex>) -> Vec<SearchHit> {
- let UnifiedSearchIndex::Document(parent) = &hit.source else {
- return vec![hit.into()];
- };
- let Some(inner) = hit.inner_hits.as_ref() else {
- return vec![hit.into()];
- };
-
- let entity_id = parent.entity_id;
- let updated_at = parent
- .updated_at_seconds
- .and_then(|s| DateTime::from_timestamp(s, 0));
-
- let expanded =
- crate::search::documents::expand_inner_hits_to_search_hits(entity_id, updated_at, inner);
- if expanded.is_empty() {
- // Malformed or empty inner_hits — fall back to the parent so
- // the document still surfaces, just without per-chunk drill-down.
- return vec![hit.into()];
+ match &hit.source {
+ UnifiedSearchIndex::Document(parent) => {
+ let Some(inner) = hit.inner_hits.as_ref() else {
+ return vec![hit.into()];
+ };
+ let entity_id = parent.entity_id;
+ let updated_at = parent
+ .updated_at_seconds
+ .and_then(|s| DateTime::from_timestamp(s, 0));
+ let expanded = crate::search::documents::expand_inner_hits_to_search_hits(
+ entity_id, updated_at, inner,
+ );
+ if expanded.is_empty() {
+ return vec![hit.into()];
+ }
+ expanded
+ }
+ UnifiedSearchIndex::Chat(parent) => {
+ let Some(inner) = hit.inner_hits.as_ref() else {
+ return vec![hit.into()];
+ };
+ let entity_id = parent.entity_id;
+ let updated_at = parent
+ .updated_at_seconds
+ .and_then(|s| DateTime::from_timestamp(s, 0));
+ let expanded = crate::search::chats::expand_inner_hits_to_search_hits(
+ entity_id, updated_at, inner,
+ );
+ if expanded.is_empty() {
+ return vec![hit.into()];
+ }
+ expanded
+ }
+ _ => vec![hit.into()],
}
- expanded
}
impl From<Hit<UnifiedSearchIndex>> for SearchHit {
@@ -420,8 +435,13 @@ impl From<Hit<UnifiedSearchIndex>> for SearchHit {
})
.unwrap_or_default(),
goto: Some(SearchGotoContent::Chats(SearchGotoChat {
- chat_message_id: a.chat_message_id,
- role: a.role,
+ // Flat-shape docs always carry chat_message_id +
+ // role; the join-shape parent fallback path can
+ // arrive here only when inner_hits was empty, in
+ // which case we have no message-level identifier
+ // to navigate to.
+ chat_message_id: a.chat_message_id.unwrap_or_default(),
+ role: a.role.unwrap_or_default(),
})),
updated_at: a
.updated_at_seconds
@@ -586,14 +606,15 @@ pub(crate) async fn search_unified(
tracing::trace!("search request {:?}", search_request);
- // Documents reads can be redirected to a side alias via
- // DOCUMENTS_INDEX_NAME for local end-to-end testing; every other
- // entity type keeps its default alias.
+ // Documents and chats reads can be redirected to a side alias via
+ // DOCUMENTS_INDEX_NAME / CHATS_INDEX_NAME for local end-to-end
+ // testing; every other entity type keeps its default alias.
let search_indices: Vec<&str> = args
.search_indices
.iter()
.map(|i| match i {
OpenSearchEntityType::Documents => crate::documents_shape::documents_search_alias(),
+ OpenSearchEntityType::Chats => crate::chats_shape::chats_search_alias(),
other => other.index_name(),
})
.collect();
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 da0c783b39..c0cebaa668 100644
--- a/rust/cloud-storage/opensearch_client/src/upsert/chat_message.rs
+++ b/rust/cloud-storage/opensearch_client/src/upsert/chat_message.rs
@@ -1,6 +1,17 @@
use models_opensearch::SearchIndex;
-use crate::{Result, date_format::EpochSeconds, error::OpensearchClientError};
+use crate::{
+ Result,
+ chats_shape::{alias_uses_join_shape, destination_uses_join_shape},
+ date_format::EpochSeconds,
+ error::OpensearchClientError,
+};
+
+/// Relation name for parent docs in the chats join field.
+const PARENT_RELATION: &str = "chat";
+
+/// Relation name for child (message) docs in the chats join field.
+const CHILD_RELATION: &str = "message";
/// The arguments for upserting a chat message into the opensearch index
#[derive(Debug, serde::Serialize)]
@@ -24,14 +35,35 @@ pub struct UpsertChatMessageArgs {
pub content: String,
}
+/// Resolve `index_override` to the physical/alias name we'll write to.
+fn resolve_destination(index_override: Option<&str>) -> &str {
+ index_override.unwrap_or(SearchIndex::Chats.as_ref())
+}
+
#[tracing::instrument(skip(client))]
pub(crate) async fn upsert_chat_message(
client: &opensearch::OpenSearch,
args: &UpsertChatMessageArgs,
index_override: Option<&str>,
+) -> Result<()> {
+ let destination = resolve_destination(index_override);
+ if destination_uses_join_shape(destination) {
+ upsert_chat_message_join(client, args, destination).await
+ } else {
+ upsert_chat_message_flat(client, args, destination).await
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Flat-shape (legacy) path
+// ---------------------------------------------------------------------------
+
+async fn upsert_chat_message_flat(
+ client: &opensearch::OpenSearch,
+ args: &UpsertChatMessageArgs,
+ index: &str,
) -> Result<()> {
let id = format!("{}:{}", args.chat_id, args.chat_message_id);
- let index = index_override.unwrap_or(SearchIndex::Chats.as_ref());
let response = client
.index(opensearch::IndexParts::IndexId(index, &id))
.body(args)
@@ -45,36 +77,220 @@ pub(crate) async fn upsert_chat_message(
let status_code = response.status_code();
if status_code.is_success() {
tracing::trace!(id=%id, "chat message upserted successfully");
- } else {
- let body =
- response
- .text()
- .await
- .map_err(|err| OpensearchClientError::DeserializationFailed {
- details: err.to_string(),
- method: Some("upsert_chat_message".to_string()),
- })?;
+ return Ok(());
+ }
+
+ let body =
+ response
+ .text()
+ .await
+ .map_err(|err| OpensearchClientError::DeserializationFailed {
+ details: err.to_string(),
+ method: Some("upsert_chat_message".to_string()),
+ })?;
+
+ tracing::error!(
+ status_code=%status_code,
+ body=%body,
+ "error upserting chat message",
+ );
+
+ Err(OpensearchClientError::Unknown {
+ details: body,
+ method: Some("upsert_chat_message".to_string()),
+ })
+}
+
+// ---------------------------------------------------------------------------
+// Join-shape path
+// ---------------------------------------------------------------------------
+
+/// Builds the JSON document body for the parent chat doc.
+fn parent_doc_body(args: &UpsertChatMessageArgs) -> serde_json::Value {
+ serde_json::json!({
+ "entity_id": &args.chat_id,
+ "title": &args.title,
+ "user_id": &args.user_id,
+ "updated_at_seconds": args.updated_at_seconds,
+ "chat_relation": PARENT_RELATION,
+ })
+}
+
+/// Builds the JSON document body for a child (message) doc.
+fn child_doc_body(args: &UpsertChatMessageArgs) -> serde_json::Value {
+ serde_json::json!({
+ "entity_id": &args.chat_message_id,
+ "chat_message_id": &args.chat_message_id,
+ "content": &args.content,
+ "role": &args.role,
+ "created_at_seconds": args.created_at_seconds,
+ "updated_at_seconds": args.updated_at_seconds,
+ "chat_relation": {
+ "name": CHILD_RELATION,
+ "parent": &args.chat_id,
+ },
+ })
+}
+
+/// Writes the parent chat doc and the child message doc, each rooted at
+/// the chat_id via `_routing` so they live on the same shard. Uses
+/// full-overwrite `index` semantics (not `update + doc_as_upsert`) so
+/// stale optional fields can't leak across writes.
+async fn upsert_chat_message_join(
+ client: &opensearch::OpenSearch,
+ args: &UpsertChatMessageArgs,
+ index: &str,
+) -> Result<()> {
+ let routing = args.chat_id.as_str();
+
+ let parent_body = parent_doc_body(args);
+ let parent_response = client
+ .index(opensearch::IndexParts::IndexId(index, &args.chat_id))
+ .routing(routing)
+ .body(parent_body)
+ .send()
+ .await
+ .map_err(|err| OpensearchClientError::DeserializationFailed {
+ details: err.to_string(),
+ method: Some("upsert_chat_message_join_parent".to_string()),
+ })?;
+ if !parent_response.status_code().is_success() {
+ let status_code = parent_response.status_code();
+ let body = parent_response.text().await.map_err(|err| {
+ OpensearchClientError::DeserializationFailed {
+ details: err.to_string(),
+ method: Some("upsert_chat_message_join_parent".to_string()),
+ }
+ })?;
tracing::error!(
status_code=%status_code,
body=%body,
- "error upserting chat message",
+ "error upserting chat parent doc",
);
-
return Err(OpensearchClientError::Unknown {
details: body,
- method: Some("upsert_chat_message".to_string()),
+ method: Some("upsert_chat_message_join_parent".to_string()),
});
}
- Ok(())
+
+ let child_id = format!("{}:{}", args.chat_id, args.chat_message_id);
+ let child_body = child_doc_body(args);
+ let child_response = client
+ .index(opensearch::IndexParts::IndexId(index, &child_id))
+ .routing(routing)
+ .body(child_body)
+ .send()
+ .await
+ .map_err(|err| OpensearchClientError::DeserializationFailed {
+ details: err.to_string(),
+ method: Some("upsert_chat_message_join_child".to_string()),
+ })?;
+
+ let status_code = child_response.status_code();
+ if status_code.is_success() {
+ tracing::trace!(id=%child_id, "chat message upserted successfully (join)");
+ return Ok(());
+ }
+
+ let body = child_response.text().await.map_err(|err| {
+ OpensearchClientError::DeserializationFailed {
+ details: err.to_string(),
+ method: Some("upsert_chat_message_join_child".to_string()),
+ }
+ })?;
+
+ tracing::error!(
+ status_code=%status_code,
+ body=%body,
+ "error upserting chat message (join)",
+ );
+
+ Err(OpensearchClientError::Unknown {
+ details: body,
+ method: Some("upsert_chat_message_join_child".to_string()),
+ })
}
-/// Updates the chat metadata for all chat messages
+// ---------------------------------------------------------------------------
+// Chat metadata updates
+// ---------------------------------------------------------------------------
+
+/// Updates the chat metadata for all chat messages.
+///
+/// On the join shape, title lives only on the parent doc so this is a
+/// single update by id. On the flat shape, title is denormalized across
+/// every message doc so we update by query.
#[tracing::instrument(skip(client))]
pub(crate) async fn update_chat_metadata(
client: &opensearch::OpenSearch,
chat_id: &str,
title: &str,
+) -> Result<()> {
+ if alias_uses_join_shape() {
+ update_chat_metadata_join(client, chat_id, title).await
+ } else {
+ update_chat_metadata_flat(client, chat_id, title).await
+ }
+}
+
+async fn update_chat_metadata_join(
+ client: &opensearch::OpenSearch,
+ chat_id: &str,
+ title: &str,
+) -> Result<()> {
+ use opensearch::UpdateParts;
+ use serde_json::json;
+
+ let body = json!({ "doc": { "title": title } });
+
+ let response = client
+ .update(UpdateParts::IndexId(SearchIndex::Chats.as_ref(), chat_id))
+ .routing(chat_id)
+ .body(body)
+ .send()
+ .await
+ .map_err(|err| OpensearchClientError::DeserializationFailed {
+ details: err.to_string(),
+ method: Some("update_chat_metadata_join".to_string()),
+ })?;
+
+ let status_code = response.status_code();
+ if status_code.is_success() {
+ tracing::debug!(
+ chat_id=%chat_id,
+ title=%title,
+ "chat metadata updated successfully (join)"
+ );
+ return Ok(());
+ }
+
+ let body =
+ response
+ .text()
+ .await
+ .map_err(|err| OpensearchClientError::DeserializationFailed {
+ details: err.to_string(),
+ method: Some("update_chat_metadata_join".to_string()),
+ })?;
+
+ tracing::error!(
+ status_code=?status_code,
+ body=?body,
+ chat_id=%chat_id,
+ "error updating chat metadata (join)",
+ );
+
+ Err(OpensearchClientError::Unknown {
+ details: body,
+ method: Some("update_chat_metadata_join".to_string()),
+ })
+}
+
+async fn update_chat_metadata_flat(
+ client: &opensearch::OpenSearch,
+ chat_id: &str,
+ title: &str,
) -> Result<()> {
use opensearch::UpdateByQueryParts;
use serde_json::json;
diff --git a/rust/cloud-storage/search_processing_service/src/domain/models.rs b/rust/cloud-storage/search_processing_service/src/domain/models.rs
index 7b1a131894..9c0ade07ab 100644
--- a/rust/cloud-storage/search_processing_service/src/domain/models.rs
+++ b/rust/cloud-storage/search_processing_service/src/domain/models.rs
@@ -69,16 +69,34 @@ pub struct CallBackfillRequest {
/// Chat-message backfill filter. Empty vectors mean "all messages for every
/// chat / every user".
+///
+/// `updated_after` / `updated_before` filter on `updatedAt`, not `createdAt`,
+/// so incremental runs (e.g. "anything changed since X") catch messages that
+/// existed before the cutoff but were edited after it.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct ChatBackfillRequest {
pub chat_ids: Vec<String>,
pub user_ids: Vec<String>,
+ pub updated_after: Option<DateTime<Utc>>,
+ pub updated_before: Option<DateTime<Utc>>,
pub deletion_filter: DeletionFilter,
/// Override the OpenSearch target index for upserts (e.g. blue/green swap).
pub index_override: Option<String>,
}
+/// Keyset (seek-method) pagination cursor for chat backfills.
+///
+/// `get_chat_messages_for_search_backfill` walks `"ChatMessage"` in
+/// `(updatedAt ASC, id ASC)` order; the cursor carries the last row's
+/// pair so the next page resumes with `WHERE (updatedAt, id) > cursor`.
+/// `None` starts at the beginning.
+#[derive(Debug, Clone)]
+pub struct ChatBackfillCursor {
+ pub updated_at: DateTime<Utc>,
+ pub message_id: String,
+}
+
/// Channel-message backfill filter. No scoping knobs yet — reserved so adding
/// one later doesn't break the request shape.
#[derive(Debug, Clone, Default, Deserialize)]
diff --git a/rust/cloud-storage/search_processing_service/src/domain/ports.rs b/rust/cloud-storage/search_processing_service/src/domain/ports.rs
index eadf2ebd38..1c113bea8b 100644
--- a/rust/cloud-storage/search_processing_service/src/domain/ports.rs
+++ b/rust/cloud-storage/search_processing_service/src/domain/ports.rs
@@ -17,8 +17,9 @@ use std::future::Future;
use sqs_client::search::SearchQueueMessage;
use super::models::{
- BackfillError, CallBackfillRequest, ChannelBackfillRequest, ChatBackfillRequest,
- DocumentBackfillCursor, DocumentBackfillRequest, EmailBackfillRequest, SourcePage,
+ BackfillError, CallBackfillRequest, ChannelBackfillRequest, ChatBackfillCursor,
+ ChatBackfillRequest, DocumentBackfillCursor, DocumentBackfillRequest, EmailBackfillRequest,
+ SourcePage,
};
/// Publishes batches of search-event messages.
@@ -44,11 +45,16 @@ pub trait BackfillSource: Send + Sync + 'static {
offset: usize,
) -> impl Future<Output = Result<SourcePage, BackfillError>> + Send;
+ /// Chats paginate by keyset cursor (mirroring documents): each call
+ /// passes the cursor of the last row from the previous page (or
+ /// `None` for the first page), and the implementation returns the
+ /// page plus the cursor to feed back into the next call. An empty
+ /// page signals end-of-source.
fn fetch_chats(
&self,
req: &ChatBackfillRequest,
- offset: usize,
- ) -> impl Future<Output = Result<SourcePage, BackfillError>> + Send;
+ cursor: Option<ChatBackfillCursor>,
+ ) -> impl Future<Output = Result<(SourcePage, Option<ChatBackfillCursor>), BackfillError>> + Send;
fn fetch_channels(
&self,
diff --git a/rust/cloud-storage/search_processing_service/src/domain/service.rs b/rust/cloud-storage/search_processing_service/src/domain/service.rs
index b61ca3a31b..5397e306ab 100644
--- a/rust/cloud-storage/search_processing_service/src/domain/service.rs
+++ b/rust/cloud-storage/search_processing_service/src/domain/service.rs
@@ -177,8 +177,8 @@ where
progress: Arc<JobProgress>,
cancel: CancellationToken,
) -> Result<BackfillReceipt, BackfillError> {
- drain_source(&self.publisher, &progress, &cancel, |offset| {
- self.source.fetch_chats(&req, offset)
+ drain_source_with_cursor(&self.publisher, &progress, &cancel, |cursor| {
+ self.source.fetch_chats(&req, cursor)
})
.await
}
diff --git a/rust/cloud-storage/search_processing_service/src/outbound/source.rs b/rust/cloud-storage/search_processing_service/src/outbound/source.rs
index 437e34e13d..6baa31b25f 100644
--- a/rust/cloud-storage/search_processing_service/src/outbound/source.rs
+++ b/rust/cloud-storage/search_processing_service/src/outbound/source.rs
@@ -9,8 +9,9 @@ use sqs_client::search::{
use crate::config::BackfillPageSizes;
use crate::domain::models::{
- BackfillError, CallBackfillRequest, ChannelBackfillRequest, ChatBackfillRequest,
- DocumentBackfillCursor, DocumentBackfillRequest, EmailBackfillRequest, SourcePage,
+ BackfillError, CallBackfillRequest, ChannelBackfillRequest, ChatBackfillCursor,
+ ChatBackfillRequest, DocumentBackfillCursor, DocumentBackfillRequest, EmailBackfillRequest,
+ SourcePage,
};
use crate::domain::ports::BackfillSource;
@@ -91,22 +92,29 @@ impl BackfillSource for PgBackfillSource {
async fn fetch_chats(
&self,
req: &ChatBackfillRequest,
- offset: usize,
- ) -> Result<SourcePage, BackfillError> {
+ cursor: Option<ChatBackfillCursor>,
+ ) -> Result<(SourcePage, Option<ChatBackfillCursor>), BackfillError> {
let chat_ids = (!req.chat_ids.is_empty()).then_some(&req.chat_ids);
let user_ids = (!req.user_ids.is_empty()).then_some(&req.user_ids);
+ let db_cursor = cursor.map(|c| (c.updated_at, c.message_id));
let batch = macro_db_client::chat::get::get_chat_messages_for_search_backfill(
&self.db,
self.page_sizes.chats as i64,
- offset as i64,
+ db_cursor,
chat_ids,
user_ids,
+ req.updated_after,
+ req.updated_before,
req.deletion_filter.as_only_deleted(),
)
.await
.map_err(BackfillError::Source)?;
+ let next_cursor = batch.last().map(|row| ChatBackfillCursor {
+ updated_at: row.updated_at,
+ message_id: row.message_id.clone(),
+ });
let rows_consumed = batch.len();
let messages: Vec<SearchQueueMessage> = batch
.into_iter()
@@ -122,10 +130,13 @@ impl BackfillSource for PgBackfillSource {
})
.collect();
- Ok(SourcePage {
- messages,
- rows_consumed,
- })
+ Ok((
+ SourcePage {
+ messages,
+ rows_consumed,
+ },
+ next_cursor,
+ ))
}
async fn fetch_channels(
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs
index 424c573327..a1e02b9222 100644
--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs
+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs
@@ -200,18 +200,23 @@ pub(in crate::api::search) async fn perform_unified_search(
// Emails and channels both get whitespace-split terms — emails match
// each term independently across many fields ANDed inside OpenSearch;
// channel messages are single-doc-per-message so each token must
- // appear in the same message via bool.must. Documents get split terms
- // once the alias points at a join-shape index, where each term becomes
- // a separate has_child clause ANDed via bool.must.
+ // appear in the same message via bool.must. Documents and chats get
+ // split terms once their alias points at a join-shape index, where
+ // each term becomes a separate has_child clause ANDed via bool.must.
let document_terms = if opensearch_client::documents_shape::alias_uses_join_shape() {
split_search_terms(&terms)
} else {
terms.clone()
};
+ let chat_terms = if opensearch_client::chats_shape::alias_uses_join_shape() {
+ split_search_terms(&terms)
+ } else {
+ terms.clone()
+ };
let channel_terms = split_search_terms(&terms);
filter_document_response.terms = document_terms;
filter_channel_response.terms = channel_terms;
- filter_chat_response.terms = terms.clone();
+ filter_chat_response.terms = chat_terms;
filter_email_response.terms = email_terms.clone();
filter_call_record_response.terms = terms.clone();