Skip to content

armgit / macro

Public Imported from GitHub
0

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

fix(soup): Improve dynamic query performance (#1366)

Evan Hutnik7e67ac4bf589
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
new file mode 100644
index 0000000000..97e0fe81e0
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/fixtures/dynamic_query_exhaustive.sql
@@ -0,0 +1,245 @@
+-- Exhaustive fixture for expanded_dynamic_cursor_soup tests.
+--
+-- Covers:
+-- - 3-level deep project hierarchy (root -> mid -> deep)
+-- - Deleted items (doc + chat) that must be excluded
+-- - Task documents with completed/incomplete/no-status states
+-- - Isolated project with no access for user-1
+-- - Second user for access isolation testing
+-- - Multi-owner items (user-2 owns doc/chat in user-1's project)
+-- - Standalone items (no project) with direct access
+-- - Frecency records on some items
+-- - Multiple file types (pdf, docx, txt, md)
+-- - Distinct timestamps for createdAt, updatedAt, and UserHistory.updatedAt
+-- so all four sort methods (viewed_at, updated_at, created_at, viewed_updated)
+-- produce different orderings.
+--
+-- User-1 accessible items (14 total):
+-- Projects: project-root, project-mid, project-deep (3)
+-- Documents: doc-root-pdf, doc-mid-docx, doc-deep-pdf, doc-standalone-txt,
+-- doc-task-completed, doc-task-incomplete, doc-task-no-status,
+-- doc-shared-md (8)
+-- Chats: chat-root, chat-standalone, chat-shared (3)
+--
+-- NOT accessible to user-1:
+-- doc-deleted (deletedAt set), chat-deleted (deletedAt set),
+-- doc-isolated, chat-isolated, project-isolated (no access)
+--
+-- User-2 accessible items (3 total):
+-- project-isolated, doc-isolated, chat-isolated
+
+SET session_replication_role = 'replica';
+
+---------------------------------
+-- BASE SETUP: USERS & ORG
+---------------------------------
+
+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)
+ON CONFLICT DO NOTHING;
+
+---------------------------------
+-- PROJECT HIERARCHY: root -> mid -> deep
+---------------------------------
+
+INSERT INTO public."Project" ("id", "name", "userId", "parentId", "createdAt", "updatedAt")
+VALUES
+ ('aa000001-ffff-ffff-ffff-ffffffffffff', 'Project Root', 'macro|[email protected]', NULL,
+ '2024-01-10 10:00:00', '2024-02-10 10:00:00'),
+ ('aa000002-ffff-ffff-ffff-ffffffffffff', 'Project Mid', 'macro|[email protected]', 'aa000001-ffff-ffff-ffff-ffffffffffff',
+ '2024-01-11 10:00:00', '2024-02-11 10:00:00'),
+ ('aa000003-ffff-ffff-ffff-ffffffffffff', 'Project Deep', 'macro|[email protected]', 'aa000002-ffff-ffff-ffff-ffffffffffff',
+ '2024-01-12 10:00:00', '2024-02-12 10:00:00'),
+ -- Isolated project: user-1 has NO access, user-2 has owner
+ ('aa000004-ffff-ffff-ffff-ffffffffffff', 'Project Isolated', 'macro|[email protected]', NULL,
+ '2024-01-13 10:00:00', '2024-02-13 10:00:00');
+
+---------------------------------
+-- DOCUMENTS (10 total)
+---------------------------------
+
+INSERT INTO public."DocumentFamily" ("id", "rootDocumentId")
+VALUES (101, 'bb000001-aaaa-aaaa-aaaa-aaaaaaaaaaaa'),
+ (102, 'bb000002-aaaa-aaaa-aaaa-aaaaaaaaaaaa'),
+ (103, 'bb000003-aaaa-aaaa-aaaa-aaaaaaaaaaaa'),
+ (104, 'bb000004-aaaa-aaaa-aaaa-aaaaaaaaaaaa'),
+ (105, 'bb000005-aaaa-aaaa-aaaa-aaaaaaaaaaaa'),
+ (106, 'bb000006-aaaa-aaaa-aaaa-aaaaaaaaaaaa'),
+ (107, 'bb000007-aaaa-aaaa-aaaa-aaaaaaaaaaaa'),
+ (108, 'bb000008-aaaa-aaaa-aaaa-aaaaaaaaaaaa'),
+ (109, 'bb000009-aaaa-aaaa-aaaa-aaaaaaaaaaaa'),
+ (110, 'bb000010-aaaa-aaaa-aaaa-aaaaaaaaaaaa');
+
+INSERT INTO public."Document" ("id", "name", "owner", "projectId", "documentFamilyId", "fileType", "createdAt", "updatedAt", "deletedAt")
+VALUES
+ -- doc-root-pdf: in root project, pdf, user-1
+ ('bb000001-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Doc Root Pdf', 'macro|[email protected]',
+ 'aa000001-ffff-ffff-ffff-ffffffffffff', 101, 'pdf',
+ '2024-01-01 10:00:00', '2024-02-01 10:00:00', NULL),
+ -- doc-mid-docx: in mid project, docx, user-1
+ ('bb000002-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Doc Mid Docx', 'macro|[email protected]',
+ 'aa000002-ffff-ffff-ffff-ffffffffffff', 102, 'docx',
+ '2024-01-02 10:00:00', '2024-02-02 10:00:00', NULL),
+ -- doc-deep-pdf: in deep project, pdf, user-1
+ ('bb000003-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Doc Deep Pdf', 'macro|[email protected]',
+ 'aa000003-ffff-ffff-ffff-ffffffffffff', 103, 'pdf',
+ '2024-01-03 10:00:00', '2024-03-10 10:00:00', NULL),
+ -- doc-standalone-txt: no project, txt, user-1
+ ('bb000004-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Doc Standalone Txt', 'macro|[email protected]',
+ NULL, 104, 'txt',
+ '2024-01-04 10:00:00', '2024-02-04 10:00:00', NULL),
+ -- doc-deleted: in root, pdf, user-1, DELETED
+ ('bb000005-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Doc Deleted', 'macro|[email protected]',
+ 'aa000001-ffff-ffff-ffff-ffffffffffff', 105, 'pdf',
+ '2024-01-15 10:00:00', '2024-02-15 10:00:00', '2024-03-01 10:00:00'),
+ -- doc-task-completed: in root, txt, user-1, task, completed, assigned to user-1
+ ('bb000006-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Doc Task Completed', 'macro|[email protected]',
+ 'aa000001-ffff-ffff-ffff-ffffffffffff', 106, 'txt',
+ '2024-01-05 10:00:00', '2024-02-05 10:00:00', NULL),
+ -- doc-task-incomplete: in root, txt, user-1, task, in-progress, assigned to other
+ ('bb000007-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Doc Task Incomplete', 'macro|[email protected]',
+ 'aa000001-ffff-ffff-ffff-ffffffffffff', 107, 'txt',
+ '2024-01-06 10:00:00', '2024-02-06 10:00:00', NULL),
+ -- doc-task-no-status: in root, txt, user-1, task, no status, no assignee
+ ('bb000008-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Doc Task No Status', 'macro|[email protected]',
+ 'aa000001-ffff-ffff-ffff-ffffffffffff', 108, 'txt',
+ '2024-01-07 10:00:00', '2024-02-07 10:00:00', NULL),
+ -- doc-isolated: in isolated project, pdf, user-2
+ ('bb000009-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Doc Isolated', 'macro|[email protected]',
+ 'aa000004-ffff-ffff-ffff-ffffffffffff', 109, 'pdf',
+ '2024-01-14 10:00:00', '2024-02-14 10:00:00', NULL),
+ -- doc-shared-md: in root project, md, owned by user-2 (accessible to user-1 via project)
+ ('bb000010-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Doc Shared Md', 'macro|[email protected]',
+ 'aa000001-ffff-ffff-ffff-ffffffffffff', 110, 'md',
+ '2024-01-08 10:00:00', '2024-02-08 10:00:00', NULL);
+
+INSERT INTO public."DocumentInstance" ("documentId", "sha")
+VALUES ('bb000001-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'sha-root-pdf'),
+ ('bb000002-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'sha-mid-docx'),
+ ('bb000003-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'sha-deep-pdf'),
+ ('bb000004-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'sha-standalone-txt'),
+ ('bb000005-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'sha-deleted'),
+ ('bb000006-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'sha-task-completed'),
+ ('bb000007-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'sha-task-incomplete'),
+ ('bb000008-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'sha-task-no-status'),
+ ('bb000009-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'sha-isolated'),
+ ('bb000010-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'sha-shared-md');
+
+---------------------------------
+-- CHATS (5 total)
+---------------------------------
+
+INSERT INTO public."Chat" ("id", "name", "userId", "projectId", "createdAt", "updatedAt", "deletedAt")
+VALUES
+ -- chat-root: in root project, user-1
+ ('cc000001-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Chat Root', 'macro|[email protected]',
+ 'aa000001-ffff-ffff-ffff-ffffffffffff',
+ '2024-01-08 10:00:00', '2024-02-09 10:00:00', NULL),
+ -- chat-standalone: no project, user-1
+ ('cc000002-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Chat Standalone', 'macro|[email protected]',
+ NULL,
+ '2024-01-09 10:00:00', '2024-03-11 10:00:00', NULL),
+ -- chat-deleted: in root, user-1, DELETED
+ ('cc000003-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Chat Deleted', 'macro|[email protected]',
+ 'aa000001-ffff-ffff-ffff-ffffffffffff',
+ '2024-01-16 10:00:00', '2024-02-16 10:00:00', '2024-03-02 10:00:00'),
+ -- chat-isolated: in isolated project, user-2
+ ('cc000004-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Chat Isolated', 'macro|[email protected]',
+ 'aa000004-ffff-ffff-ffff-ffffffffffff',
+ '2024-01-17 10:00:00', '2024-02-17 10:00:00', NULL),
+ -- chat-shared: in root project, owned by user-2 (accessible to user-1 via project)
+ ('cc000005-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Chat Shared', 'macro|[email protected]',
+ 'aa000001-ffff-ffff-ffff-ffffffffffff',
+ '2024-01-18 10:00:00', '2024-02-18 10:00:00', NULL);
+
+---------------------------------
+-- TASK SUB-TYPES
+---------------------------------
+
+INSERT INTO public."document_sub_type" ("document_id", "sub_type")
+VALUES ('bb000006-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'task'),
+ ('bb000007-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'task'),
+ ('bb000008-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'task');
+
+-- Entity properties: Status for completed task
+INSERT INTO public."entity_properties" ("id", "entity_id", "entity_type", "property_definition_id", "values")
+VALUES
+ -- Completed task: Status = Completed
+ (gen_random_uuid(), 'bb000006-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'TASK',
+ '00000001-0000-0000-0000-000000000002',
+ '{"type": "SelectOption", "value": ["00000001-0000-0000-0002-000000000004"]}'::jsonb),
+ -- Incomplete task: Status = In Progress
+ (gen_random_uuid(), 'bb000007-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'TASK',
+ '00000001-0000-0000-0000-000000000002',
+ '{"type": "SelectOption", "value": ["00000001-0000-0000-0002-000000000002"]}'::jsonb);
+-- No entity_properties for doc-task-no-status (to test false case)
+
+---------------------------------
+-- USER ACCESS PERMISSIONS
+---------------------------------
+
+INSERT INTO public."UserItemAccess" ("id", "user_id", "item_id", "item_type", "access_level")
+VALUES
+ -- user-1: owner on project-root (inherits to mid, deep, and all items therein)
+ (gen_random_uuid(), 'macro|[email protected]', 'aa000001-ffff-ffff-ffff-ffffffffffff', 'project', 'owner'),
+ -- user-1: direct access to standalone items
+ (gen_random_uuid(), 'macro|[email protected]', 'bb000004-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'document', 'owner'),
+ (gen_random_uuid(), 'macro|[email protected]', 'cc000002-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'chat', 'owner'),
+ -- user-2: owner on isolated project
+ (gen_random_uuid(), 'macro|[email protected]', 'aa000004-ffff-ffff-ffff-ffffffffffff', 'project', 'owner');
+
+---------------------------------
+-- USER HISTORY
+-- Designed so all 4 sort methods produce different orderings.
+-- Items WITHOUT history:
+-- doc-deep-pdf (high updatedAt 2024-03-10, no history)
+-- doc-task-incomplete (updatedAt 2024-02-06, no history)
+-- chat-standalone (high updatedAt 2024-03-11, no history)
+-- project-mid (updatedAt 2024-02-11, no history)
+-- doc-shared-md (updatedAt 2024-02-08, no history)
+-- chat-shared (updatedAt 2024-02-18, no history)
+---------------------------------
+
+INSERT INTO public."UserHistory" ("userId", "itemId", "itemType", "createdAt", "updatedAt")
+VALUES
+ -- doc-root-pdf: viewed_at = 2024-03-05
+ ('macro|[email protected]', 'bb000001-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'document',
+ '2024-01-01 00:00:00', '2024-03-05 10:00:00'),
+ -- doc-mid-docx: viewed_at = 2024-03-08
+ ('macro|[email protected]', 'bb000002-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'document',
+ '2024-01-01 00:00:00', '2024-03-08 10:00:00'),
+ -- doc-standalone-txt: viewed_at = 2024-03-06
+ ('macro|[email protected]', 'bb000004-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'document',
+ '2024-01-01 00:00:00', '2024-03-06 10:00:00'),
+ -- doc-task-completed: viewed_at = 2024-03-04
+ ('macro|[email protected]', 'bb000006-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'document',
+ '2024-01-01 00:00:00', '2024-03-04 10:00:00'),
+ -- doc-task-no-status: viewed_at = 2024-03-07
+ ('macro|[email protected]', 'bb000008-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'document',
+ '2024-01-01 00:00:00', '2024-03-07 10:00:00'),
+ -- chat-root: viewed_at = 2024-03-03
+ ('macro|[email protected]', 'cc000001-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'chat',
+ '2024-01-01 00:00:00', '2024-03-03 10:00:00'),
+ -- project-root: viewed_at = 2024-03-02
+ ('macro|[email protected]', 'aa000001-ffff-ffff-ffff-ffffffffffff', 'project',
+ '2024-01-01 00:00:00', '2024-03-02 10:00:00'),
+ -- project-deep: viewed_at = 2024-03-01
+ ('macro|[email protected]', 'aa000003-ffff-ffff-ffff-ffffffffffff', 'project',
+ '2024-01-01 00:00:00', '2024-03-01 10:00:00');
+
+---------------------------------
+-- FRECENCY RECORDS
+-- doc-root-pdf and chat-root have frecency for user-1
+---------------------------------
+
+INSERT INTO public."frecency_aggregates" ("entity_id", "entity_type", "user_id", "event_count", "frecency_score", "first_event", "recent_events")
+VALUES
+ ('bb000001-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'document', 'macro|[email protected]', 5, 10.0, '2024-01-01 10:00:00', '[]'::jsonb),
+ ('cc000001-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'chat', 'macro|[email protected]', 3, 8.0, '2024-01-08 10:00:00', '[]'::jsonb);
+
+SET session_replication_role = 'origin';
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 199db19757..219aab564b 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
@@ -26,41 +26,42 @@ use crate::outbound::pg_soup_repo::{populate_properties, type_err};
static PREFIX: &str = r#"
WITH RECURSIVE ProjectHierarchy AS (
- SELECT p.id, uia.access_level
+ SELECT p.id, uia.access_level
FROM "Project" p
JOIN "UserItemAccess" uia ON p.id = uia.item_id AND uia.item_type = 'project'
WHERE uia.user_id = $1 AND p."deletedAt" IS NULL
UNION ALL
SELECT p.id, ph.access_level
- FROM "Project" p
+ FROM "Project" p
JOIN ProjectHierarchy ph ON p."parentId" = ph.id
WHERE p."deletedAt" IS NULL
),
AllAccessGrants AS (
- SELECT item_id, item_type, access_level
- FROM "UserItemAccess"
+ SELECT item_id, item_type, access_level
+ FROM "UserItemAccess"
WHERE user_id = $1
UNION ALL
- SELECT d.id AS item_id, 'document' AS item_type, ph.access_level
- FROM "Document" d
- JOIN ProjectHierarchy ph ON d."projectId" = ph.id
- WHERE d."projectId" IS NOT NULL AND d."deletedAt" IS NULL
+ SELECT d.id AS item_id, 'document' AS item_type,
+ (SELECT ph.access_level FROM ProjectHierarchy ph WHERE ph.id = d."projectId" LIMIT 1) as access_level
+ FROM "Document" d
+ WHERE d."projectId" = ANY(ARRAY(SELECT id FROM ProjectHierarchy))
+ AND d."deletedAt" IS NULL
UNION ALL
SELECT c.id AS item_id, 'chat' AS item_type, ph.access_level
- FROM "Chat" c
+ FROM "Chat" c
JOIN ProjectHierarchy ph ON c."projectId" = ph.id
WHERE c."projectId" IS NOT NULL AND c."deletedAt" IS NULL
UNION ALL
- SELECT ph.id AS item_id, 'project' AS item_type, ph.access_level
+ SELECT ph.id AS item_id, 'project' AS item_type, ph.access_level
FROM ProjectHierarchy ph
),
UserAccessibleItems AS (
SELECT DISTINCT ON (item_id, item_type) item_id, item_type
FROM AllAccessGrants
- ORDER BY item_id, item_type,
+ ORDER BY item_id, item_type,
CASE access_level
WHEN 'owner' THEN 4
- WHEN 'edit' THEN 3
+ WHEN 'edit' THEN 3
WHEN 'comment' THEN 2
WHEN 'view' THEN 1
ELSE 0
@@ -68,163 +69,186 @@ static PREFIX: &str = r#"
),
"#;
-static DOCUMENT_CLAUSE: &str = r#"
- SELECT
- 'document' as "item_type",
- d.id as "id",
- CAST(COALESCE(di.id, db.id) as TEXT) as "document_version_id",
- d.owner as "user_id",
- d.name as "name",
- d."branchedFromId" as "branched_from_id",
- d."branchedFromVersionId" as "branched_from_version_id",
- d."documentFamilyId" as "document_family_id",
- d."fileType" as "file_type",
- d."createdAt"::timestamptz as "created_at",
- d."updatedAt"::timestamptz as "updated_at",
- d."projectId" as "project_id",
- NULL as "is_persistent",
- di.sha as "sha",
- dt.sub_type as "sub_type",
- uh."updatedAt"::timestamptz as "viewed_at",
- CASE $2
- WHEN 'viewed_updated' THEN COALESCE(uh."updatedAt", d."updatedAt")
- WHEN 'viewed_at' THEN COALESCE(uh."updatedAt", '1970-01-01 00:00:00+00')
- WHEN 'created_at' THEN d."createdAt"
- ELSE d."updatedAt"
- END::timestamptz as "sort_ts",
- CASE
- WHEN dt.sub_type = 'task'
- AND ep_status.values->'value' ? $6
- THEN true
- WHEN dt.sub_type = 'task'
- THEN false
- ELSE NULL
- END as "is_completed",
- d."deletedAt"::timestamptz as "deleted_at"
- FROM "Document" d
- LEFT JOIN document_sub_type dt ON dt.document_id = d.id
- LEFT JOIN entity_properties ep_status
- ON dt.sub_type = 'task'
- AND ep_status.entity_id = d.id
- AND ep_status.entity_type = 'TASK'
- AND ep_status.property_definition_id = $7
- LEFT JOIN entity_properties ep_assignees
- ON dt.sub_type = 'task'
- AND ep_assignees.entity_id = d.id
- AND ep_assignees.entity_type = 'TASK'
- AND ep_assignees.property_definition_id = $8
- INNER JOIN UserAccessibleItems uai ON uai.item_id = d.id AND uai.item_type = 'document'
- -- This MUST be a LEFT JOIN to support all three sort methods
- LEFT JOIN "UserHistory" uh ON uh."itemId" = d.id AND uh."itemType" = 'document' AND uh."userId" = $1
- LEFT JOIN LATERAL (
- SELECT b.id
- FROM "DocumentBom" b
- WHERE b."documentId" = d.id
- ORDER BY b."createdAt" DESC
- LIMIT 1
- ) db ON true
- LEFT JOIN LATERAL (
- SELECT i.id, i.sha
- FROM "DocumentInstance" i
- WHERE i."documentId" = d.id
- ORDER BY i."updatedAt" DESC
- LIMIT 1
- ) di ON true
- WHERE d."deletedAt" IS NULL
+// -- Lightweight top clauses: only id + sort_ts (plus filter-required joins) --
+
+static DOCUMENT_TOP_CLAUSE: &str = r#"
+ SELECT
+ 'document'::text as item_type,
+ d.id,
+ CASE $2
+ WHEN 'viewed_updated' THEN COALESCE(uh."updatedAt", d."updatedAt")
+ WHEN 'viewed_at' THEN COALESCE(uh."updatedAt", '1970-01-01 00:00:00+00')
+ WHEN 'created_at' THEN d."createdAt"
+ ELSE d."updatedAt"
+ END::timestamptz as sort_ts
+ FROM "Document" d
+ LEFT JOIN document_sub_type dt ON dt.document_id = d.id
+ LEFT JOIN entity_properties ep_assignees
+ ON dt.sub_type = 'task'
+ AND ep_assignees.entity_id = d.id
+ AND ep_assignees.entity_type = 'TASK'
+ AND ep_assignees.property_definition_id = $8
+ INNER JOIN UserAccessibleItems uai ON uai.item_id = d.id AND uai.item_type = 'document'
+ LEFT JOIN "UserHistory" uh ON uh."itemId" = d.id AND uh."itemType" = 'document' AND uh."userId" = $1
+ WHERE d."deletedAt" IS NULL
"#;
-static CHAT_CLAUSE: &str = r#"
- SELECT
- 'chat' as "item_type",
- c.id as "id",
- NULL as "document_version_id",
- c."userId" as "user_id",
- c.name as "name",
- NULL as "branched_from_id",
- NULL as "branched_from_version_id",
- NULL as "document_family_id",
- NULL as "file_type",
- c."createdAt"::timestamptz as "created_at",
- c."updatedAt"::timestamptz as "updated_at",
- c."projectId" as "project_id",
- c."isPersistent" as "is_persistent",
- NULL as "sha",
- NULL as "sub_type",
- uh."updatedAt"::timestamptz as "viewed_at",
- CASE $2
- WHEN 'viewed_updated' THEN COALESCE(uh."updatedAt", c."updatedAt")
- WHEN 'viewed_at' THEN COALESCE(uh."updatedAt", '1970-01-01 00:00:00+00')
- WHEN 'created_at' THEN c."createdAt"
- ELSE c."updatedAt"
- END::timestamptz as "sort_ts",
- NULL as "is_completed",
- c."deletedAt"::timestamptz as "deleted_at"
- FROM "Chat" c
- INNER JOIN UserAccessibleItems uai ON uai.item_id = c.id AND uai.item_type = 'chat'
- LEFT JOIN "UserHistory" uh ON uh."itemId" = c.id AND uh."itemType" = 'chat' AND uh."userId" = $1
- WHERE c."deletedAt" IS NULL
+static CHAT_TOP_CLAUSE: &str = r#"
+ SELECT
+ 'chat'::text as item_type,
+ c.id,
+ CASE $2
+ WHEN 'viewed_updated' THEN COALESCE(uh."updatedAt", c."updatedAt")
+ WHEN 'viewed_at' THEN COALESCE(uh."updatedAt", '1970-01-01 00:00:00+00')
+ WHEN 'created_at' THEN c."createdAt"
+ ELSE c."updatedAt"
+ END::timestamptz as sort_ts
+ FROM "Chat" c
+ INNER JOIN UserAccessibleItems uai ON uai.item_id = c.id AND uai.item_type = 'chat'
+ LEFT JOIN "UserHistory" uh ON uh."itemId" = c.id AND uh."itemType" = 'chat' AND uh."userId" = $1
+ WHERE c."deletedAt" IS NULL
"#;
-static PROJECT_CLAUSE: &str = r#"
- SELECT
- 'project' as "item_type",
- p.id as "id",
- NULL as "document_version_id",
- p."userId" as "user_id",
- p.name as "name",
- NULL as "branched_from_id",
- NULL as "branched_from_version_id",
- NULL as "document_family_id",
- NULL as "file_type",
- p."createdAt"::timestamptz as "created_at",
- p."updatedAt"::timestamptz as "updated_at",
- p."parentId" as "project_id",
- NULL as "is_persistent",
- NULL as "sha",
- NULL as "sub_type",
- uh."updatedAt"::timestamptz as "viewed_at",
- CASE $2
- WHEN 'viewed_updated' THEN COALESCE(uh."updatedAt", p."updatedAt")
- WHEN 'viewed_at' THEN COALESCE(uh."updatedAt", '1970-01-01 00:00:00+00')
- WHEN 'created_at' THEN p."createdAt"
- ELSE p."updatedAt"
- END::timestamptz as "sort_ts",
- NULL as "is_completed",
- p."deletedAt"::timestamptz as "deleted_at"
- FROM "Project" p
- INNER JOIN UserAccessibleItems uai
- ON uai.item_id = p.id
- AND uai.item_type = 'project'
- LEFT JOIN "UserHistory" uh
- ON uh."itemId" = p.id
- AND uh."itemType" = 'project'
- AND uh."userId" = $1
- WHERE p."deletedAt" IS NULL
+static PROJECT_TOP_CLAUSE: &str = r#"
+ SELECT
+ 'project'::text as item_type,
+ p.id,
+ CASE $2
+ WHEN 'viewed_updated' THEN COALESCE(uh."updatedAt", p."updatedAt")
+ WHEN 'viewed_at' THEN COALESCE(uh."updatedAt", '1970-01-01 00:00:00+00')
+ WHEN 'created_at' THEN p."createdAt"
+ ELSE p."updatedAt"
+ END::timestamptz as sort_ts
+ FROM "Project" p
+ INNER JOIN UserAccessibleItems uai
+ ON uai.item_id = p.id
+ AND uai.item_type = 'project'
+ LEFT JOIN "UserHistory" uh
+ ON uh."itemId" = p.id
+ AND uh."itemType" = 'project'
+ AND uh."userId" = $1
+ WHERE p."deletedAt" IS NULL
"#;
-static SUFFIX: &str = r#"
- SELECT * FROM Combined
- WHERE
- ($4::timestamptz IS NULL)
- OR
- ("sort_ts", "id"::text) < ($4, $5)
- ORDER BY "sort_ts" DESC, "id" DESC
- LIMIT $3
+// -- Detail clauses: full columns, joined back from TopItems --
+
+static DOCUMENT_DETAIL_CLAUSE: &str = r#"
+ SELECT
+ 'document' as "item_type",
+ d.id as "id",
+ CAST(COALESCE(di.id, db.id) as TEXT) as "document_version_id",
+ d.owner as "user_id",
+ d.name as "name",
+ d."branchedFromId" as "branched_from_id",
+ d."branchedFromVersionId" as "branched_from_version_id",
+ d."documentFamilyId" as "document_family_id",
+ d."fileType" as "file_type",
+ d."createdAt"::timestamptz as "created_at",
+ d."updatedAt"::timestamptz as "updated_at",
+ d."projectId" as "project_id",
+ NULL as "is_persistent",
+ di.sha as "sha",
+ dt.sub_type as "sub_type",
+ uh."updatedAt"::timestamptz as "viewed_at",
+ t.sort_ts as "sort_ts",
+ CASE
+ WHEN dt.sub_type = 'task'
+ AND ep_status.values->'value' ? $6
+ THEN true
+ WHEN dt.sub_type = 'task'
+ THEN false
+ ELSE NULL
+ END as "is_completed",
+ d."deletedAt"::timestamptz as "deleted_at"
+ FROM TopItems t
+ INNER JOIN "Document" d ON d.id = t.id
+ LEFT JOIN document_sub_type dt ON dt.document_id = d.id
+ LEFT JOIN entity_properties ep_status
+ ON dt.sub_type = 'task'
+ AND ep_status.entity_id = d.id
+ AND ep_status.entity_type = 'TASK'
+ AND ep_status.property_definition_id = $7
+ LEFT JOIN "UserHistory" uh
+ ON uh."itemId" = d.id AND uh."itemType" = 'document' AND uh."userId" = $1
+ LEFT JOIN LATERAL (
+ SELECT b.id
+ FROM "DocumentBom" b
+ WHERE b."documentId" = d.id
+ ORDER BY b."createdAt" DESC
+ LIMIT 1
+ ) db ON true
+ LEFT JOIN LATERAL (
+ SELECT i.id, i.sha
+ FROM "DocumentInstance" i
+ WHERE i."documentId" = d.id
+ ORDER BY i."updatedAt" DESC
+ LIMIT 1
+ ) di ON true
+ WHERE t.item_type = 'document'
"#;
-static SUFFIX_NO_FRECENCY: &str = r#"
- SELECT Combined.* FROM Combined
- LEFT JOIN frecency_aggregates fa
- ON fa.entity_id = Combined."id"
- AND fa.entity_type = Combined."item_type"
- AND fa.user_id = $1
- WHERE fa.id IS NULL
- AND (
- ($4::timestamptz IS NULL)
- OR
- (Combined."sort_ts", Combined."id"::text) < ($4, $5)
- )
- ORDER BY Combined."sort_ts" DESC, Combined."id" DESC
+static CHAT_DETAIL_CLAUSE: &str = r#"
+ SELECT
+ 'chat' as "item_type",
+ c.id as "id",
+ NULL as "document_version_id",
+ c."userId" as "user_id",
+ c.name as "name",
+ NULL as "branched_from_id",
+ NULL as "branched_from_version_id",
+ NULL as "document_family_id",
+ NULL as "file_type",
+ c."createdAt"::timestamptz as "created_at",
+ c."updatedAt"::timestamptz as "updated_at",
+ c."projectId" as "project_id",
+ c."isPersistent" as "is_persistent",
+ NULL as "sha",
+ NULL as "sub_type",
+ uh."updatedAt"::timestamptz as "viewed_at",
+ t.sort_ts as "sort_ts",
+ NULL as "is_completed",
+ c."deletedAt"::timestamptz as "deleted_at"
+ FROM TopItems t
+ INNER JOIN "Chat" c ON c.id = t.id
+ LEFT JOIN "UserHistory" uh
+ ON uh."itemId" = c.id AND uh."itemType" = 'chat' AND uh."userId" = $1
+ WHERE t.item_type = 'chat'
+"#;
+
+static PROJECT_DETAIL_CLAUSE: &str = r#"
+ SELECT
+ 'project' as "item_type",
+ p.id as "id",
+ NULL as "document_version_id",
+ p."userId" as "user_id",
+ p.name as "name",
+ NULL as "branched_from_id",
+ NULL as "branched_from_version_id",
+ NULL as "document_family_id",
+ NULL as "file_type",
+ p."createdAt"::timestamptz as "created_at",
+ p."updatedAt"::timestamptz as "updated_at",
+ p."parentId" as "project_id",
+ NULL as "is_persistent",
+ NULL as "sha",
+ NULL as "sub_type",
+ uh."updatedAt"::timestamptz as "viewed_at",
+ t.sort_ts as "sort_ts",
+ NULL as "is_completed",
+ p."deletedAt"::timestamptz as "deleted_at"
+ FROM TopItems t
+ INNER JOIN "Project" p ON p.id = t.id
+ LEFT JOIN "UserHistory" uh
+ ON uh."itemId" = p.id
+ AND uh."itemType" = 'project'
+ AND uh."userId" = $1
+ WHERE t.item_type = 'project'
+"#;
+
+static DETAIL_SUFFIX: &str = r#"
+ )
+ SELECT * FROM Combined
+ ORDER BY "sort_ts" DESC, "id" DESC
LIMIT $3
"#;
@@ -323,32 +347,67 @@ fn build_project_filter(ast: Option<&Expr<ProjectLiteral>>) -> String {
fn build_query(filter_ast: &EntityFilterAst, exclude_frecency: bool) -> QueryBuilder<'_, Postgres> {
let mut builder = sqlx::QueryBuilder::new(PREFIX);
- builder.push("Combined AS (");
- // Document clause
- builder.push(DOCUMENT_CLAUSE);
+ // TopItems CTE: lightweight id + sort_ts with filters, cursor, and limit
+ builder.push("TopItems AS (");
+ builder.push("SELECT all_items.item_type, all_items.id, all_items.sort_ts FROM (");
+
+ // Document top clause (lightweight)
+ builder.push(DOCUMENT_TOP_CLAUSE);
builder.push(build_document_filter(filter_ast.document_filter.as_deref()));
builder.push(" UNION ALL ");
- // Chat clause
- builder.push(CHAT_CLAUSE);
+ // Chat top clause (lightweight)
+ builder.push(CHAT_TOP_CLAUSE);
builder.push(build_chat_filter(filter_ast.chat_filter.as_deref()));
builder.push(" UNION ALL ");
- // Project clause
- builder.push(PROJECT_CLAUSE);
+ // Project top clause (lightweight)
+ builder.push(PROJECT_TOP_CLAUSE);
builder.push(build_project_filter(filter_ast.project_filter.as_deref()));
- builder.push(") ");
+ builder.push(") all_items ");
+ // Frecency exclusion join (only when exclude_frecency is true)
if exclude_frecency {
- builder.push(SUFFIX_NO_FRECENCY);
+ builder.push(
+ r#"LEFT JOIN frecency_aggregates fa
+ ON fa.entity_id = all_items.id
+ AND fa.entity_type = all_items.item_type
+ AND fa.user_id = $1
+ WHERE fa.id IS NULL AND ("#,
+ );
} else {
- builder.push(SUFFIX);
+ builder.push("WHERE ");
}
+ // Cursor condition
+ builder.push(
+ r#"($4::timestamptz IS NULL)
+ OR
+ (all_items.sort_ts, all_items.id::text) < ($4, $5)"#,
+ );
+
+ if exclude_frecency {
+ builder.push(")");
+ }
+
+ builder.push(" ORDER BY all_items.sort_ts DESC, all_items.id DESC LIMIT $3");
+ builder.push("), ");
+
+ // Combined CTE: full detail joins back from TopItems
+ builder.push("Combined AS (");
+
+ builder.push(DOCUMENT_DETAIL_CLAUSE);
+ builder.push(" UNION ALL ");
+ builder.push(CHAT_DETAIL_CLAUSE);
+ builder.push(" UNION ALL ");
+ builder.push(PROJECT_DETAIL_CLAUSE);
+
+ builder.push(DETAIL_SUFFIX);
+
builder
}
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 34c8d9fc9b..f2a6b38ff5 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
@@ -3401,3 +3401,1014 @@ async fn test_exhaustive_entity_type_counts(pool: Pool<Postgres>) -> anyhow::Res
Ok(())
}
+
+// ============================================================================
+// Exhaustive expanded_dynamic_cursor_soup tests
+// Uses dynamic_query_exhaustive fixture.
+// ============================================================================
+
+// Fixture constants for dynamic_query_exhaustive
+const DYN_PROJECT_ROOT: &str = "aa000001-ffff-ffff-ffff-ffffffffffff";
+const DYN_PROJECT_MID: &str = "aa000002-ffff-ffff-ffff-ffffffffffff";
+const DYN_PROJECT_DEEP: &str = "aa000003-ffff-ffff-ffff-ffffffffffff";
+const DYN_PROJECT_ISOLATED: &str = "aa000004-ffff-ffff-ffff-ffffffffffff";
+const DYN_DOC_ROOT_PDF: &str = "bb000001-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const DYN_DOC_MID_DOCX: &str = "bb000002-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const DYN_DOC_DEEP_PDF: &str = "bb000003-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const DYN_DOC_STANDALONE_TXT: &str = "bb000004-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const DYN_DOC_DELETED: &str = "bb000005-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const DYN_DOC_TASK_COMPLETED: &str = "bb000006-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const DYN_DOC_TASK_INCOMPLETE: &str = "bb000007-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const DYN_DOC_TASK_NO_STATUS: &str = "bb000008-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const DYN_DOC_ISOLATED: &str = "bb000009-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const DYN_DOC_SHARED_MD: &str = "bb000010-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const DYN_CHAT_ROOT: &str = "cc000001-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const DYN_CHAT_STANDALONE: &str = "cc000002-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const DYN_CHAT_DELETED: &str = "cc000003-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const DYN_CHAT_ISOLATED: &str = "cc000004-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const DYN_CHAT_SHARED: &str = "cc000005-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+
+/// Helper to call expanded_dynamic_cursor_soup with common defaults
+async fn dyn_fetch(
+ db: &PgPool,
+ user: &str,
+ limit: u16,
+ sort: SimpleSortMethod,
+ filters: EntityFilterAst,
+ exclude_frecency: bool,
+) -> Result<Vec<SoupItem>, sqlx::Error> {
+ let user_id = MacroUserIdStr::parse_from_str(user).unwrap();
+ expanded_dynamic_cursor_soup(
+ db,
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit,
+ cursor: Query::Sort(sort, filters),
+ exclude_frecency,
+ },
+ )
+ .await
+}
+
+// ---- Sort methods (4 tests) ----
+
+/// 1. Verify UpdatedAt sort order through the dynamic query.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("dynamic_query_exhaustive")
+ )
+)]
+async fn test_dyn_sort_updated_at(db: PgPool) -> anyhow::Result<()> {
+ let items = dyn_fetch(
+ &db,
+ 50,
+ SimpleSortMethod::UpdatedAt,
+ EntityFilterAst::mock_empty(),
+ false,
+ )
+ .await?;
+
+ let ids: Vec<Uuid> = items.iter().map(|i| i.id()).collect();
+
+ // updatedAt DESC:
+ // chat-standalone 2024-03-11
+ // doc-deep-pdf 2024-03-10
+ // chat-shared 2024-02-18
+ // project-deep 2024-02-12
+ // project-mid 2024-02-11
+ // project-root 2024-02-10
+ // chat-root 2024-02-09
+ // doc-shared-md 2024-02-08
+ // doc-task-no-status 2024-02-07
+ // doc-task-incomplete 2024-02-06
+ // doc-task-completed 2024-02-05
+ // doc-standalone-txt 2024-02-04
+ // doc-mid-docx 2024-02-02
+ // doc-root-pdf 2024-02-01
+ let expected: Vec<Uuid> = [
+ DYN_CHAT_STANDALONE,
+ DYN_DOC_DEEP_PDF,
+ DYN_CHAT_SHARED,
+ DYN_PROJECT_DEEP,
+ DYN_PROJECT_MID,
+ DYN_PROJECT_ROOT,
+ DYN_CHAT_ROOT,
+ DYN_DOC_SHARED_MD,
+ DYN_DOC_TASK_NO_STATUS,
+ DYN_DOC_TASK_INCOMPLETE,
+ DYN_DOC_TASK_COMPLETED,
+ DYN_DOC_STANDALONE_TXT,
+ DYN_DOC_MID_DOCX,
+ DYN_DOC_ROOT_PDF,
+ ]
+ .iter()
+ .map(|s| uuid(s))
+ .collect();
+
+ assert_eq!(ids, expected, "UpdatedAt sort order is wrong");
+ Ok(())
+}
+
+/// 2. Verify CreatedAt sort order through the dynamic query.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("dynamic_query_exhaustive")
+ )
+)]
+async fn test_dyn_sort_created_at(db: PgPool) -> anyhow::Result<()> {
+ let items = dyn_fetch(
+ &db,
+ 50,
+ SimpleSortMethod::CreatedAt,
+ EntityFilterAst::mock_empty(),
+ false,
+ )
+ .await?;
+
+ let ids: Vec<Uuid> = items.iter().map(|i| i.id()).collect();
+
+ // createdAt DESC:
+ // chat-shared 2024-01-18
+ // project-deep 2024-01-12
+ // project-mid 2024-01-11
+ // project-root 2024-01-10
+ // chat-standalone 2024-01-09
+ // chat-root 2024-01-08 (id cc000001 > bb000010)
+ // doc-shared-md 2024-01-08
+ // doc-task-no-status 2024-01-07
+ // doc-task-incomplete 2024-01-06
+ // doc-task-completed 2024-01-05
+ // doc-standalone-txt 2024-01-04
+ // doc-deep-pdf 2024-01-03
+ // doc-mid-docx 2024-01-02
+ // doc-root-pdf 2024-01-01
+ let expected: Vec<Uuid> = [
+ DYN_CHAT_SHARED,
+ DYN_PROJECT_DEEP,
+ DYN_PROJECT_MID,
+ DYN_PROJECT_ROOT,
+ DYN_CHAT_STANDALONE,
+ DYN_CHAT_ROOT,
+ DYN_DOC_SHARED_MD,
+ DYN_DOC_TASK_NO_STATUS,
+ DYN_DOC_TASK_INCOMPLETE,
+ DYN_DOC_TASK_COMPLETED,
+ DYN_DOC_STANDALONE_TXT,
+ DYN_DOC_DEEP_PDF,
+ DYN_DOC_MID_DOCX,
+ DYN_DOC_ROOT_PDF,
+ ]
+ .iter()
+ .map(|s| uuid(s))
+ .collect();
+
+ assert_eq!(ids, expected, "CreatedAt sort order is wrong");
+ Ok(())
+}
+
+/// 3. Verify ViewedAt sort order through the dynamic query.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("dynamic_query_exhaustive")
+ )
+)]
+async fn test_dyn_sort_viewed_at(db: PgPool) -> anyhow::Result<()> {
+ let items = dyn_fetch(
+ &db,
+ 50,
+ SimpleSortMethod::ViewedAt,
+ EntityFilterAst::mock_empty(),
+ false,
+ )
+ .await?;
+
+ let ids: Vec<Uuid> = items.iter().map(|i| i.id()).collect();
+
+ // With history (UserHistory.updatedAt DESC):
+ // doc-mid-docx 2024-03-08
+ // doc-task-no-status 2024-03-07
+ // doc-standalone-txt 2024-03-06
+ // doc-root-pdf 2024-03-05
+ // doc-task-completed 2024-03-04
+ // chat-root 2024-03-03
+ // project-root 2024-03-02
+ // project-deep 2024-03-01
+ // Without history (epoch, tie by id DESC):
+ // cc000005 chat-shared
+ // cc000002 chat-standalone
+ // bb000010 doc-shared-md
+ // bb000007 doc-task-incomplete
+ // bb000003 doc-deep-pdf
+ // aa000002 project-mid
+ let expected: Vec<Uuid> = [
+ DYN_DOC_MID_DOCX,
+ DYN_DOC_TASK_NO_STATUS,
+ DYN_DOC_STANDALONE_TXT,
+ DYN_DOC_ROOT_PDF,
+ DYN_DOC_TASK_COMPLETED,
+ DYN_CHAT_ROOT,
+ DYN_PROJECT_ROOT,
+ DYN_PROJECT_DEEP,
+ DYN_CHAT_SHARED,
+ DYN_CHAT_STANDALONE,
+ DYN_DOC_SHARED_MD,
+ DYN_DOC_TASK_INCOMPLETE,
+ DYN_DOC_DEEP_PDF,
+ DYN_PROJECT_MID,
+ ]
+ .iter()
+ .map(|s| uuid(s))
+ .collect();
+
+ assert_eq!(ids, expected, "ViewedAt sort order is wrong");
+ Ok(())
+}
+
+/// 4. Verify ViewedUpdated sort order through the dynamic query.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("dynamic_query_exhaustive")
+ )
+)]
+async fn test_dyn_sort_viewed_updated(db: PgPool) -> anyhow::Result<()> {
+ let items = dyn_fetch(
+ &db,
+ 50,
+ SimpleSortMethod::ViewedUpdated,
+ EntityFilterAst::mock_empty(),
+ false,
+ )
+ .await?;
+
+ let ids: Vec<Uuid> = items.iter().map(|i| i.id()).collect();
+
+ // COALESCE(uh.updatedAt, item.updatedAt) DESC:
+ // chat-standalone no history -> updatedAt 2024-03-11
+ // doc-deep-pdf no history -> updatedAt 2024-03-10
+ // doc-mid-docx history 2024-03-08
+ // doc-task-no-status history 2024-03-07
+ // doc-standalone-txt history 2024-03-06
+ // doc-root-pdf history 2024-03-05
+ // doc-task-completed history 2024-03-04
+ // chat-root history 2024-03-03
+ // project-root history 2024-03-02
+ // project-deep history 2024-03-01
+ // chat-shared no history -> updatedAt 2024-02-18
+ // project-mid no history -> updatedAt 2024-02-11
+ // doc-shared-md no history -> updatedAt 2024-02-08
+ // doc-task-incomplete no history -> updatedAt 2024-02-06
+ let expected: Vec<Uuid> = [
+ DYN_CHAT_STANDALONE,
+ DYN_DOC_DEEP_PDF,
+ DYN_DOC_MID_DOCX,
+ DYN_DOC_TASK_NO_STATUS,
+ DYN_DOC_STANDALONE_TXT,
+ DYN_DOC_ROOT_PDF,
+ DYN_DOC_TASK_COMPLETED,
+ DYN_CHAT_ROOT,
+ DYN_PROJECT_ROOT,
+ DYN_PROJECT_DEEP,
+ DYN_CHAT_SHARED,
+ DYN_PROJECT_MID,
+ DYN_DOC_SHARED_MD,
+ DYN_DOC_TASK_INCOMPLETE,
+ ]
+ .iter()
+ .map(|s| uuid(s))
+ .collect();
+
+ assert_eq!(ids, expected, "ViewedUpdated sort order is wrong");
+ Ok(())
+}
+
+// ---- Access control & deleted items (3 tests) ----
+
+/// 5. Deleted doc and chat never appear in dynamic query results.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("dynamic_query_exhaustive")
+ )
+)]
+async fn test_dyn_deleted_items_excluded(db: PgPool) -> anyhow::Result<()> {
+ let items = dyn_fetch(
+ &db,
+ 50,
+ SimpleSortMethod::UpdatedAt,
+ EntityFilterAst::mock_empty(),
+ false,
+ )
+ .await?;
+
+ let ids: HashSet<Uuid> = items.iter().map(|i| i.id()).collect();
+
+ assert!(
+ !ids.contains(&uuid(DYN_DOC_DELETED)),
+ "Deleted document must not appear"
+ );
+ assert!(
+ !ids.contains(&uuid(DYN_CHAT_DELETED)),
+ "Deleted chat must not appear"
+ );
+
+ Ok(())
+}
+
+/// 6. Isolated project/doc/chat excluded for user-1 in dynamic query.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("dynamic_query_exhaustive")
+ )
+)]
+async fn test_dyn_access_control_excludes_isolated(db: PgPool) -> anyhow::Result<()> {
+ let items = dyn_fetch(
+ &db,
+ 50,
+ SimpleSortMethod::UpdatedAt,
+ EntityFilterAst::mock_empty(),
+ false,
+ )
+ .await?;
+
+ let ids: HashSet<Uuid> = items.iter().map(|i| i.id()).collect();
+
+ assert!(
+ !ids.contains(&uuid(DYN_PROJECT_ISOLATED)),
+ "Isolated project must not appear for user-1"
+ );
+ assert!(
+ !ids.contains(&uuid(DYN_DOC_ISOLATED)),
+ "Isolated doc must not appear for user-1"
+ );
+ assert!(
+ !ids.contains(&uuid(DYN_CHAT_ISOLATED)),
+ "Isolated chat must not appear for user-1"
+ );
+
+ Ok(())
+}
+
+/// 7. User-2 only sees isolated items through the dynamic query.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("dynamic_query_exhaustive")
+ )
+)]
+async fn test_dyn_user_isolation(db: PgPool) -> anyhow::Result<()> {
+ let items = dyn_fetch(
+ &db,
+ 50,
+ SimpleSortMethod::UpdatedAt,
+ EntityFilterAst::mock_empty(),
+ false,
+ )
+ .await?;
+
+ let ids: HashSet<Uuid> = items.iter().map(|i| i.id()).collect();
+
+ let expected: HashSet<Uuid> = [DYN_PROJECT_ISOLATED, DYN_DOC_ISOLATED, DYN_CHAT_ISOLATED]
+ .iter()
+ .map(|s| uuid(s))
+ .collect();
+
+ assert_eq!(
+ ids, expected,
+ "User-2 should only see isolated project, its doc, and its chat"
+ );
+
+ Ok(())
+}
+
+// ---- Filter types (3 tests) ----
+
+/// 8. Filter documents by owner (user-2) returns only doc-shared-md.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("dynamic_query_exhaustive")
+ )
+)]
+async fn test_dyn_filter_doc_by_owner(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{DocumentFilters, EntityFilters};
+
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ owners: vec!["macro|[email protected]".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = dyn_fetch(
+ &db,
+ 50,
+ SimpleSortMethod::UpdatedAt,
+ filters,
+ false,
+ )
+ .await?;
+
+ let doc_ids: Vec<Uuid> = items
+ .iter()
+ .filter_map(|i| match i {
+ SoupItem::Document(d) => Some(d.id),
+ _ => None,
+ })
+ .collect();
+
+ // Only doc-shared-md is owned by user-2 and accessible to user-1
+ assert_eq!(doc_ids.len(), 1, "Should get exactly 1 document");
+ assert_eq!(doc_ids[0], uuid(DYN_DOC_SHARED_MD));
+
+ // Chats and projects should still be present (unfiltered)
+ let chat_count = items
+ .iter()
+ .filter(|i| matches!(i, SoupItem::Chat(_)))
+ .count();
+ let project_count = items
+ .iter()
+ .filter(|i| matches!(i, SoupItem::Project(_)))
+ .count();
+ assert_eq!(chat_count, 3, "Should get all 3 chats");
+ assert_eq!(project_count, 3, "Should get all 3 projects");
+
+ Ok(())
+}
+
+/// 9. Filter documents by project ID returns only docs in that project.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("dynamic_query_exhaustive")
+ )
+)]
+async fn test_dyn_filter_doc_by_project(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{DocumentFilters, EntityFilters};
+
+ // Filter for documents in project-deep only
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ project_ids: vec![DYN_PROJECT_DEEP.to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = dyn_fetch(
+ &db,
+ 50,
+ SimpleSortMethod::UpdatedAt,
+ filters,
+ false,
+ )
+ .await?;
+
+ let doc_ids: Vec<Uuid> = items
+ .iter()
+ .filter_map(|i| match i {
+ SoupItem::Document(d) => Some(d.id),
+ _ => None,
+ })
+ .collect();
+
+ assert_eq!(doc_ids.len(), 1, "Should get exactly 1 document in deep");
+ assert_eq!(doc_ids[0], uuid(DYN_DOC_DEEP_PDF));
+
+ Ok(())
+}
+
+/// 10. Filter documents by multiple file types (pdf + docx).
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("dynamic_query_exhaustive")
+ )
+)]
+async fn test_dyn_filter_multiple_file_types(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{DocumentFilters, EntityFilters};
+
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ file_types: vec!["pdf".to_string(), "docx".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = dyn_fetch(
+ &db,
+ 50,
+ SimpleSortMethod::UpdatedAt,
+ filters,
+ false,
+ )
+ .await?;
+
+ let doc_ids: HashSet<Uuid> = items
+ .iter()
+ .filter_map(|i| match i {
+ SoupItem::Document(d) => Some(d.id),
+ _ => None,
+ })
+ .collect();
+
+ // Accessible pdf docs: doc-root-pdf, doc-deep-pdf
+ // Accessible docx docs: doc-mid-docx
+ let expected_docs: HashSet<Uuid> = [DYN_DOC_ROOT_PDF, DYN_DOC_MID_DOCX, DYN_DOC_DEEP_PDF]
+ .iter()
+ .map(|s| uuid(s))
+ .collect();
+
+ assert_eq!(
+ doc_ids, expected_docs,
+ "Should get exactly the pdf and docx documents"
+ );
+
+ Ok(())
+}
+
+// ---- Task completion & document fields (2 tests) ----
+
+/// 11. Task documents should have correct is_completed values.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("dynamic_query_exhaustive")
+ )
+)]
+async fn test_dyn_task_completion_status(db: PgPool) -> anyhow::Result<()> {
+ use models_soup::document::SoupDocumentSubType;
+
+ let items = dyn_fetch(
+ &db,
+ 50,
+ SimpleSortMethod::UpdatedAt,
+ EntityFilterAst::mock_empty(),
+ false,
+ )
+ .await?;
+
+ let items_map: std::collections::HashMap<Uuid, &SoupItem> =
+ items.iter().map(|i| (i.id(), i)).collect();
+
+ // Completed task
+ let doc = unwrap_enum!(items_map[&uuid(DYN_DOC_TASK_COMPLETED)], SoupItem::Document);
+ match &doc.sub_type {
+ Some(SoupDocumentSubType::Task { is_completed }) => {
+ assert!(is_completed, "Completed task should have is_completed=true");
+ }
+ other => panic!("Expected Task sub_type, got {:?}", other),
+ }
+
+ // Incomplete task (status = In Progress)
+ let doc = unwrap_enum!(
+ items_map[&uuid(DYN_DOC_TASK_INCOMPLETE)],
+ SoupItem::Document
+ );
+ match &doc.sub_type {
+ Some(SoupDocumentSubType::Task { is_completed }) => {
+ assert!(
+ !is_completed,
+ "Incomplete task should have is_completed=false"
+ );
+ }
+ other => panic!("Expected Task sub_type, got {:?}", other),
+ }
+
+ // Task with no status property
+ let doc = unwrap_enum!(items_map[&uuid(DYN_DOC_TASK_NO_STATUS)], SoupItem::Document);
+ match &doc.sub_type {
+ Some(SoupDocumentSubType::Task { is_completed }) => {
+ assert!(
+ !is_completed,
+ "Task with no status should have is_completed=false"
+ );
+ }
+ other => panic!("Expected Task sub_type, got {:?}", other),
+ }
+
+ // Non-task document
+ let doc = unwrap_enum!(items_map[&uuid(DYN_DOC_ROOT_PDF)], SoupItem::Document);
+ assert!(
+ doc.sub_type.is_none(),
+ "Non-task document should have sub_type=None"
+ );
+
+ Ok(())
+}
+
+/// 12. Document fields (sha, file_type, viewed_at, project_id) populated correctly.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("dynamic_query_exhaustive")
+ )
+)]
+async fn test_dyn_document_fields(db: PgPool) -> anyhow::Result<()> {
+ let items = dyn_fetch(
+ &db,
+ 50,
+ SimpleSortMethod::UpdatedAt,
+ EntityFilterAst::mock_empty(),
+ false,
+ )
+ .await?;
+
+ let items_map: std::collections::HashMap<Uuid, &SoupItem> =
+ items.iter().map(|i| (i.id(), i)).collect();
+
+ // doc-root-pdf: pdf, sha-root-pdf, has history, in project-root
+ let doc = unwrap_enum!(items_map[&uuid(DYN_DOC_ROOT_PDF)], SoupItem::Document);
+ assert_eq!(doc.file_type.as_deref(), Some("pdf"));
+ assert_eq!(doc.sha.as_deref(), Some("sha-root-pdf"));
+ assert!(doc.viewed_at.is_some(), "doc-root-pdf has history");
+ assert_eq!(doc.project_id, Some(uuid(DYN_PROJECT_ROOT)));
+
+ // doc-mid-docx: docx, sha-mid-docx, has history, in project-mid
+ let doc = unwrap_enum!(items_map[&uuid(DYN_DOC_MID_DOCX)], SoupItem::Document);
+ assert_eq!(doc.file_type.as_deref(), Some("docx"));
+ assert_eq!(doc.sha.as_deref(), Some("sha-mid-docx"));
+ assert!(doc.viewed_at.is_some(), "doc-mid-docx has history");
+ assert_eq!(doc.project_id, Some(uuid(DYN_PROJECT_MID)));
+
+ // doc-standalone-txt: txt, sha-standalone-txt, has history, no project
+ let doc = unwrap_enum!(items_map[&uuid(DYN_DOC_STANDALONE_TXT)], SoupItem::Document);
+ assert_eq!(doc.file_type.as_deref(), Some("txt"));
+ assert_eq!(doc.sha.as_deref(), Some("sha-standalone-txt"));
+ assert!(doc.viewed_at.is_some(), "doc-standalone-txt has history");
+ assert_eq!(doc.project_id, None);
+
+ // doc-deep-pdf: pdf, no history
+ let doc = unwrap_enum!(items_map[&uuid(DYN_DOC_DEEP_PDF)], SoupItem::Document);
+ assert_eq!(doc.file_type.as_deref(), Some("pdf"));
+ assert!(doc.viewed_at.is_none(), "doc-deep-pdf has no history");
+ assert_eq!(doc.project_id, Some(uuid(DYN_PROJECT_DEEP)));
+
+ // doc-shared-md: md, owned by user-2
+ let doc = unwrap_enum!(items_map[&uuid(DYN_DOC_SHARED_MD)], SoupItem::Document);
+ assert_eq!(doc.file_type.as_deref(), Some("md"));
+ assert_eq!(doc.sha.as_deref(), Some("sha-shared-md"));
+ assert_eq!(doc.project_id, Some(uuid(DYN_PROJECT_ROOT)));
+
+ Ok(())
+}
+
+// ---- Pagination (2 tests) ----
+
+/// 13. Walk all items limit=1, verify no dupes, matches bulk fetch order.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("dynamic_query_exhaustive")
+ )
+)]
+async fn test_dyn_paginate_one_at_a_time(db: PgPool) -> anyhow::Result<()> {
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let sort = SimpleSortMethod::UpdatedAt;
+ let filters = EntityFilterAst::mock_empty();
+
+ let mut all_ids: Vec<Uuid> = Vec::new();
+ let mut current_query: Query<Uuid, SimpleSortMethod, EntityFilterAst> =
+ Query::Sort(sort, filters.clone());
+
+ loop {
+ let result = expanded_dynamic_cursor_soup(
+ &db,
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 1,
+ cursor: current_query,
+ exclude_frecency: false,
+ },
+ )
+ .await?
+ .into_iter()
+ .paginate_on(1, sort)
+ .filter_on(filters.clone())
+ .into_page();
+
+ all_ids.extend(result.items.iter().map(|i| i.id()));
+
+ match result.next_cursor {
+ Some(cursor) => {
+ let decoded = cursor.decode_json().unwrap();
+ current_query = Query::Cursor(models_pagination::Cursor {
+ id: decoded.id,
+ limit: decoded.limit,
+ val: decoded.val,
+ filter: decoded.filter,
+ });
+ }
+ None => break,
+ }
+ }
+
+ assert_eq!(all_ids.len(), 14, "Should walk through all 14 items");
+
+ let unique: HashSet<Uuid> = all_ids.iter().copied().collect();
+ assert_eq!(
+ unique.len(),
+ 14,
+ "No duplicates when paginating one at a time"
+ );
+
+ // Verify order matches a single large fetch
+ let all_at_once = dyn_fetch(
+ &db,
+ 50,
+ sort,
+ EntityFilterAst::mock_empty(),
+ false,
+ )
+ .await?;
+ let expected_ids: Vec<Uuid> = all_at_once.iter().map(|i| i.id()).collect();
+ assert_eq!(
+ all_ids, expected_ids,
+ "Paginated order should match single-fetch order"
+ );
+
+ Ok(())
+}
+
+/// 14. Paginate through filtered results, verify filter consistency and no dupes.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("dynamic_query_exhaustive")
+ )
+)]
+async fn test_dyn_paginate_with_filters(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{DocumentFilters, EntityFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let sort = SimpleSortMethod::CreatedAt;
+ let page_size: u16 = 3;
+
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ file_types: vec!["pdf".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let make_filters = || {
+ EntityFilterAst::new_from_filters(entity_filters.clone())
+ .unwrap()
+ .unwrap()
+ };
+
+ let mut all_items: Vec<SoupItem> = Vec::new();
+ let mut current_query: Query<Uuid, SimpleSortMethod, EntityFilterAst> =
+ Query::Sort(sort, make_filters());
+
+ loop {
+ let result = expanded_dynamic_cursor_soup(
+ &db,
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: page_size,
+ cursor: current_query,
+ exclude_frecency: false,
+ },
+ )
+ .await?
+ .into_iter()
+ .paginate_on(page_size as usize, sort)
+ .filter_on(make_filters())
+ .into_page();
+
+ all_items.extend(result.items);
+
+ match result.next_cursor {
+ Some(cursor) => {
+ let decoded = cursor.decode_json()?;
+ current_query = Query::Cursor(models_pagination::Cursor {
+ id: decoded.id,
+ limit: decoded.limit,
+ val: decoded.val,
+ filter: decoded.filter,
+ });
+ }
+ None => break,
+ }
+ }
+
+ // Verify all documents are PDFs (filter consistency)
+ for item in &all_items {
+ if let SoupItem::Document(doc) = item {
+ assert_eq!(
+ doc.file_type.as_deref(),
+ Some("pdf"),
+ "All documents should be PDFs"
+ );
+ }
+ }
+
+ // Verify no duplicates
+ let all_ids: Vec<Uuid> = all_items.iter().map(|i| i.id()).collect();
+ let unique: HashSet<Uuid> = all_ids.iter().copied().collect();
+ assert_eq!(
+ all_ids.len(),
+ unique.len(),
+ "Should have no duplicate items across pages"
+ );
+
+ // Should get 2 pdf docs + 3 chats + 3 projects = 8 total
+ let doc_count = all_items
+ .iter()
+ .filter(|i| matches!(i, SoupItem::Document(_)))
+ .count();
+ assert_eq!(doc_count, 2, "Should get exactly 2 PDF documents");
+
+ Ok(())
+}
+
+// ---- Frecency (2 tests) ----
+
+/// 15. exclude_frecency=true removes items with frecency records.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("dynamic_query_exhaustive")
+ )
+)]
+async fn test_dyn_exclude_frecency(db: PgPool) -> anyhow::Result<()> {
+ let items = dyn_fetch(
+ &db,
+ 50,
+ SimpleSortMethod::UpdatedAt,
+ EntityFilterAst::mock_empty(),
+ true, // exclude_frecency
+ )
+ .await?;
+
+ let ids: HashSet<Uuid> = items.iter().map(|i| i.id()).collect();
+
+ // doc-root-pdf and chat-root have frecency records and should be excluded
+ assert!(
+ !ids.contains(&uuid(DYN_DOC_ROOT_PDF)),
+ "doc-root-pdf should be excluded (has frecency)"
+ );
+ assert!(
+ !ids.contains(&uuid(DYN_CHAT_ROOT)),
+ "chat-root should be excluded (has frecency)"
+ );
+
+ // All other accessible items should still be present (14 - 2 = 12)
+ assert_eq!(
+ items.len(),
+ 12,
+ "Should get 12 items after frecency exclusion"
+ );
+
+ // Verify a non-frecency item is still present
+ assert!(
+ ids.contains(&uuid(DYN_DOC_MID_DOCX)),
+ "doc-mid-docx should still be present"
+ );
+
+ Ok(())
+}
+
+/// 16. exclude_frecency works with all 4 sort methods.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("dynamic_query_exhaustive")
+ )
+)]
+async fn test_dyn_exclude_frecency_all_sort_methods(db: PgPool) -> anyhow::Result<()> {
+ let frecency_ids: HashSet<Uuid> = [DYN_DOC_ROOT_PDF, DYN_CHAT_ROOT]
+ .iter()
+ .map(|s| uuid(s))
+ .collect();
+
+ for sort in [
+ SimpleSortMethod::UpdatedAt,
+ SimpleSortMethod::CreatedAt,
+ SimpleSortMethod::ViewedAt,
+ SimpleSortMethod::ViewedUpdated,
+ ] {
+ let items = dyn_fetch(
+ &db,
+ 50,
+ sort,
+ EntityFilterAst::mock_empty(),
+ true,
+ )
+ .await?;
+
+ let ids: HashSet<Uuid> = items.iter().map(|i| i.id()).collect();
+
+ for fid in &frecency_ids {
+ assert!(
+ !ids.contains(fid),
+ "Sort {:?}: item {} should be excluded by frecency filter",
+ sort,
+ fid
+ );
+ }
+
+ assert_eq!(
+ items.len(),
+ 12,
+ "Sort {:?}: should get 12 items after frecency exclusion",
+ sort
+ );
+ }
+
+ Ok(())
+}
+
+// ---- Edge cases (1 test) ----
+
+/// 17. All 3 entity types filtered to nothing returns empty vec.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("dynamic_query_exhaustive")
+ )
+)]
+async fn test_dyn_all_types_filtered_to_empty(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{ChatFilters, DocumentFilters, EntityFilters, ProjectFilters};
+
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ document_ids: vec!["00000000-0000-0000-0000-000000000000".to_string()],
+ ..Default::default()
+ },
+ chat_filters: ChatFilters {
+ chat_ids: vec!["00000000-0000-0000-0000-000000000000".to_string()],
+ ..Default::default()
+ },
+ project_filters: ProjectFilters {
+ project_ids: vec!["00000000-0000-0000-0000-000000000000".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = dyn_fetch(
+ &db,
+ 50,
+ SimpleSortMethod::UpdatedAt,
+ filters,
+ false,
+ )
+ .await?;
+
+ assert!(
+ items.is_empty(),
+ "All types filtered to nothing should return empty"
+ );
+
+ Ok(())
+}