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.

perf(soup): check initiative listing access per initiative (#8592)

teo6407408ea5a9
diff --git a/crates/soup/AGENTS.md b/crates/soup/AGENTS.md
index bc8757b37d..7d1027179b 100644
--- a/crates/soup/AGENTS.md
+++ b/crates/soup/AGENTS.md
@@ -67,11 +67,13 @@ rows, initiatives, ...) and get back a single unified, paginated result.
`expanded` path instead.
- `candidate_gates.rs` encodes access-gate SQL shared across repo queries;
changing it changes what every entity kind can return.
-- Queries over a known id list (`*/by_ids.rs`, hydration) check access per id
- with `EXISTS` on `entity_access`, matching sources with
- `= ANY(ARRAY(SELECT ...))` so they are collected once rather than semi-joined
- per row. Building the caller's whole accessible set first scans all of
- `entity_access`, so cost grows with the table, not the page.
+- Queries over a known id list (`*/by_ids.rs`, hydration) and the initiative
+ listing (`initiative_access_clause`) check access per row with `EXISTS` on
+ `entity_access`, matching sources with `= ANY(ARRAY(SELECT ...))` so they are
+ collected once rather than semi-joined per row. Building the caller's whole
+ accessible set first scans `entity_access` once per source, so cost grows
+ with the table and the caller's channels, not the page. A listing `EXISTS`
+ also needs `PER_CANDIDATE`, or Postgres hashes it back into the whole set.
## Related
diff --git a/crates/soup/src/outbound/pg_soup_repo/candidate_gates.rs b/crates/soup/src/outbound/pg_soup_repo/candidate_gates.rs
index 503cbcc6cf..c4625e3baf 100644
--- a/crates/soup/src/outbound/pg_soup_repo/candidate_gates.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/candidate_gates.rs
@@ -48,7 +48,7 @@ fn exact_subtree_sql<T>(expr: &Expr<T>, fold: &impl Fn(&T) -> Option<String>) ->
/// against every candidate the outer scan could produce rather than the
/// page's `LIMIT`. For these gates that hash is the user's whole accessible
/// set. An `OFFSET` keeps the subquery per candidate.
-const PER_CANDIDATE: &str = "OFFSET 0";
+pub(super) const PER_CANDIDATE: &str = "OFFSET 0";
/// Renders the implied conjuncts of `tree` that `fold` knows how to express
/// as ` AND ...` clauses, in tree order.
diff --git a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/initiative.rs b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/initiative.rs
index 4f67aa2d81..4a6cdb24c0 100644
--- a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/initiative.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/initiative.rs
@@ -6,19 +6,28 @@ use item_filters::ast::initiative::InitiativeLiteral;
use models_pagination::SimpleSortMethod;
use system_properties::SystemPropertyKey;
-use super::{access_semi_join, sql_string_literal, top_needs_user_history};
+use super::{sql_string_literal, top_needs_user_history};
+use crate::outbound::pg_soup_repo::candidate_gates::PER_CANDIDATE;
/// The initiative listing policy: explicit grants and the owner's team link.
/// Public links do not enumerate otherwise undiscovered initiatives.
+///
+/// Both checks run per initiative against sources collected once into an
+/// array, so cost follows the initiative count. Joining `user_source_ids`
+/// instead scales with the caller's channels.
pub(in crate::outbound::pg_soup_repo) fn initiative_access_clause() -> String {
format!(
- r#"({} OR EXISTS (
+ r#"(EXISTS (
+ SELECT 1 FROM entity_access ea
+ WHERE ea.entity_id = i.id AND ea.entity_type = 'initiative'
+ AND ea.source_id = ANY(ARRAY(SELECT source_id FROM user_source_ids))
+ {PER_CANDIDATE}
+ ) OR EXISTS (
SELECT 1 FROM "SharePermission" sp
JOIN team_user owner_team ON owner_team.user_id = i.owner_user_id
WHERE sp.id = i.share_permission_id AND sp."linkShare" = 'TEAM'
- AND owner_team.team_id::text IN (SELECT source_id FROM user_source_ids)
- ))"#,
- access_semi_join("i.id::text", "initiative")
+ AND owner_team.team_id::text = ANY(ARRAY(SELECT source_id FROM user_source_ids))
+ ))"#
)
}
diff --git a/crates/soup/src/outbound/pg_soup_repo/initiative/test.rs b/crates/soup/src/outbound/pg_soup_repo/initiative/test.rs
index 8cf422f945..c0c0b41e8c 100644
--- a/crates/soup/src/outbound/pg_soup_repo/initiative/test.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/initiative/test.rs
@@ -120,6 +120,77 @@ async fn initiatives_access_cursor_and_hydration(pool: PgPool) -> anyhow::Result
Ok(())
}
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("mixed_items_expanded")
+ ),
+ fixtures("test/initiatives.sql"),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn initiative_listing_and_candidate_gate_share_access_rules(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ // Visible: 1 direct share, 2 active channel, 3 team grant, 4 owner's team
+ // link, 7 owner, 8 inherited from a folder. Hidden: 5 left channel, 6 no grant.
+ let listed = expanded_dynamic_cursor_soup(
+ &pool,
+ ExpandedDynamicCursorArgs {
+ user_id: user(),
+ limit: 20,
+ cursor: Query::Sort(SimpleSortMethod::UpdatedAt, filters()),
+ exclude_frecency: false,
+ },
+ )
+ .await?;
+ assert_eq!(
+ listed.iter().map(Identify::id).collect::<Vec<_>>(),
+ vec![
+ Uuid::from_u128(0xad000000000000000000000000000004),
+ Uuid::from_u128(0xad000000000000000000000000000003),
+ Uuid::from_u128(0xad000000000000000000000000000002),
+ Uuid::from_u128(0xad000000000000000000000000000001),
+ Uuid::from_u128(0xad000000000000000000000000000008),
+ Uuid::from_u128(0xad000000000000000000000000000007),
+ ]
+ );
+
+ let gated: Vec<Uuid> = sqlx::query_scalar(&format!(
+ r#"WITH user_source_ids AS (
+ SELECT cp.channel_id::text AS source_id FROM comms_channel_participants cp
+ WHERE cp.user_id = $1 AND cp.left_at IS NULL
+ UNION ALL
+ SELECT t.team_id::text FROM team_user t WHERE t.user_id = $1
+ UNION ALL
+ SELECT $1
+ )
+ SELECT candidate.id FROM unnest($2::uuid[]) candidate(id)
+ WHERE {}
+ ORDER BY candidate.id"#,
+ crate::outbound::pg_soup_repo::candidate_gates::initiative_gate("candidate.id::text", None)
+ ))
+ .bind(user().as_ref())
+ .bind(
+ (1..=8)
+ .map(|n| Uuid::from_u128(0xad000000000000000000000000000000 + n))
+ .collect::<Vec<_>>(),
+ )
+ .fetch_all(&pool)
+ .await?;
+ assert_eq!(
+ gated,
+ vec![
+ Uuid::from_u128(0xad000000000000000000000000000001),
+ Uuid::from_u128(0xad000000000000000000000000000002),
+ Uuid::from_u128(0xad000000000000000000000000000003),
+ Uuid::from_u128(0xad000000000000000000000000000004),
+ Uuid::from_u128(0xad000000000000000000000000000007),
+ Uuid::from_u128(0xad000000000000000000000000000008),
+ ]
+ );
+ Ok(())
+}
+
#[sqlx::test(
fixtures(
path = "../../../../../macro_db_client/fixtures",
@@ -148,8 +219,8 @@ async fn initiatives_grouping_and_property_enrichment(pool: PgPool) -> anyhow::R
)
.await?
.collect::<Vec<_>>();
- assert_eq!(rows.len(), 4);
- assert_eq!(rows[0].total_group_count, 4);
+ assert_eq!(rows.len(), 6);
+ assert_eq!(rows[0].total_group_count, 6);
let enriched = crate::outbound::pg_soup_repo::populate_properties(
&pool,
user(),
diff --git a/crates/soup/src/outbound/pg_soup_repo/initiative/test/initiatives.sql b/crates/soup/src/outbound/pg_soup_repo/initiative/test/initiatives.sql
index 6ea78352fb..5f1c889b4c 100644
--- a/crates/soup/src/outbound/pg_soup_repo/initiative/test/initiatives.sql
+++ b/crates/soup/src/outbound/pg_soup_repo/initiative/test/initiatives.sql
@@ -26,6 +26,15 @@ INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, acces
('ad000000-0000-0000-0000-000000000003', 'initiative', 'macro|[email protected]', 'user', 'view'),
-- Left-channel grants and an inaccessible row must never leak.
('ad000000-0000-0000-0000-000000000005', 'initiative', 'ae000000-0000-0000-0000-000000000003', 'channel', 'view');
+-- Row 7 is owned by the viewer; row 8 is granted through a shared folder.
+-- Both sort after rows 1-4.
+INSERT INTO "SharePermission" (id) VALUES ('soup-initiative-share-7'), ('soup-initiative-share-8');
+INSERT INTO initiative (id, name, owner_user_id, share_permission_id, created_at, updated_at) VALUES
+('ad000000-0000-0000-0000-000000000007', 'Launch 7', 'macro|[email protected]', 'soup-initiative-share-7', '2026-01-01', '2026-01-01'),
+('ad000000-0000-0000-0000-000000000008', 'Launch 8', 'macro|[email protected]', 'soup-initiative-share-8', '2026-01-01', '2026-01-01');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id) VALUES
+('ad000000-0000-0000-0000-000000000007', 'initiative', 'macro|[email protected]', 'user', 'owner', NULL),
+('ad000000-0000-0000-0000-000000000008', 'initiative', 'macro|[email protected]', 'user', 'view', 'aaaaaaaa-ffff-ffff-ffff-ffffffffffff');
INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
SELECT replace(id::text, 'ad000000', 'ab000000')::uuid, id::text, 'INITIATIVE', '00000001-0000-0000-0000-000000000002',
'{"type":"SelectOption","value":["00000001-0000-0000-0002-000000000001"]}'::jsonb