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(soup): support document sub_type filter in dynamic query (#1991)

Will Hutchinsond5db9f309ff7
diff --git a/js/app/packages/service-clients/service-search/generated/models/documentFilters.ts b/js/app/packages/service-clients/service-search/generated/models/documentFilters.ts
index 25445d3d61..86e5340d1f 100644
--- a/js/app/packages/service-clients/service-search/generated/models/documentFilters.ts
+++ b/js/app/packages/service-clients/service-search/generated/models/documentFilters.ts
@@ -25,6 +25,8 @@ export interface DocumentFilters {
/** A list of project ids to search within. Examples: ['project1'].
filtering. Empty to ignore project filtering. */
project_ids?: string[];
+ /** Filter by document sub type. Examples: ['task']. Empty to search all sub types. */
+ sub_types?: string[];
/** Task-specific filters that only apply to task subtype documents. */
task_filters?: TaskFilters;
}
diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.json
index 2f46fb476d..352f0538b5 100644
--- a/js/app/packages/service-clients/service-search/openapi.json
+++ b/js/app/packages/service-clients/service-search/openapi.json
@@ -665,6 +665,13 @@
},
"description": "A list of project ids to search within. Examples: ['project1'].\nfiltering. Empty to ignore project filtering."
},
+ "sub_types": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Filter by document sub type. Examples: ['task']. Empty to search all sub types."
+ },
"task_filters": {
"$ref": "#/components/schemas/TaskFilters",
"description": "Task-specific filters that only apply to task subtype documents."
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentFilters.ts
index 6cd848c835..f063ee92e3 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/documentFilters.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentFilters.ts
@@ -25,6 +25,8 @@ export interface DocumentFilters {
/** A list of project ids to search within. Examples: ['project1'].
filtering. Empty to ignore project filtering. */
project_ids?: string[];
+ /** Filter by document sub type. Examples: ['task']. Empty to search all sub types. */
+ sub_types?: string[];
/** Task-specific filters that only apply to task subtype documents. */
task_filters?: TaskFilters;
}
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index 7a3405c61b..54c7a17799 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -4237,6 +4237,12 @@ export const postItemsSoupBody = zod
.describe(
"A list of project ids to search within. Examples: ['project1'].\nfiltering. Empty to ignore project filtering."
),
+ sub_types: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ "Filter by document sub type. Examples: ['task']. Empty to search all sub types."
+ ),
task_filters: zod
.object({
include_cbm_atm_nc: zod
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index d2e88c78a3..cee4b0c07e 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -6323,6 +6323,13 @@
},
"description": "A list of project ids to search within. Examples: ['project1'].\nfiltering. Empty to ignore project filtering."
},
+ "sub_types": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Filter by document sub type. Examples: ['task']. Empty to search all sub types."
+ },
"task_filters": {
"$ref": "#/components/schemas/TaskFilters",
"description": "Task-specific filters that only apply to task subtype documents."
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 7ef7d7fdda..d9c459c3e7 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -5162,6 +5162,7 @@ version = "0.1.0"
dependencies = [
"chrono",
"cool_asserts",
+ "document_sub_type",
"either",
"filter_ast",
"macro_user_id",
diff --git a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs
index d5caa21ebf..fbe44df3ca 100644
--- a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs
+++ b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs
@@ -180,6 +180,9 @@ fn build_document_filter(ast: Option<&Expr<DocumentLiteral>>) -> String {
build_task_include_cbm_atm_nc_clause("fa.entity_id")
}
filter_ast::ExprFrame::Literal(DocumentLiteral::IncludeCbmAtmNc(false)) => String::new(),
+ filter_ast::ExprFrame::Literal(DocumentLiteral::SubType(st)) => {
+ format!("dt.sub_type = '{st}'")
+ }
});
if formatting.is_empty() {
String::new()
diff --git a/rust/cloud-storage/item_filters/Cargo.toml b/rust/cloud-storage/item_filters/Cargo.toml
index 9550aad7aa..3630c38777 100644
--- a/rust/cloud-storage/item_filters/Cargo.toml
+++ b/rust/cloud-storage/item_filters/Cargo.toml
@@ -11,6 +11,7 @@ schema = ["dep:schemars", "dep:utoipa"]
[dependencies]
chrono = { workspace = true }
either = { workspace = true }
+document_sub_type = { path = "../document_sub_type" }
filter_ast = { path = "../filter_ast" }
macro_user_id = { path = "../macro_user_id" }
model_file_type = { path = "../model_file_type" }
diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rs
index 3ed3e0984b..4e2d7263b8 100644
--- a/rust/cloud-storage/item_filters/src/ast.rs
+++ b/rust/cloud-storage/item_filters/src/ast.rs
@@ -62,6 +62,9 @@ pub enum ExpandErr {
/// invalid macro user id
#[error(transparent)]
MacroIdErr(#[from] macro_user_id::error::ParseErr),
+ /// unknown document sub type
+ #[error(transparent)]
+ DocumentSubTypeErr(#[from] strum::ParseError),
}
/// type alias for a maybe empty, cheaply cloneable ast literal tree
diff --git a/rust/cloud-storage/item_filters/src/ast/document.rs b/rust/cloud-storage/item_filters/src/ast/document.rs
index 5354b23567..96a990d045 100644
--- a/rust/cloud-storage/item_filters/src/ast/document.rs
+++ b/rust/cloud-storage/item_filters/src/ast/document.rs
@@ -1,4 +1,5 @@
use crate::{DocumentFilters, ast::ExpandErr};
+use document_sub_type::DocumentSubType;
use either::Either;
use filter_ast::{ExpandFrame, Expr, FoldTree, TryExpandNode};
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
@@ -41,6 +42,9 @@ pub enum DocumentLiteral {
/// include tasks that are created by me, assigned to me, and not completed.
#[serde(rename = "cbm")]
IncludeCbmAtmNc(bool),
+ /// this node value filters by document sub type
+ #[serde(rename = "dst")]
+ SubType(DocumentSubType),
}
fn prefix(s: &str) -> IResult<&str, &str> {
@@ -144,6 +148,7 @@ impl ExpandFrame<DocumentLiteral> for DocumentFilters {
importance,
notification_filters,
task_filters,
+ sub_types,
} = filter_request;
let file_types_node = file_types
@@ -175,6 +180,11 @@ impl ExpandFrame<DocumentLiteral> for DocumentFilters {
.seen
.map(|seen| Expr::Literal(DocumentLiteral::NotificationSeen(seen)));
+ let sub_types_node = sub_types
+ .iter()
+ .map(|s| DocumentSubType::from_str(s))
+ .try_expand(|r| r.map(DocumentLiteral::SubType), Expr::or)?;
+
let normal_expr = [
file_types_node,
document_id_nodes,
@@ -183,6 +193,7 @@ impl ExpandFrame<DocumentLiteral> for DocumentFilters {
importance_node,
notification_done_node,
notification_seen_node,
+ sub_types_node,
]
.into_iter()
.fold_with(Expr::and);
diff --git a/rust/cloud-storage/item_filters/src/ast/tests.rs b/rust/cloud-storage/item_filters/src/ast/tests.rs
index 6afc531559..d4a8dba8f7 100644
--- a/rust/cloud-storage/item_filters/src/ast/tests.rs
+++ b/rust/cloud-storage/item_filters/src/ast/tests.rs
@@ -631,3 +631,95 @@ fn it_expands_property_filter_with_entity_type() {
// entity_type should be present when Some
assert_eq!(json, exp);
}
+
+#[test]
+fn it_expands_single_document_sub_type() {
+ let f = EntityFilters {
+ document_filters: DocumentFilters {
+ sub_types: vec!["task".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let ast = Arc::into_inner(
+ EntityFilterAst::new_from_filters(f)
+ .unwrap()
+ .unwrap()
+ .document_filter
+ .unwrap(),
+ )
+ .unwrap();
+
+ let json = serde_json::to_value(ast).unwrap();
+ let exp = json!({
+ "l": {
+ "dst": "task"
+ }
+ });
+
+ assert_eq!(json, exp);
+}
+
+#[test]
+fn it_expands_sub_type_with_file_type() {
+ let f = EntityFilters {
+ document_filters: DocumentFilters {
+ file_types: vec!["pdf".to_string()],
+ sub_types: vec!["task".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let ast = Arc::into_inner(
+ EntityFilterAst::new_from_filters(f)
+ .unwrap()
+ .unwrap()
+ .document_filter
+ .unwrap(),
+ )
+ .unwrap();
+
+ let json = serde_json::to_value(ast).unwrap();
+ // Should be AND of file_type and sub_type
+ assert!(
+ json.get("&").is_some(),
+ "file_type and sub_type should AND together"
+ );
+ let as_text = serde_json::to_string(&json).unwrap();
+ assert!(as_text.contains(r#""dst":"task""#));
+ assert!(as_text.contains(r#""ft":"pdf""#));
+}
+
+#[test]
+fn invalid_sub_type_returns_error() {
+ let f = EntityFilters {
+ document_filters: DocumentFilters {
+ sub_types: vec!["nonexistent".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ assert!(
+ EntityFilterAst::new_from_filters(f).is_err(),
+ "invalid sub type should return an error"
+ );
+}
+
+#[test]
+fn empty_sub_types_produce_no_ast() {
+ let f = EntityFilters {
+ document_filters: DocumentFilters {
+ sub_types: vec![],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ assert!(
+ EntityFilterAst::new_from_filters(f).unwrap().is_none(),
+ "empty sub_types should produce no AST"
+ );
+}
diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rs
index d996ee0738..fcdbe28187 100644
--- a/rust/cloud-storage/item_filters/src/lib.rs
+++ b/rust/cloud-storage/item_filters/src/lib.rs
@@ -93,6 +93,10 @@ pub struct DocumentFilters {
/// Task-specific filters that only apply to task subtype documents.
#[serde(default, skip_serializing_if = "TaskFilters::is_empty")]
pub task_filters: TaskFilters,
+
+ /// Filter by document sub type. Examples: ['task']. Empty to search all sub types.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub sub_types: Vec<String>,
}
impl IsEmpty for DocumentFilters {
@@ -105,6 +109,7 @@ impl IsEmpty for DocumentFilters {
importance,
notification_filters,
task_filters,
+ sub_types,
} = self;
file_types.is_empty()
&& document_ids.is_empty()
@@ -113,6 +118,7 @@ impl IsEmpty for DocumentFilters {
&& importance.is_none()
&& notification_filters.is_empty()
&& task_filters.is_empty()
+ && sub_types.is_empty()
}
}
diff --git a/rust/cloud-storage/macro_db_client/fixtures/dynamic_query_exhaustive.sql b/rust/cloud-storage/macro_db_client/fixtures/dynamic_query_exhaustive.sql
index ede763ac16..87ab3817c6 100644
--- a/rust/cloud-storage/macro_db_client/fixtures/dynamic_query_exhaustive.sql
+++ b/rust/cloud-storage/macro_db_client/fixtures/dynamic_query_exhaustive.sql
@@ -38,9 +38,14 @@ INSERT INTO public."Organization" ("id", "name", "status")
VALUES (1, 'Test Organization', 'PILOT')
ON CONFLICT DO NOTHING;
-INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId")
-VALUES ('macro|[email protected]', '[email protected]', 'stripe_id_1', 1),
- ('macro|[email protected]', '[email protected]', 'stripe_id_2', 1)
+INSERT INTO public.macro_user (id, username, email, stripe_customer_id) VALUES
+ ('00000000-0000-0000-0000-000000000001', 'testuser1', '[email protected]', 'stripe_mu_1'),
+ ('00000000-0000-0000-0000-000000000002', 'testuser2', '[email protected]', 'stripe_mu_2')
+ON CONFLICT DO NOTHING;
+
+INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId", "macro_user_id")
+VALUES ('macro|[email protected]', '[email protected]', 'stripe_id_1', 1, '00000000-0000-0000-0000-000000000001'),
+ ('macro|[email protected]', '[email protected]', 'stripe_id_2', 1, '00000000-0000-0000-0000-000000000002')
ON CONFLICT DO NOTHING;
---------------------------------
diff --git a/rust/cloud-storage/macro_db_client/fixtures/entity_filter_tests.sql b/rust/cloud-storage/macro_db_client/fixtures/entity_filter_tests.sql
index 9501e079a3..53d16713d0 100644
--- a/rust/cloud-storage/macro_db_client/fixtures/entity_filter_tests.sql
+++ b/rust/cloud-storage/macro_db_client/fixtures/entity_filter_tests.sql
@@ -10,9 +10,14 @@ INSERT INTO public."Organization" ("id", "name", "status")
VALUES (1, 'Test Organization', 'PILOT')
ON CONFLICT DO NOTHING;
+-- Insert macro_user
+INSERT INTO public.macro_user (id, username, email, stripe_customer_id)
+VALUES ('00000000-0000-0000-0000-000000000001', 'testuser1', '[email protected]', 'stripe_mu_1')
+ON CONFLICT DO NOTHING;
+
-- Insert user
-INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId")
-VALUES ('macro|[email protected]', '[email protected]', 'stripe_id_1', 1)
+INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId", "macro_user_id")
+VALUES ('macro|[email protected]', '[email protected]', 'stripe_id_1', 1, '00000000-0000-0000-0000-000000000001')
ON CONFLICT DO NOTHING;
---------------------------------
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
index f9bac4bc5f..387d17e95e 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
@@ -361,6 +361,9 @@ fn build_document_filter(ast: Option<&Expr<DocumentLiteral>>) -> String {
}
// false is equivalent to disabled/no-op.
filter_ast::ExprFrame::Literal(DocumentLiteral::IncludeCbmAtmNc(false)) => String::new(),
+ filter_ast::ExprFrame::Literal(DocumentLiteral::SubType(st)) => {
+ format!("dt.sub_type = '{st}'")
+ }
});
if formatting.is_empty() {
String::new()
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
index 21ea28c137..455ca2a4d0 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
@@ -5051,3 +5051,129 @@ async fn test_property_filter_scoped_entity_type(db: Pool<Postgres>) -> anyhow::
Ok(())
}
+
+// Test filtering documents by sub_type = task
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("entity_filter_tests")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_dyn_filter_by_document_sub_type_task(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{DocumentFilters, EntityFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ sub_types: vec!["task".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = expanded_dynamic_cursor_soup(
+ &db,
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 20,
+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ exclude_frecency: false,
+ },
+ )
+ .await?;
+
+ let mut task_doc_count = 0;
+ let mut non_task_doc_count = 0;
+ let mut chat_count = 0;
+ let mut project_count = 0;
+
+ for item in &items {
+ match item {
+ SoupItem::Document(doc) => {
+ if doc.sub_type.is_some() {
+ task_doc_count += 1;
+ } else {
+ non_task_doc_count += 1;
+ }
+ }
+ SoupItem::Chat(_) => chat_count += 1,
+ SoupItem::Project(_) => project_count += 1,
+ _ => unimplemented!("unexpected item type"),
+ }
+ }
+
+ // 3 accessible task documents: doc-in-A, doc-in-B, doc-in-C
+ assert_eq!(task_doc_count, 3, "Should get 3 task documents");
+ // No non-task documents should be returned since sub_type filter is applied
+ assert_eq!(non_task_doc_count, 0, "Should get 0 non-task documents");
+ // Chats and projects are unaffected by document filters
+ assert!(chat_count > 0, "Should still get chats");
+ assert!(project_count > 0, "Should still get projects");
+
+ Ok(())
+}
+
+// Test filtering documents by sub_type combined with file_type
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("entity_filter_tests")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_dyn_filter_by_sub_type_and_file_type(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{DocumentFilters, EntityFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Filter for task documents that are also PDFs
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ sub_types: vec!["task".to_string()],
+ file_types: vec!["pdf".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = expanded_dynamic_cursor_soup(
+ &db,
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 20,
+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ exclude_frecency: false,
+ },
+ )
+ .await?;
+
+ let doc_count = items
+ .iter()
+ .filter(|i| matches!(i, SoupItem::Document(_)))
+ .count();
+
+ // doc-in-A (task, pdf) and doc-in-B (task, pdf) match; doc-in-C is task but md
+ assert_eq!(
+ doc_count, 2,
+ "Should get 2 documents that are both tasks and PDFs"
+ );
+
+ for item in &items {
+ if let SoupItem::Document(doc) = item {
+ assert!(doc.sub_type.is_some(), "All docs should be tasks");
+ assert_eq!(
+ doc.file_type.as_deref(),
+ Some("pdf"),
+ "All docs should be PDFs"
+ );
+ }
+ }
+
+ Ok(())
+}