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): index entity properties for task search filtering (#4175)

gbirman2a9b61db9443
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index c95d000f1a..536a7ab475 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -2700,6 +2700,7 @@
"workspace-hack"
],
"models_properties": [
+ "document_sub_type",
"models_properties",
"workspace-hack"
],
@@ -3135,6 +3136,7 @@
"workspace-hack"
],
"properties_db_client": [
+ "document_sub_type",
"macro_uuid",
"models_properties",
"properties_db_client",
@@ -3411,6 +3413,7 @@
"notification",
"opensearch_client",
"opensearch_query_builder",
+ "properties_db_client",
"rate_limit",
"remote_env_var",
"s3_client",
@@ -3921,6 +3924,7 @@
],
"system_properties": [
"cowlike",
+ "document_sub_type",
"macro_user_id",
"macro_uuid",
"models_properties",
diff --git a/infra/stacks/opensearch/helpers/scripts/create_documents_v2.ts b/infra/stacks/opensearch/helpers/scripts/create_documents_v2.ts
deleted file mode 100644
index 5a97db8fcc..0000000000
--- a/infra/stacks/opensearch/helpers/scripts/create_documents_v2.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- * Creates `documents_v2` with the parent/child join mapping used for the
- * multi-term AND search migration. Does NOT touch the `documents` alias —
- * `documents_v2` is created idle so the search_processing_service backfill
- * can populate it (with `index_override: "documents_v2"`) while production
- * reads/writes continue to flow through `documents` -> `documents_v1`.
- *
- * Swap the alias separately, once backfill is caught up and the new search
- * query path is deployed.
- *
- * Usage:
- * bun scripts/create_documents_v2.ts
- *
- * Idempotent — safe to re-run; if `documents_v2` already exists nothing
- * happens.
- */
-require('dotenv').config();
-
-import { client } from '../client';
-import { SHARD_SETTINGS, SLOWLOG_SETTINGS } from '../constants';
-
-const INDEX = 'documents_v2';
-const RELATION_PARENT = 'document';
-const RELATION_CHILD = 'chunk';
-
-const BODY = {
- settings: {
- ...SHARD_SETTINGS,
- ...SLOWLOG_SETTINGS,
- refresh_interval: '1s',
- },
- mappings: {
- dynamic: 'false',
- properties: {
- entity_id: { type: 'keyword' },
- // Parent-only metadata
- document_name: {
- type: 'text',
- fields: { keyword: { type: 'keyword', ignore_above: 128 } },
- },
- owner_id: { type: 'keyword', index: true, doc_values: true },
- file_type: { type: 'keyword', index: false, doc_values: true },
- sub_type: { type: 'keyword', index: true, doc_values: true },
- updated_at_seconds: {
- type: 'date',
- format: 'epoch_second',
- index: false,
- doc_values: true,
- },
- // Child-only fields
- node_id: { type: 'keyword', index: false, doc_values: true },
- content: { type: 'text', analyzer: 'standard' },
- raw_content: { type: 'text' },
- // Join relationship
- document_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/opensearch/helpers/scripts/create_indices.ts b/infra/stacks/opensearch/helpers/scripts/create_indices.ts
index 7c59a1788d..19682c1a54 100644
--- a/infra/stacks/opensearch/helpers/scripts/create_indices.ts
+++ b/infra/stacks/opensearch/helpers/scripts/create_indices.ts
@@ -276,6 +276,18 @@ const DOCUMENT_BODY = {
index: false,
doc_values: true,
},
+ // Parent-only entity properties (status, priority, assignees, custom).
+ // `nested` so a property filter matches definition_id + its value
+ // within the same entry rather than cross-matching across properties.
+ properties: {
+ type: 'nested',
+ properties: {
+ definition_id: { type: 'keyword' },
+ values: { type: 'keyword' },
+ number_value: { type: 'double' },
+ date_value: { type: 'date' },
+ },
+ },
// Child-only fields
node_id: {
type: 'keyword',
diff --git a/rust/cloud-storage/.sqlx/query-eaf32ba063527b6af6e09f701039d2bf0fd4316d9e1280175eca27a0470c2a71.json b/rust/cloud-storage/.sqlx/query-eaf32ba063527b6af6e09f701039d2bf0fd4316d9e1280175eca27a0470c2a71.json
new file mode 100644
index 0000000000..1b9f06c60a
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-eaf32ba063527b6af6e09f701039d2bf0fd4316d9e1280175eca27a0470c2a71.json
@@ -0,0 +1,45 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n property_definition_id,\n values as \"values: serde_json::Value\"\n FROM entity_properties\n WHERE entity_id = $1\n AND entity_type = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "property_definition_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "values: serde_json::Value",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ {
+ "Custom": {
+ "name": "property_entity_type",
+ "kind": {
+ "Enum": [
+ "CHANNEL",
+ "CHAT",
+ "DOCUMENT",
+ "PROJECT",
+ "THREAD",
+ "USER",
+ "COMPANY",
+ "TASK"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "nullable": [
+ false,
+ true
+ ]
+ },
+ "hash": "eaf32ba063527b6af6e09f701039d2bf0fd4316d9e1280175eca27a0470c2a71"
+}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 23e53d97c2..f485584623 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -7669,6 +7669,7 @@ name = "models_properties"
version = "0.1.0"
dependencies = [
"chrono",
+ "document_sub_type",
"serde",
"serde_json",
"serde_with",
@@ -10659,10 +10660,12 @@ dependencies = [
"model_file_type",
"models_email",
"models_opensearch",
+ "models_properties",
"models_search",
"nom 8.0.0",
"opensearch_client",
"pdfium-render",
+ "properties_db_client",
"rust-embed",
"s3_client",
"s3_key",
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index a6c3aaaf2b..2aba69c262 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -276,11 +276,18 @@ async fn main() -> anyhow::Result<()> {
let notification_service = NotificationServiceImpl::new(SqsNotificationIngress {
queue: ingress_queue,
});
- let properties_service = Arc::new(PropertiesServiceImpl::new(
- PropertiesPgRepo::new(db.clone()),
- Some(permission_checker),
- Some(notification_service),
- ));
+ let properties_service = Arc::new(
+ PropertiesServiceImpl::new(
+ PropertiesPgRepo::new(db.clone()),
+ Some(permission_checker),
+ Some(notification_service),
+ )
+ .with_search_indexer(Arc::new(
+ crate::service::property_search_indexer::SqsPropertySearchIndexer::new(
+ sqs_client.clone(),
+ ),
+ )),
+ );
// Create the channel list service used by soup.
let channel_service_for_soup = ChannelListServiceImpl::new(
diff --git a/rust/cloud-storage/document_storage_service/src/service/mod.rs b/rust/cloud-storage/document_storage_service/src/service/mod.rs
index d27eca2441..c5d38b58b3 100644
--- a/rust/cloud-storage/document_storage_service/src/service/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/service/mod.rs
@@ -1,4 +1,5 @@
pub mod call_search_indexer;
pub mod conn_gateway;
pub mod delete_document_worker;
+pub mod property_search_indexer;
pub mod s3;
diff --git a/rust/cloud-storage/document_storage_service/src/service/property_search_indexer.rs b/rust/cloud-storage/document_storage_service/src/service/property_search_indexer.rs
new file mode 100644
index 0000000000..8ccaf4f105
--- /dev/null
+++ b/rust/cloud-storage/document_storage_service/src/service/property_search_indexer.rs
@@ -0,0 +1,40 @@
+//! Adapter that publishes property search-index upserts to the search queue.
+
+use models_properties::EntityType;
+use properties::PropertySearchIndexer;
+use sqs_client::SQS;
+use sqs_client::search::SearchQueueMessage;
+use sqs_client::search::document::DocumentPropertiesUpdate;
+
+/// Publishes an upsert of an entity's indexed properties to the shared search
+/// event queue so the search-processing service refreshes them after a write.
+#[derive(Debug)]
+pub struct SqsPropertySearchIndexer {
+ sqs: SQS,
+}
+
+impl SqsPropertySearchIndexer {
+ pub fn new(sqs: SQS) -> Self {
+ Self { sqs }
+ }
+}
+
+impl PropertySearchIndexer for SqsPropertySearchIndexer {
+ fn enqueue_upsert(
+ &self,
+ entity_id: String,
+ entity_type: EntityType,
+ ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<()>> + Send>> {
+ let sqs = self.sqs.clone();
+ Box::pin(async move {
+ sqs.send_message_to_search_event_queue(SearchQueueMessage::UpdateDocumentProperties(
+ DocumentPropertiesUpdate {
+ document_id: entity_id,
+ entity_type: entity_type.to_string(),
+ },
+ ))
+ .await?;
+ Ok(())
+ })
+ }
+}
diff --git a/rust/cloud-storage/models_properties/Cargo.toml b/rust/cloud-storage/models_properties/Cargo.toml
index f34d95fa82..c14d340149 100644
--- a/rust/cloud-storage/models_properties/Cargo.toml
+++ b/rust/cloud-storage/models_properties/Cargo.toml
@@ -6,6 +6,7 @@ version = "0.1.0"
[dependencies]
chrono = { workspace = true }
+document_sub_type = { path = "../document_sub_type" }
serde = { workspace = true }
serde_json = { workspace = true }
serde_with = { workspace = true }
diff --git a/rust/cloud-storage/models_properties/src/shared/entity_type.rs b/rust/cloud-storage/models_properties/src/shared/entity_type.rs
index 3f01a88780..252be4abc3 100644
--- a/rust/cloud-storage/models_properties/src/shared/entity_type.rs
+++ b/rust/cloud-storage/models_properties/src/shared/entity_type.rs
@@ -1,5 +1,6 @@
//! Entity type shared across database, service, and API layers.
+use document_sub_type::DocumentSubType;
use serde::{Deserialize, Serialize};
use std::{fmt, str::FromStr};
use utoipa::ToSchema;
@@ -57,3 +58,13 @@ impl FromStr for EntityType {
}
}
}
+
+impl From<DocumentSubType> for EntityType {
+ fn from(sub_type: DocumentSubType) -> Self {
+ match sub_type {
+ DocumentSubType::Task => EntityType::Task,
+ // No dedicated property entity type for snippets; they key under Document.
+ DocumentSubType::Snippet => EntityType::Document,
+ }
+ }
+}
diff --git a/rust/cloud-storage/opensearch_client/src/document.rs b/rust/cloud-storage/opensearch_client/src/document.rs
index 530d308df3..636624092a 100644
--- a/rust/cloud-storage/opensearch_client/src/document.rs
+++ b/rust/cloud-storage/opensearch_client/src/document.rs
@@ -1,6 +1,9 @@
use crate::{
OpensearchClient, Result, delete,
- upsert::{self, document::UpsertDocumentArgs},
+ upsert::{
+ self,
+ document::{IndexedProperty, UpsertDocumentArgs},
+ },
};
impl OpensearchClient {
@@ -39,6 +42,17 @@ impl OpensearchClient {
upsert::document::update_document_metadata(&self.inner, document_id, document_name).await
}
+ /// Refresh only the denormalized `properties` on an existing parent doc.
+ #[tracing::instrument(skip(self, properties))]
+ pub async fn update_document_properties(
+ &self,
+ document_id: &str,
+ properties: &[IndexedProperty],
+ ) -> Result<()> {
+ upsert::document::update_document_properties(&self.inner, document_id, properties, None)
+ .await
+ }
+
#[tracing::instrument(skip(self))]
pub async fn delete_documents_by_owner_id(&self, owner_id: &str) -> Result<()> {
delete::document::delete_document_by_owner_id(&self.inner, owner_id).await
diff --git a/rust/cloud-storage/opensearch_client/src/upsert/document.rs b/rust/cloud-storage/opensearch_client/src/upsert/document.rs
index ab2907fa97..5fce7d877f 100644
--- a/rust/cloud-storage/opensearch_client/src/upsert/document.rs
+++ b/rust/cloud-storage/opensearch_client/src/upsert/document.rs
@@ -11,6 +11,27 @@ const PARENT_RELATION: &str = "document";
/// Relation name for child (chunk) docs in the join field.
const CHILD_RELATION: &str = "chunk";
+/// A denormalized entity property indexed on the parent doc so search can
+/// filter by it. `values` holds every equality-filterable value (select
+/// options, entity refs, links, text, bool); `number_value`/`date_value`
+/// are split out only because they need range + sort semantics that keyword
+/// can't provide. Always queried scoped by `definition_id`.
+#[derive(Debug, Clone, Default, serde::Serialize)]
+pub struct IndexedProperty {
+ /// The property definition id this value belongs to.
+ pub definition_id: String,
+ /// Every equality-filterable value as a keyword: select-option UUIDs,
+ /// entity-reference ids, links, text, bool as "true"/"false".
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub values: Vec<String>,
+ /// Numeric value (e.g. story points) — range + sort.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub number_value: Option<f64>,
+ /// Date value as epoch milliseconds (e.g. due date) — range + sort.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub date_value: Option<i64>,
+}
+
/// The arguments for upserting a document into the opensearch index
#[derive(Debug, serde::Serialize)]
pub struct UpsertDocumentArgs {
@@ -41,6 +62,10 @@ pub struct UpsertDocumentArgs {
/// The sub type of the document (e.g. task)
#[serde(skip_serializing_if = "Option::is_none")]
pub sub_type: Option<String>,
+ /// Denormalized parent entity properties (status, priority, assignees,
+ /// custom) used for search filtering. Empty for documents without
+ /// properties.
+ pub properties: Vec<IndexedProperty>,
}
/// Resolve `index_override` to the physical/alias name we'll write to.
@@ -64,6 +89,11 @@ fn parent_doc_body(any_chunk: &UpsertDocumentArgs) -> serde_json::Value {
if let Some(sub_type) = &any_chunk.sub_type {
doc["sub_type"] = serde_json::Value::String(sub_type.clone());
}
+ if !any_chunk.properties.is_empty()
+ && let Ok(properties) = serde_json::to_value(&any_chunk.properties)
+ {
+ doc["properties"] = properties;
+ }
doc
}
@@ -333,5 +363,81 @@ pub(crate) async fn update_document_metadata(
})
}
+/// Update only the denormalized `properties` on an existing parent doc,
+/// without touching content. Used when an entity's properties change
+/// independently of its body. A missing doc (404) is treated as a no-op —
+/// the next full index will include the properties.
+pub(crate) async fn update_document_properties(
+ client: &opensearch::OpenSearch,
+ document_id: &str,
+ properties: &[IndexedProperty],
+ index_override: Option<&str>,
+) -> Result<()> {
+ use serde_json::json;
+
+ let index = resolve_destination(index_override);
+ let properties_value =
+ serde_json::to_value(properties).map_err(|err| OpensearchClientError::Unknown {
+ details: err.to_string(),
+ method: Some("update_document_properties".to_string()),
+ })?;
+ let body = json!({ "doc": { "properties": properties_value } });
+
+ let response = client
+ .update(opensearch::UpdateParts::IndexId(index, document_id))
+ .routing(document_id)
+ .body(body)
+ .send()
+ .await
+ .map_err(|err| OpensearchClientError::DeserializationFailed {
+ details: err.to_string(),
+ method: Some("update_document_properties".to_string()),
+ })?;
+
+ let status_code = response.status_code();
+ if status_code.is_success() {
+ tracing::trace!(document_id=%document_id, "document properties updated");
+ return Ok(());
+ }
+ let body =
+ response
+ .text()
+ .await
+ .map_err(|err| OpensearchClientError::DeserializationFailed {
+ details: err.to_string(),
+ method: Some("update_document_properties".to_string()),
+ })?;
+
+ // A *missing document* 404 is a no-op: the doc isn't indexed yet, so the
+ // next full index will include its properties. A *missing index* 404
+ // (`index_not_found_exception`) is a real outage and must propagate. The
+ // type is read from the error body the same way `parse_bulk_response`
+ // reads `error.reason`.
+ if status_code.as_u16() == 404 {
+ let error_type = serde_json::from_str::<serde_json::Value>(&body)
+ .ok()
+ .and_then(|value| value["error"]["type"].as_str().map(str::to_owned));
+ if error_type.as_deref() == Some("document_missing_exception") {
+ tracing::debug!(
+ document_id=%document_id,
+ "document not indexed yet; skipping property update"
+ );
+ return Ok(());
+ }
+ }
+
+ tracing::error!(
+ status_code=?status_code,
+ body=?body,
+ document_id=%document_id,
+ "error updating document properties",
+ );
+
+ Err(OpensearchClientError::Unknown {
+ details: body,
+ method: Some("update_document_properties".to_string()),
+ })
+}
+
#[cfg(test)]
mod test;
diff --git a/rust/cloud-storage/opensearch_client/src/upsert/document/test.rs b/rust/cloud-storage/opensearch_client/src/upsert/document/test.rs
index 39154a9805..9ccc3f5d79 100644
--- a/rust/cloud-storage/opensearch_client/src/upsert/document/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/upsert/document/test.rs
@@ -12,6 +12,7 @@ fn args(doc_id: &str, node_id: &str) -> UpsertDocumentArgs {
content: format!("content {doc_id} {node_id}"),
updated_at_seconds: EpochSeconds::new(1_700_000_000).unwrap(),
sub_type: None,
+ properties: vec![],
}
}
@@ -38,6 +39,44 @@ fn parent_doc_body_includes_optional_sub_type() {
assert_eq!(doc["sub_type"], "task");
}
+#[test]
+fn parent_doc_body_includes_properties_when_present() {
+ let mut a = args("doc1", "n1");
+ a.properties = vec![
+ IndexedProperty {
+ definition_id: "status-def".to_string(),
+ values: vec!["not-started".to_string()],
+ ..Default::default()
+ },
+ IndexedProperty {
+ definition_id: "assignees-def".to_string(),
+ values: vec!["macro|[email protected]".to_string()],
+ ..Default::default()
+ },
+ IndexedProperty {
+ definition_id: "due-date-def".to_string(),
+ date_value: Some(1_700_000_000_000),
+ ..Default::default()
+ },
+ ];
+ let doc = parent_doc_body(&a);
+ let props = doc["properties"].as_array().expect("properties array");
+ assert_eq!(props.len(), 3);
+ assert_eq!(props[0]["definition_id"], "status-def");
+ assert_eq!(props[0]["values"][0], "not-started");
+ // Empty value fields are skipped, not serialized as empty/null.
+ assert!(props[0].get("number_value").is_none());
+ assert_eq!(props[1]["values"][0], "macro|[email protected]");
+ assert_eq!(props[2]["date_value"], 1_700_000_000_000i64);
+ assert!(props[2].get("values").is_none());
+}
+
+#[test]
+fn parent_doc_body_omits_properties_when_empty() {
+ let doc = parent_doc_body(&args("doc1", "n1"));
+ assert!(doc.get("properties").is_none());
+}
+
#[test]
fn child_doc_body_has_chunk_fields_and_join_pointer() {
let mut a = args("doc1", "n1");
diff --git a/rust/cloud-storage/properties/src/domain/ports.rs b/rust/cloud-storage/properties/src/domain/ports.rs
index b184740c77..10171e2143 100644
--- a/rust/cloud-storage/properties/src/domain/ports.rs
+++ b/rust/cloud-storage/properties/src/domain/ports.rs
@@ -168,3 +168,19 @@ pub trait NotificationService: Send + Sync + 'static {
>,
) -> impl Future<Output = Result<uuid::Uuid, Self::Err>> + Send;
}
+
+/// Port for keeping an entity's indexed properties in sync after a mutation.
+///
+/// Mirrors the per-domain `*SearchIndexer` ports (e.g. `CallSearchIndexer`):
+/// the domain calls it on a write and an SQS-backed adapter in the composition
+/// root publishes the upsert. `dyn`-compatible (boxed future) so it can be an
+/// optional collaborator on the service without adding a generic parameter.
+pub trait PropertySearchIndexer: Send + Sync + std::fmt::Debug {
+ /// Enqueue an upsert of the entity's indexed properties. Best-effort —
+ /// callers log and continue on error.
+ fn enqueue_upsert(
+ &self,
+ entity_id: String,
+ entity_type: EntityType,
+ ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<()>> + Send>>;
+}
diff --git a/rust/cloud-storage/properties/src/domain/service_impl/mod.rs b/rust/cloud-storage/properties/src/domain/service_impl/mod.rs
index f71d7737f3..cdd0d8c4dd 100644
--- a/rust/cloud-storage/properties/src/domain/service_impl/mod.rs
+++ b/rust/cloud-storage/properties/src/domain/service_impl/mod.rs
@@ -12,7 +12,9 @@ use uuid::Uuid;
use super::error::PropertiesErr;
use super::model::EntityPropertyInfo;
-use super::ports::{NotificationService, PermissionService, PropertiesRepo};
+use std::sync::Arc;
+
+use super::ports::{NotificationService, PermissionService, PropertiesRepo, PropertySearchIndexer};
use super::service::PropertiesService;
use helpers::{extract_option_ids_from_property_value, is_property_applicable_to};
@@ -28,6 +30,7 @@ where
repository: R,
permission_service: Option<P>,
notification_service: Option<N>,
+ search_indexer: Option<Arc<dyn PropertySearchIndexer>>,
}
impl<R, P, N> PropertiesServiceImpl<R, P, N>
@@ -46,6 +49,32 @@ where
repository,
permission_service,
notification_service,
+ search_indexer: None,
+ }
+ }
+
+ /// Attach a search-reindex publisher so property mutations refresh the
+ /// search index. Builder-style so existing constructions are unaffected.
+ pub fn with_search_indexer(mut self, search_indexer: Arc<dyn PropertySearchIndexer>) -> Self {
+ self.search_indexer = Some(search_indexer);
+ self
+ }
+
+ /// Best-effort publish of a property reindex for entities that live in
+ /// the documents search index (tasks/documents). Logs and continues on
+ /// failure so a missed reindex never fails the mutation itself.
+ async fn enqueue_property_upsert(&self, entity_id: &str, entity_type: EntityType) {
+ let Some(search_indexer) = self.search_indexer.as_ref() else {
+ return;
+ };
+ if !matches!(entity_type, EntityType::Task | EntityType::Document) {
+ return;
+ }
+ if let Err(error) = search_indexer
+ .enqueue_upsert(entity_id.to_string(), entity_type)
+ .await
+ {
+ tracing::warn!(error = ?error, entity_id = %entity_id, "failed to enqueue search reindex for property change");
}
}
@@ -115,6 +144,8 @@ where
.await
.map_err(anyhow::Error::from)?;
+ self.enqueue_property_upsert(entity_id, entity_type).await;
+
Ok(())
}
@@ -291,6 +322,8 @@ where
.await
.map_err(anyhow::Error::from)?;
+ self.enqueue_property_upsert(entity_id, entity_type).await;
+
Ok(())
}
diff --git a/rust/cloud-storage/properties/src/lib.rs b/rust/cloud-storage/properties/src/lib.rs
index 899c3246b7..b18d7c5800 100644
--- a/rust/cloud-storage/properties/src/lib.rs
+++ b/rust/cloud-storage/properties/src/lib.rs
@@ -16,7 +16,9 @@ pub mod outbound;
pub use domain::error::PropertiesErr;
pub use domain::model::{EntityPropertyInfo, PropertyOptionInfo};
-pub use domain::ports::{NotificationService, PermissionService, PropertiesRepo};
+pub use domain::ports::{
+ NotificationService, PermissionService, PropertiesRepo, PropertySearchIndexer,
+};
pub use domain::service::PropertiesService;
pub use domain::service_impl::PropertiesServiceImpl;
pub use outbound::notification_service::NotificationServiceImpl;
diff --git a/rust/cloud-storage/properties_db_client/src/entity_properties/get.rs b/rust/cloud-storage/properties_db_client/src/entity_properties/get.rs
index 54bf1309bf..18ec57b649 100644
--- a/rust/cloud-storage/properties_db_client/src/entity_properties/get.rs
+++ b/rust/cloud-storage/properties_db_client/src/entity_properties/get.rs
@@ -568,6 +568,98 @@ AND pd.id = ANY($3::UUID[])
Ok(entity_properties_map)
}
+/// An entity property flattened into the shape the search index stores. Each
+/// value lands under the field matching its type; the rest stay empty/None.
+/// Covers every `PropertyValue` kind except multi-string.
+#[derive(Default)]
+pub struct IndexedEntityProperty {
+ /// The property definition id this value belongs to.
+ pub definition_id: String,
+ /// Every equality-filterable value as a string: select-option UUIDs,
+ /// entity-reference ids, links, text, bool as "true"/"false".
+ pub values: Vec<String>,
+ /// Numeric value (range + sort).
+ pub number_value: Option<f64>,
+ /// Date value as epoch milliseconds (range + sort).
+ pub date_value: Option<i64>,
+}
+
+impl IndexedEntityProperty {
+ fn is_empty(&self) -> bool {
+ self.values.is_empty() && self.number_value.is_none() && self.date_value.is_none()
+ }
+}
+
+/// Fetch an entity's properties flattened for the search index. Each value
+/// lands under the field matching its type (equality-filterable values as
+/// strings, numbers, or epoch-millis dates); null and unparseable values are
+/// skipped so one bad value can't fail the whole index.
+#[tracing::instrument(skip(db), err)]
+pub async fn get_entity_properties_for_index(
+ db: &Pool<Postgres>,
+ entity_id: &str,
+ entity_type: EntityType,
+) -> Result<Vec<IndexedEntityProperty>> {
+ let rows = sqlx::query!(
+ r#"
+ SELECT
+ property_definition_id,
+ values as "values: serde_json::Value"
+ FROM entity_properties
+ WHERE entity_id = $1
+ AND entity_type = $2
+ "#,
+ entity_id,
+ entity_type as EntityType,
+ )
+ .fetch_all(db)
+ .await?;
+
+ let mut result = Vec::with_capacity(rows.len());
+ for row in rows {
+ let Some(value) = row.values else {
+ continue;
+ };
+ if value.is_null() {
+ continue;
+ }
+ let parsed = match serde_json::from_value::<PropertyValue>(value) {
+ Ok(parsed) => parsed,
+ Err(e) => {
+ tracing::warn!(
+ error = ?e,
+ definition_id = %row.property_definition_id,
+ "skipping unparseable property value for index"
+ );
+ continue;
+ }
+ };
+ let mut property = IndexedEntityProperty {
+ definition_id: row.property_definition_id.to_string(),
+ ..Default::default()
+ };
+ match parsed {
+ PropertyValue::SelectOption(ids) => {
+ property.values = ids.into_iter().map(|id| id.to_string()).collect();
+ }
+ PropertyValue::EntityRef(refs) => {
+ property.values = refs.into_iter().map(|r| r.entity_id).collect();
+ }
+ PropertyValue::Link(urls) => property.values = urls,
+ PropertyValue::Str(s) => property.values = vec![s],
+ PropertyValue::Bool(b) => property.values = vec![b.to_string()],
+ PropertyValue::Num(n) => property.number_value = Some(n),
+ PropertyValue::Date(d) => property.date_value = Some(d.timestamp_millis()),
+ }
+ if property.is_empty() {
+ continue;
+ }
+ result.push(property);
+ }
+
+ Ok(result)
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/rust/cloud-storage/search_processing_service/Cargo.toml b/rust/cloud-storage/search_processing_service/Cargo.toml
index ae1b90f0f9..6fd2b99c24 100644
--- a/rust/cloud-storage/search_processing_service/Cargo.toml
+++ b/rust/cloud-storage/search_processing_service/Cargo.toml
@@ -8,7 +8,7 @@ version = "0.1.0"
[features]
default = ["processing", "service"]
processing = []
-service = ["macro_db_client"]
+service = ["macro_db_client", "models_properties", "properties_db_client"]
[[bin]]
name = "search_processing_service"
@@ -52,11 +52,13 @@ s3_key = { path = "../s3_key" }
models_email = { path = "../models_email" }
model_file_type = { path = "../model_file_type" }
models_opensearch = { path = "../models_opensearch" }
+models_properties = { path = "../models_properties", optional = true }
models_search = { path = "../models_search" }
nom = { workspace = true }
opensearch_client = { path = "../opensearch_client" }
ensure_exists = { path = "../ensure_exists", features = ["dynamodb"] }
pdfium-render = { workspace = true }
+properties_db_client = { path = "../properties_db_client", optional = true }
rust-embed = "8.6.0"
s3_client = { path = "../s3_client" }
secretsmanager_client = { path = "../secretsmanager_client" }
diff --git a/rust/cloud-storage/search_processing_service/src/process/document/mod.rs b/rust/cloud-storage/search_processing_service/src/process/document/mod.rs
index 7bd7e6da5a..58662ac8aa 100644
--- a/rust/cloud-storage/search_processing_service/src/process/document/mod.rs
+++ b/rust/cloud-storage/search_processing_service/src/process/document/mod.rs
@@ -1,7 +1,7 @@
use anyhow::Context;
use model::document::FileTypeExt;
use opensearch_client::OpensearchClient;
-use sqs_client::search::document::{DocumentId, SearchExtractorMessage};
+use sqs_client::search::document::{DocumentId, DocumentPropertiesUpdate, SearchExtractorMessage};
mod document_info;
mod raw_document;
@@ -69,3 +69,18 @@ pub async fn process_extract_sync_message(
Ok(())
}
+
+pub async fn process_property_update(
+ opensearch_client: &OpensearchClient,
+ db: &sqlx::Pool<sqlx::Postgres>,
+ message: &DocumentPropertiesUpdate,
+) -> anyhow::Result<()> {
+ raw_document::update_search_with_property_update(opensearch_client, db, message)
+ .await
+ .context(format!(
+ "{} unable to update document properties in search",
+ message.document_id
+ ))?;
+
+ Ok(())
+}
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 db6102d679..80314f7f3b 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
@@ -2,12 +2,17 @@ use std::str::FromStr;
use anyhow::Context;
use chrono::Utc;
+use document_sub_type::DocumentSubType;
use model::document::{DocumentMetadata, FileType};
+use models_properties::EntityType;
use models_search::document::MarkdownParseResult;
use models_search::unified::is_searchable_association;
use opensearch_client::{
- OpensearchClient, date_format::EpochSeconds, upsert::document::UpsertDocumentArgs,
+ OpensearchClient,
+ date_format::EpochSeconds,
+ upsert::document::{IndexedProperty, UpsertDocumentArgs},
};
+use properties_db_client::entity_properties::get::get_entity_properties_for_index;
use s3_key::{
CONVERTED_DOCUMENT_FILE_NAME, build_cloud_storage_bucket_document_key,
build_docx_to_pdf_converted_document_key,
@@ -18,7 +23,7 @@ use crate::{
process::document::document_info::{DocumentInfo, get_document_info},
};
-use super::SearchExtractorMessage;
+use super::{DocumentPropertiesUpdate, SearchExtractorMessage};
async fn upsert_document(
opensearch_client: &OpensearchClient,
@@ -61,6 +66,55 @@ async fn upsert_document(
Ok(())
}
+/// Properties are keyed under the task entity type for tasks, otherwise the
+/// document entity type.
+fn properties_entity_type(sub_type: Option<&str>) -> EntityType {
+ sub_type
+ .and_then(|s| s.parse::<DocumentSubType>().ok())
+ .map(EntityType::from)
+ .unwrap_or(EntityType::Document)
+}
+
+/// Fetch the entity's indexed properties and attach them to every chunk upsert
+/// (parent metadata is denormalized identically across chunks).
+///
+/// A full index overwrites the parent doc, so an *empty* `properties` clears
+/// previously-indexed values — the deliberate "omit == remove" behavior used
+/// for `sub_type`. That is correct when the entity genuinely has no
+/// properties, but a fetch *failure* must not be mistaken for "empty": we
+/// propagate the error so the doc isn't overwritten and the message is retried
+/// (mirroring the partial-update path).
+async fn attach_indexed_properties(
+ db: &sqlx::Pool<sqlx::Postgres>,
+ document_id: &str,
+ sub_type: Option<&str>,
+ upserts: &mut [UpsertDocumentArgs],
+) -> anyhow::Result<()> {
+ if upserts.is_empty() {
+ return Ok(());
+ }
+ let properties =
+ get_entity_properties_for_index(db, document_id, properties_entity_type(sub_type))
+ .await
+ .context("failed to fetch properties for search index")?;
+ if properties.is_empty() {
+ return Ok(());
+ }
+ let indexed: Vec<IndexedProperty> = properties
+ .into_iter()
+ .map(|p| IndexedProperty {
+ definition_id: p.definition_id,
+ values: p.values,
+ number_value: p.number_value,
+ date_value: p.date_value,
+ })
+ .collect();
+ for upsert in upserts.iter_mut() {
+ upsert.properties = indexed.clone();
+ }
+ Ok(())
+}
+
/// Processes a message for a standard document and reads the updated contents from s3 and updates
/// the document in opensearch.
#[tracing::instrument(skip(opensearch_client, db, s3_client, document_storage_bucket, search_extractor_message), fields(document_id=search_extractor_message.document_id, file_type=?search_extractor_message.file_type))]
@@ -166,7 +220,7 @@ pub async fn update_search_with_raw_document(
let updated_at = EpochSeconds::new(Utc::now().timestamp())?;
let uuid = macro_uuid::generate_uuid_v7().to_string();
- let upserts: Vec<UpsertDocumentArgs> = match file_type {
+ let mut upserts: Vec<UpsertDocumentArgs> = match file_type {
FileType::Pdf | FileType::Docx => {
let pages_content = parse_pdf_pages(content).context("unable to parse pdf")?;
pages_content
@@ -182,6 +236,7 @@ pub async fn update_search_with_raw_document(
file_type: file_type.to_string(),
updated_at_seconds: updated_at,
sub_type: sub_type.clone(),
+ properties: vec![],
})
.collect()
}
@@ -198,6 +253,7 @@ pub async fn update_search_with_raw_document(
file_type: file_type.to_string(),
updated_at_seconds: updated_at,
sub_type: sub_type.clone(),
+ properties: vec![],
}]
}
FileType::Md => {
@@ -218,6 +274,7 @@ pub async fn update_search_with_raw_document(
file_type: file_type.to_string(),
updated_at_seconds: updated_at,
sub_type: sub_type.clone(),
+ properties: vec![],
})
.collect::<Vec<UpsertDocumentArgs>>()
}
@@ -236,11 +293,20 @@ pub async fn update_search_with_raw_document(
file_type: file_type.to_string(),
updated_at_seconds: updated_at,
sub_type: sub_type.clone(),
+ properties: vec![],
}]
}
}
};
+ attach_indexed_properties(
+ db,
+ &search_extractor_message.document_id,
+ sub_type.as_deref(),
+ &mut upserts,
+ )
+ .await?;
+
upsert_document(opensearch_client, search_extractor_message, upserts).await?;
Ok(())
@@ -273,6 +339,7 @@ fn generate_upserts(
file_type: file_type.to_string(),
updated_at_seconds: updated_at,
sub_type: sub_type.clone(),
+ properties: vec![],
})
.collect::<Vec<UpsertDocumentArgs>>();
@@ -338,7 +405,11 @@ pub async fn update_search_with_sync_document(
}
};
- let upserts = generate_upserts(document_info, result).context("unable to generate upserts")?;
+ let sub_type = document_info.sub_type.as_ref().map(|st| st.to_string());
+ let mut upserts =
+ generate_upserts(document_info, result).context("unable to generate upserts")?;
+
+ attach_indexed_properties(db, document_id, sub_type.as_deref(), &mut upserts).await?;
let chunk_count = upserts.len();
upsert_document(opensearch_client, search_extractor_message, upserts).await?;
@@ -347,6 +418,34 @@ pub async fn update_search_with_sync_document(
Ok(())
}
+/// Refresh only the indexed `properties` of a document after a property
+/// mutation, without re-extracting its content.
+pub async fn update_search_with_property_update(
+ opensearch_client: &OpensearchClient,
+ db: &sqlx::Pool<sqlx::Postgres>,
+ message: &DocumentPropertiesUpdate,
+) -> anyhow::Result<()> {
+ let entity_type = EntityType::from_str(&message.entity_type)
+ .with_context(|| format!("invalid entity_type '{}'", message.entity_type))?;
+ let properties = get_entity_properties_for_index(db, &message.document_id, entity_type)
+ .await
+ .context("failed to fetch properties for reindex")?;
+ let indexed: Vec<IndexedProperty> = properties
+ .into_iter()
+ .map(|p| IndexedProperty {
+ definition_id: p.definition_id,
+ values: p.values,
+ number_value: p.number_value,
+ date_value: p.date_value,
+ })
+ .collect();
+ opensearch_client
+ .update_document_properties(&message.document_id, &indexed)
+ .await
+ .context("failed to update document properties in search index")?;
+ Ok(())
+}
+
#[cfg(test)]
mod tests {
use macro_user_id::user_id::MacroUserIdStr;
diff --git a/rust/cloud-storage/search_processing_service/src/process/mod.rs b/rust/cloud-storage/search_processing_service/src/process/mod.rs
index 22bae2f10d..2ed0e7dfa5 100644
--- a/rust/cloud-storage/search_processing_service/src/process/mod.rs
+++ b/rust/cloud-storage/search_processing_service/src/process/mod.rs
@@ -90,6 +90,9 @@ pub async fn process_message(
)
.await?;
}
+ SearchQueueMessage::UpdateDocumentProperties(message) => {
+ document::process_property_update(&ctx.opensearch_client, &ctx.db, &message).await?;
+ }
SearchQueueMessage::ChatMessage(message) => {
chat::insert_chat_message(&ctx.opensearch_client, &ctx.db, &message).await?;
}
diff --git a/rust/cloud-storage/search_service/src/api/search/document.rs b/rust/cloud-storage/search_service/src/api/search/document.rs
index 8935f7221d..90b41bd5b2 100644
--- a/rust/cloud-storage/search_service/src/api/search/document.rs
+++ b/rust/cloud-storage/search_service/src/api/search/document.rs
@@ -48,10 +48,10 @@ pub(in crate::api::search) async fn enrich_documents(
.iter()
.filter(|(_, info)| info.file_type.as_deref() == Some("md"))
.map(|(id, info)| {
- let entity_type = match info.sub_type {
- Some(document_sub_type::DocumentSubType::Task) => EntityType::Task,
- _ => EntityType::Document,
- };
+ let entity_type = info
+ .sub_type
+ .map(EntityType::from)
+ .unwrap_or(EntityType::Document);
EntityReference::new(id.clone(), entity_type)
})
.collect();
diff --git a/rust/cloud-storage/sqs_client/src/search/document.rs b/rust/cloud-storage/sqs_client/src/search/document.rs
index b80b9568ee..8c6244ba6e 100644
--- a/rust/cloud-storage/sqs_client/src/search/document.rs
+++ b/rust/cloud-storage/sqs_client/src/search/document.rs
@@ -7,6 +7,16 @@ pub struct DocumentId {
pub document_id: String,
}
+/// A request to refresh only the indexed properties of a document (e.g. after
+/// a status / assignee / tag change), without re-extracting its content.
+#[derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, Debug)]
+pub struct DocumentPropertiesUpdate {
+ /// The document (entity) whose indexed properties should be refreshed.
+ pub document_id: String,
+ /// The property entity type the values are keyed under (e.g. "TASK").
+ pub entity_type: String,
+}
+
/// Search text extractor message
#[derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, Debug)]
pub struct SearchExtractorMessage {
diff --git a/rust/cloud-storage/sqs_client/src/search/mod.rs b/rust/cloud-storage/sqs_client/src/search/mod.rs
index 4a261fbf41..01799799b6 100644
--- a/rust/cloud-storage/sqs_client/src/search/mod.rs
+++ b/rust/cloud-storage/sqs_client/src/search/mod.rs
@@ -4,7 +4,7 @@ use crate::{
call::{CallRecordMessage, RemoveCallRecord},
channel::{ChannelMessageUpdate, RemoveChannelMessage},
chat::{ChatMessage, RemoveChatMessage},
- document::{DocumentId, SearchExtractorMessage},
+ document::{DocumentId, DocumentPropertiesUpdate, SearchExtractorMessage},
email::{EmailLinkMessage, EmailMessage, EmailThreadBatchMessage, EmailThreadMessage},
},
};
@@ -70,6 +70,7 @@ pub enum SearchQueueMessage {
ExtractDocumentText(SearchExtractorMessage),
RemoveDocument(DocumentId),
ExtractSync(SearchExtractorMessage),
+ UpdateDocumentProperties(DocumentPropertiesUpdate),
// Chat
ChatMessage(ChatMessage),
RemoveChatMessage(RemoveChatMessage),
@@ -96,6 +97,7 @@ impl PrimaryId for SearchQueueMessage {
SearchQueueMessage::ExtractDocumentText(message) => message.document_id.clone(),
SearchQueueMessage::RemoveDocument(message) => message.document_id.clone(),
SearchQueueMessage::ExtractSync(message) => message.document_id.clone(),
+ SearchQueueMessage::UpdateDocumentProperties(message) => message.document_id.clone(),
SearchQueueMessage::ChatMessage(message) => message.message_id.clone(), // needs
// to be the message id to ensure it's unique for batch
SearchQueueMessage::RemoveChatMessage(message) => message.chat_id.clone(),
@@ -133,6 +135,7 @@ impl SearchQueueMessage {
SearchQueueMessage::ExtractDocumentText(_) => Operation::ExtractText,
SearchQueueMessage::RemoveDocument(_) => Operation::Remove,
SearchQueueMessage::ExtractSync(_) => Operation::ExtractSync,
+ SearchQueueMessage::UpdateDocumentProperties(_) => Operation::UpdateMetadata,
// Chat
SearchQueueMessage::ChatMessage(_) => Operation::ExtractText,
SearchQueueMessage::RemoveChatMessage(_) => Operation::Remove,